body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I love the "projections" introduced by the ranges library, and I would like to use them in algorithms that haven't been rangeyfied yet.</p>
<p>I had the idea of using them through a function like this:</p>
<pre><code>#include <utility>
#include <functional>
template<typename TFn, typename TProj = std::identity>
auto
constexpr proj(TFn &&Fn, TProj &&Proj = {})
{
return [&Fn, &Proj]<typename... TArgs>(TArgs &&...Args)
{
return std::invoke(std::forward<TFn>(Fn),
std::invoke(std::forward<TProj>(Proj), std::forward<TArgs>(Args))...);
};
}
</code></pre>
<p>This function enables writting, for example:</p>
<pre><code> std::sort(std::execution::par_unseq, v.begin(), v.end(), proj(std::less{}, &Pair::Key));
</code></pre>
<p>instead of:</p>
<pre><code> std::sort(std::execution::par_unseq, v.begin(), v.end(), [](auto const &lhs, auto const &rhs) { return lhs.Key < rhs.Key; });
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-24T17:50:05.010",
"Id": "506231",
"Score": "2",
"body": "Welcome to the Code Review Community where we review working code from a project you have written and suggest improvements for that working code. This does not seem to be a review of working code and appears to be too theoretical in nature."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-24T18:49:26.033",
"Id": "506236",
"Score": "1",
"body": "@pacmaninbw The function `proj` does work, and IMHO is a useful piece of a library. I've just seen a 2D vector template class in another question, which is just another library component. What's the difference? I realize that maybe the example I posted was misleadingly too long, so that I've simplified it to just show the usefulness of the function. Please let me know if now it looks better and otherwise I'll delete the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-24T20:17:19.367",
"Id": "506239",
"Score": "2",
"body": "Simplification is actually worse. We need to see the code in its natural habitat. Please take a look at our [FAQ on asking questions](https://codereview.meta.stackexchange.com/q/2436/52915)."
}
] |
[
{
"body": "<h1>Design review</h1>\n<p>I don’t think you gave a lot of thought to what this library would be actually <em>useful</em> for.</p>\n<p>Let me start by just considering the idea of <code>proj()</code> in complete isolation, ignoring any real-use context, and just considering it as a clever trick. From that perspective, I’d have to say that <code>proj()</code> is not a bad idea… but perhaps not the best way to go about it.</p>\n<p>Here’s what a ranges call to <code>sort()</code> might look like:</p>\n<pre><code>std::ranges::sort(b, e, {}, &Pair::Key);\n</code></pre>\n<p>Here’s what <code>proj()</code> promises, at best:</p>\n<pre><code>std::sort(b, e, proj(std::less{}, &Pair::Key));\n</code></pre>\n<p>Here’s what else is possible in C++17, and possibly even before if you’re willing to put in the work of re-implementing <code>std::invoke</code>, etc. (of course it’s also possible in C++20, but… we’ll get to that issue shortly):</p>\n<pre><code>myns::sort(b, e, {}, &Pair::Key);\n</code></pre>\n<p>That is, you could implement a wrapper around <code>std::sort()</code> that handles the projection transparently.</p>\n<p>For the user, that’s shorter, simpler, and doesn’t require manually specifying the comparator.</p>\n<p>Not to mention that when I <em>can</em> advance to C++20 and use the full power of <code>std::ranges</code>, all I need to do (very basically) is a find-replace for <code>myns</code> to <code>std::ranges</code>. If I had these little <code>proj()</code> sub-calls everywhere, the code transform becomes <em>MUCH</em> more complex, and possibly tedious and/or dangerous.</p>\n<p>And while you’re at it, why not implement <code>myns::sort()</code> as a <a href=\"https://brevzin.github.io/c++/2020/12/19/cpo-niebloid/#niebloids-solve-undesired-adl\" rel=\"nofollow noreferrer\">neibloid</a>, to get all the sweet, sweet benefits that go along with that?</p>\n<p>So if you <em>really</em> want the benefits of projections, why wouldn’t you do that?</p>\n<p>Yes, I realize I’m basically saying “re-implement <code>std::ranges</code>”. As a halfway solution <code>proj()</code> only halfway satisfies. What’s the point of that? If you’re going to implement a library tool to make coders’ lives easier, why half-ass it? Who benefits from a mediocre solution? I guess the person writing the library gets to save on some work… but the whole point of library writing is that the library writer is taking on extra work so library <em>users</em> don’t have to. Making things easier for the library <em>writer</em> is silly. You should be concentrating on making things easier for the <em>users</em>.</p>\n<p>And by the way, there are a bunch more complications to making something like <code>proj()</code> generally usable that I haven’t mentioned. Like, you’ve created a variant that works with most of the standard algorithms… but it won’t work with <code>std::find()</code> (no predicate, so no <code>Fn</code>). Won’t work with <code>std::merge()</code> (has a predicate, but has <em>two</em> projections). By the time you sort all that out, and test it all rigorously enough to show that it’s trustworthy in production code, you might as well have just used <a href=\"https://ericniebler.github.io/range-v3/\" rel=\"nofollow noreferrer\"><code>range-v3</code></a>.</p>\n<p>Except… and this is the biggest issue with this whole idea…</p>\n<p>This code won’t even compile in C++17. It needs C++20. C++20… where… <code>std::ranges</code> already exists.</p>\n<p><em><strong>So who exactly is this library for?</strong></em></p>\n<ul>\n<li>It can’t be for C++17 (or before) users. (Won’t compile.)</li>\n<li>It makes no sense for C++20 (and later) users. (Because if they want a projection in a legacy algorithm, they can just use the <code>std::ranges</code> version. In your example, <code>std::ranges::sort()</code>.)</li>\n</ul>\n<p>Are you targeting the hypothetical subset of users who are targeting C++20 with their project, but are using a C++20 compiler/library that has lambda templates, <code>std::identity</code>, and <code>constexpr</code> <code>std::invoke</code>… but <em>not</em> the ranges algorithms? That’s a bizarre target group, to say the least. I mean, who targets a C++ version—or uses a specific feature, like projections—without a compiler/library that actually supports it? Not to mention it’s a rather ephemeral group, because presumably if they’re targeting C++20, they could just use <code>std::ranges</code> as soon as the features they need become available in their chose compiler/library, making <code>proj()</code> just a weird stop-gap they would use for a while, then have to weed out of their code base later.</p>\n<p>The bottom line is: <code>proj()</code> makes no sense. The only people who <em>could</em> use it… don’t really need it.</p>\n<p>(Or, <em>AT BEST</em>, they could maybe use it <em>NOW</em>, for the brief period when their chosen platform supports everything needed to make <code>proj()</code> work, but doesn’t include <code>std::ranges</code>. But, frankly, I’d rather write the lambda than use a mysterious 3rd-party library that’s only going to be useful for a few months then become a legacy maintenance burden.)</p>\n<p>From where I’m sitting, this looks like a case of <a href=\"https://xkcd.com/356/\" rel=\"nofollow noreferrer\">nerd sniping</a>. A neat little theoretical problem became so distracting by its intellectual challenge, that you completely ignored the surrounding real-world problems that are, in point of fact, much more important.</p>\n<h1>Code review</h1>\n<p>There’s not much code to review, of course, but….</p>\n<pre><code>auto\nconstexpr proj(//...\n</code></pre>\n<p>It’s pretty bizarre to write the <code>constexpr</code> after the <code>auto</code>. I’ve never seen that done before. I can’t see any sensible reason to adopt this style; it’s only likely to cause confusion.</p>\n<pre><code>constexpr proj(TFn &&Fn, TProj &&Proj = {})\n</code></pre>\n<p>Putting the type modifiers next to the variable name, rather than with the type, is a C convention, not a C++ convention. In C++, types matter more, so it makes more sense to say <code>TFn&& Fn</code>.</p>\n<p>Also, it is a little peculiar to name <em>variables</em> with UpperCamelCase. UpperCamelCase is usually reserved for template argument names. In other words, <code>TFn&& fn</code> is more conventional.</p>\n<pre><code>template<typename TFn, typename TProj = std::identity>\nauto\nconstexpr proj(TFn &&Fn, TProj &&Proj = {})\n{\n return [&Fn, &Proj]<typename... TArgs>(TArgs &&...Args)\n {\n return std::invoke(std::forward<TFn>(Fn),\n std::invoke(std::forward<TProj>(Proj), std::forward<TArgs>(Args))...);\n };\n}\n</code></pre>\n<p>The thing that bothers me most about this function is that you:</p>\n<ol>\n<li>take the two function arguments as forwarding references</li>\n<li>place them into the closures as lvalue references; then</li>\n<li>forward them within the closure.</li>\n</ol>\n<p>Now, I will admit here that I haven’t sat down and reasoned this through as hard as it really deserves (because it’s late, and because I don’t see the point of the function in any case), but even from a cursory inspection it <em>smells</em> wrong. The smelly part is that you “forget” you’re dealing with forwarding references on that second step.</p>\n<p>If the two parameters are lvalues, then no harm, no foul. All the forwarding references will collapse to lvalue references, and the <code>forward()</code>s will degenerate to… well, nothing, effectively; just lvalue references. So you have lvalue references all the way through. All cool.</p>\n<p>But if a parameter is an rvalue, then the <code>forward()</code>s will degrade to rvalue references, and <em>may</em> end up <em>moving</em> the argument. So imagine you have a call to, say, <code>sort()</code>, where <code>proj()</code> has been given an rvalue function object (for either parameter, doesn’t matter). On the first execution of the comparator—that is, the first time that lambda <code>proj()</code> returns is called—it will <em>move</em> the function object… leaving it in a moved-from state… so the second time the comparator/lambda is executed, it’s using an “empty” function object. Exactly what damage this will cause depends on what using a “moved-from” function object means, which will depend on the function object type. But in any case, it’s not good.</p>\n<p>Okay, put simply:</p>\n<ul>\n<li>You have correctly taken the function arguments as forwarding references…</li>\n<li>… and you have correctly perfect-forwarded them in the <code>invoke()</code> expressions…</li>\n<li>… but you have <em><strong>NOT</strong></em> perfect-forwarded them in the lambda capture.</li>\n</ul>\n<p>You need perfectly-forwarded lambda captures. That is <em>NOT</em> trivial… but not <em>too</em> hard (tip: use <code>std::tuple</code> and a mother-ton of <code>decltype(TFn)</code>, etc.; don’t forget to mark the lambda <code>mutable</code>).</p>\n<h1>Summary</h1>\n<p>As an experiment to explore stuff like projections and perfect-forwarding, this is actually a really neat idea.</p>\n<p>As a practical library… I’m not seeing it. Just about the only people who could use it won’t need it. And the tiny demographic who could use it, but who can’t use the superior <code>std::ranges</code> solution, would be unwise to use it (better to wait until their platform supports <code>std::ranges</code>).</p>\n<p>The implementation is sound but for that one tricky hiccup: You have perfectly-forwarded everything except the lambda captures. Fix that, and I <em>think</em> it should be a sound implementation. For full practical usability (such as it is), you’d need a couple of overloads for cases not covered by a single predicate and a single projection (for example, an overload without a predicate, for things like <code>std::find()</code>, <code>std::count()</code>, <code>std::remove()</code>, etc.; plus a few other overloads for the more esoteric cases), but once you’ve got the one working, that should be no problem.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-25T08:23:18.117",
"Id": "506266",
"Score": "0",
"body": "Thanks for the review! I want this function mostly for parallel algorithms, which I believe won't be rangeyfied until at least C++26. You're right that the perfect forwarding of the functors is either useless or simply plain wrong. I misread https://stackoverflow.com/a/26831637"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-25T11:33:11.177",
"Id": "506275",
"Score": "0",
"body": "\"It’s pretty bizarre to write the constexpr after the auto\" I would also not write it that way for constexpr but it's conistent to C++'s clockwise rule. Good answer though!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T19:07:59.110",
"Id": "506389",
"Score": "0",
"body": "I wouldn’t recommend using anything complicated—anything that hides what’s going on or buries it in layers of indirection—with parallel algorithms… but then, I wouldn’t recommend using parallel algorithms at all, so… ."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-25T03:41:27.227",
"Id": "256425",
"ParentId": "256413",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "256425",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-24T15:17:38.477",
"Id": "256413",
"Score": "3",
"Tags": [
"c++",
"c++20",
"stl"
],
"Title": "Function to use projections in legacy algorithms"
}
|
256413
|
<p>Has anyone an idea how to change the planning(self, sx, sy, gx, gy)-method to save computing time? I'm new to NumPy and don't know how to use it effectively yet, but I heard it could also be a good solution.</p>
<pre><code>import math
import matplotlib.pyplot as plt
show_animation = True
class AStarPlanner:
def __init__(self, ox, oy, resolution, rr):
"""
Initialize grid map for a star planning
ox: x position list of Obstacles [m]
oy: y position list of Obstacles [m]
resolution: grid resolution [m]
rr: robot radius[m]
"""
self.resolution = resolution
self.rr = rr
self.min_x, self.min_y = 0, 0
self.max_x, self.max_y = 0, 0
self.obstacle_map = None
self.x_width, self.y_width = 0, 0
self.motion = self.get_motion_model()
self.calc_obstacle_map(ox, oy)
class Node:
def __init__(self, x, y, cost, parent_index):
self.x = x # index of grid
self.y = y # index of grid
self.cost = cost
self.parent_index = parent_index
def __str__(self):
return str(self.x) + "," + str(self.y) + "," + str(
self.cost) + "," + str(self.parent_index)
def planning(self, sx, sy, gx, gy):
"""
A star path search
input:
s_x: start x position [m]
s_y: start y position [m]
gx: goal x position [m]
gy: goal y position [m]
output:
rx: x position list of the final path
ry: y position list of the final path
"""
start_node = self.Node(self.calc_xy_index(sx, self.min_x),
self.calc_xy_index(sy, self.min_y), 0.0, -1)
goal_node = self.Node(self.calc_xy_index(gx, self.min_x),
self.calc_xy_index(gy, self.min_y), 0.0, -1)
open_set, closed_set = dict(), dict()
open_set[self.calc_grid_index(start_node)] = start_node
while 1:
if len(open_set) == 0:
print("Open set is empty..")
break
c_id = min(
open_set,
key=lambda o: open_set[o].cost + self.calc_heuristic(goal_node,
open_set[
o]))
current = open_set[c_id]
if current.x == goal_node.x and current.y == goal_node.y:
print("Found goal")
goal_node.parent_index = current.parent_index
goal_node.cost = current.cost
break
# Remove the item from the open set
del open_set[c_id]
# Add it to the closed set
closed_set[c_id] = current
# expand_grid search grid based on motion model
for i, _ in enumerate(self.motion):
node = self.Node(current.x + self.motion[i][0],
current.y + self.motion[i][1],
current.cost + self.motion[i][2], c_id)
n_id = self.calc_grid_index(node)
# If the node is not safe, do nothing
if not self.verify_node(node):
continue
if n_id in closed_set:
continue
if n_id not in open_set:
open_set[n_id] = node # discovered a new node
else:
if open_set[n_id].cost > node.cost:
# This path is the best until now. record it
open_set[n_id] = node
rx, ry = self.calc_final_path(goal_node, closed_set)
return rx, ry
def calc_final_path(self, goal_node, closed_set):
# generate final course
rx, ry = [self.calc_grid_position(goal_node.x, self.min_x)], [
self.calc_grid_position(goal_node.y, self.min_y)]
parent_index = goal_node.parent_index
while parent_index != -1:
n = closed_set[parent_index]
rx.append(self.calc_grid_position(n.x, self.min_x))
ry.append(self.calc_grid_position(n.y, self.min_y))
parent_index = n.parent_index
return rx, ry
@staticmethod
def calc_heuristic(n1, n2):
w = 1.0 # weight of heuristic
d = w * math.hypot(n1.x - n2.x, n1.y - n2.y)
return d
def calc_grid_position(self, index, min_position):
"""
calc grid position
:param index:
:param min_position:
:return:
"""
pos = index * self.resolution + min_position
return int(pos)
def decalc_grid_position(self, pos, min_position):
index = (pos - min_position) / self.resolution
return int(index)
def calc_xy_index(self, position, min_pos):
return round((position - min_pos) / self.resolution)
def calc_grid_index(self, node):
return (node.y - self.min_y) * self.x_width + (node.x - self.min_x)
def verify_node(self, node):
px = self.calc_grid_position(node.x, self.min_x)
py = self.calc_grid_position(node.y, self.min_y)
if px < self.min_x:
return False
elif py < self.min_y:
return False
elif px >= self.max_x:
return False
elif py >= self.max_y:
return False
# collision check
if self.obstacle_map[node.x][node.y]:
return False
return True
def compute_robot_radius(self):
""" Compute and store table of offsets of cells within a robot's radius.
"""
self.robot_radius = []
for x in range(int(-self.rr), int(self.rr) + 1):
for y in range(int(-self.rr), int(self.rr) + 1):
if math.hypot(x, y) < self.rr:
self.robot_radius.append((x, y))
def calc_obstacle_map(self, ox, oy):
self.min_x = round(min(ox))
self.min_y = round(min(oy))
self.max_x = round(max(ox))
self.max_y = round(max(oy))
print("min_x:", self.min_x)
print("min_y:", self.min_y)
print("max_x:", self.max_x)
print("max_y:", self.max_y)
self.x_width = round((self.max_x - self.min_x) / self.resolution)
self.y_width = round((self.max_y - self.min_y) / self.resolution)
print("x_width:", self.x_width)
print("y_width:", self.y_width)
self.compute_robot_radius()
self.obstacle_map = [[False for _ in range(len(oy))] for _ in range(len(ox))]
obstacles = zip(ox, oy)
for ox, oy in obstacles:
ox = self.decalc_grid_position(ox, self.min_x)
oy = self.decalc_grid_position(oy, self.min_y)
for dx, dy in self.robot_radius:
self.obstacle_map[int(ox + dx)][int(oy + dy)] = True
@staticmethod
def get_motion_model():
# dx, dy, cost
motion = [[1, 0, 1],
[0, 1, 1],
[-1, 0, 1],
[0, -1, 1],
[-1, -1, math.sqrt(2)],
[-1, 1, math.sqrt(2)],
[1, -1, math.sqrt(2)],
[1, 1, math.sqrt(2)]]
return motion
def main():
print(__file__ + " start!!")
# start and goal position
sx = 10.0 # [m]
sy = 10.0 # [m]
gx = 55.0 # [m]
gy = -5.0 # [m]
grid_size = 2.0 # [m]
robot_radius = 2.0 # [m]
# set obstacle positions
ox, oy = [], []
for i in range(-10, 60):
ox.append(i)
oy.append(-10.0)
for i in range(-10, 60):
ox.append(60.0)
oy.append(i)
for i in range(-10, 61):
ox.append(i)
oy.append(60.0)
for i in range(-10, 61):
ox.append(-10.0)
oy.append(i)
for i in range(-10, 40):
ox.append(20.0)
oy.append(i)
for i in range(0, 40):
ox.append(40.0)
oy.append(60.0 - i)
if show_animation: # pragma: no cover
plt.plot(ox, oy, ".k")
plt.plot(sx, sy, "og")
plt.plot(gx, gy, "xb")
plt.grid(True)
plt.axis("equal")
a_star = AStarPlanner(ox, oy, grid_size, robot_radius)
rx, ry = a_star.planning(sx, sy, gx, gy)
if show_animation: # pragma: no cover
plt.plot(rx, ry, "-r")
plt.pause(0.001)
plt.show()
if __name__ == '__main__':
main()
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-24T17:05:58.760",
"Id": "256417",
"Score": "0",
"Tags": [
"python",
"python-3.x",
"numpy"
],
"Title": "Reduce computing time of planning method (grid)"
}
|
256417
|
<p><strong>Similar Word Finder</strong></p>
<p>I created this similar word finder for fun.
(word.txt are words from <a href="http://www.mieliestronk.com/corncob_lowercase.txt" rel="nofollow noreferrer">http://www.mieliestronk.com/corncob_lowercase.txt</a>)
Is there any way to make this better or more accurate?</p>
<pre><code>import java.util.*;
import java.io.*;
class Main {
public static void print(String text, int times) {
for (int i = 0; i < times; i++) {
System.out.print(text);
}
}
public static void println(String text, int times) {
for (int i = 0; i < times; i++) {
System.out.println(text);
}
}
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList();
try {
BufferedReader reader = new BufferedReader(new FileReader("word.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
arrayList.add(line);
}
println("Welcome to similar word finder. This program searches 58100 different words for words that are similar to the word that you entered",1);
print("Enter a word: ", 1);
Scanner scanner = new Scanner(System.in);
String checkWord = scanner.nextLine();
for (int i = 0; i < checkWord.length(); i++) {
// checks whether the character is not a letter
// if it is not a letter ,it will return false
if ((Character.isLetter(checkWord.charAt(i)) == false)) {
println("Your word contains a not-unicode letter!",1);
System.exit(1);
}
}
ArrayList<String> similarwords = new ArrayList<>();
print("How strict do you want the search to be? (1) Very Strict (2) Normal strict (3) Not very strict: ",1);
String strict = scanner.nextLine();
//println(arrayList.toString(),1);
int minus = 0;
if (strict == "1") {
minus = 1;
} else {
if (strict=="2") {
minus = 2;
} else {
if (strict=="3") {
minus = 3;
} else {
minus =2;
}
}
}
int timesRight = 0;
int timesRight2 = 0;
if (checkWord.length() > 3) {
timesRight2 = checkWord.length()-minus;
println("Similar Words:", 1);
} else {
if (checkWord.length() > 2) {
timesRight2=checkWord.length();
}else {
timesRight=2;
}
}
checkWord = checkWord.trim();
try {
String[] letters = checkWord.split("");
for (String word3 : arrayList) {
timesRight=0;
String[] letters2 = word3.split("");
int under = 0;
if (letters.length<=letters2.length) {
under = letters.length;
} else {
under = letters2.length;
}
for(int i = 0; i < under;i++) {
if (letters2[i].equals(letters[i])) {
timesRight++;
} else {
if(i<letters2.length-2 && i<letters.length-2){
if (letters2[i+1].equals(letters[i])) {
timesRight++;
}
}
}
}
if (timesRight>timesRight2) {
if
if (word3 != checkWord) {
//System.out.println(checkWord);
similarwords.add(word3);
println(word3 +" #" + similarwords.size() , 1);
}else {
println(word3 + " (search word)",1);
}
} else {
//println("x",1);
}
}
} catch (Exception e) {
System.err.println("Error!: " + e);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>If you want your word match to be more accurate, look up Soundex matching.</p>\n<p>I worked on making your code more readable by ordinary humans.</p>\n<p>I couldn't figure out how you were matching words. I made an assumption that you were selecting words based on a count of the letter differences.</p>\n<p>Generally, when you write a Java class, it should read like an essay. The most important information is at the beginning, and as you go further down the code, you see more and more details. Details that are presented in bite-size morsels that we call methods.</p>\n<p>Almost all of your code was in one main method. Your code was hard for me to follow, and as I said, I gave up trying to figure out how you were comparing words and just wrote my own code.</p>\n<p>Here's the primary method I wrote to find similar words.</p>\n<pre><code>public void findSimilarWords() {\n List<String> wordList = readWordList();\n Scanner scanner = new Scanner(System.in);\n String checkword = readWord(scanner);\n int level = readStrictLevel(scanner);\n List<String> matchingWords = findMatchingWords(\n wordList, checkword, level);\n createOutput(checkword, matchingWords);\n scanner.close();\n}\n</code></pre>\n<p>Seven lines of code. Now, at this point, we don't know the details. We know there's a word list, that we get a word and a match level from the console, and we output matching words. At this point, that's all we need to know.</p>\n<p>We'll get the details as we read further down the class code.</p>\n<p>I think I've made my point. Here's the revised code. I hope you find this code easier to understand and more importantly, easier to modify. Code is not just for computers. Humans have to read and understand the code as well. Including you after time has passed.</p>\n<pre><code>import java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.net.MalformedURLException;\nimport java.net.URL;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Scanner;\n\npublic class SimilarWordFinder {\n \n public static void main(String[] args) {\n SimilarWordFinder swf = new SimilarWordFinder();\n swf.findSimilarWords();\n }\n\n public void findSimilarWords() {\n List<String> wordList = readWordList();\n Scanner scanner = new Scanner(System.in);\n String checkword = readWord(scanner);\n int level = readStrictLevel(scanner);\n List<String> matchingWords = findMatchingWords(\n wordList, checkword, level);\n createOutput(checkword, matchingWords);\n scanner.close();\n }\n \n private List<String> readWordList() {\n List<String> wordList = new ArrayList<>();\n try {\n URL url = new URL("http://www.mieliestronk.com/"\n + "corncob_lowercase.txt");\n BufferedReader reader = new BufferedReader(\n new InputStreamReader(url.openStream()));\n String line = reader.readLine();\n while (line != null) {\n wordList.add(line.trim());\n line = reader.readLine();\n }\n reader.close();\n } catch (MalformedURLException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n return wordList;\n }\n \n private String readWord(Scanner scanner) {\n println("Welcome to similar word finder. This program "\n + "searches 58,100 different words for words that "\n + "are similar to the word that you entered",\n 1);\n boolean invalidWord = true;\n String checkWord = "";\n \n while (invalidWord) {\n print("Enter a word: ", 1);\n checkWord = scanner.nextLine();\n invalidWord = false;\n for (int i = 0; i < checkWord.length(); i++) {\n // checks whether the character is not a letter\n // if it is not a letter ,it will return false\n if (!Character.isLetter(checkWord.charAt(i))) {\n println("Your word contains a not-unicode letter!", 1);\n invalidWord = true;\n break;\n }\n }\n }\n \n return checkWord;\n }\n \n private int readStrictLevel(Scanner scanner) {\n print("How strict do you want the search to be? (1) Very "\n + "Strict (2) Normal strict (3) Not very strict: ",\n 1);\n String strict = scanner.nextLine();\n return valueOf(strict);\n }\n \n private List<String> findMatchingWords(List<String> wordList,\n String word, int level) {\n List<String> similarWords = new ArrayList<>();\n \n for (String matchWord : wordList) {\n if (matchWord.length() == word.length()) {\n int difference = calculateWordDifference(word, matchWord);\n if (difference <= level) {\n similarWords.add(matchWord);\n }\n }\n }\n \n return similarWords;\n }\n \n private int calculateWordDifference(String word, String matchWord) {\n int difference = 0;\n \n for (int i = 0; i < word.length(); i++) {\n if (word.charAt(i) != matchWord.charAt(i)) {\n difference++;\n }\n }\n \n return difference;\n }\n \n private void createOutput(String word, List<String> matchingWords) {\n println(" ", 1);\n println("The following words match \\"" + word + "\\"", 1);\n println(" ", 1);\n \n for (String matchingWord : matchingWords) {\n println(" " + matchingWord, 1);\n }\n }\n \n private void print(String text, int times) {\n for (int i = 0; i < times; i++) {\n System.out.print(text);\n }\n }\n\n private void println(String text, int times) {\n for (int i = 0; i < times; i++) {\n System.out.println(text);\n }\n }\n \n private int valueOf(String number) {\n try {\n return Integer.valueOf(number);\n } catch (NumberFormatException e) {\n return 2;\n }\n }\n \n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-25T10:30:40.703",
"Id": "256434",
"ParentId": "256421",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "256434",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-24T21:47:12.217",
"Id": "256421",
"Score": "0",
"Tags": [
"java"
],
"Title": "Similar Word Finder"
}
|
256421
|
<p>I put a backtracking algorithm around the Farmer, Wolf, Goat and Cabbage problem - to see if there are any <em>interesting</em> branches, besides the (two) 7-step solutions.</p>
<p><strong>WGC Problem</strong>: A Farmer with a wolf, a goat and a giant cabbage has to cross a river on a tiny boat that can only carry <strong>him plus one</strong> of the three cargo loads. Problem is: the <strong>Goat</strong> starts eating the cabbage as soon as the Farmer is on the <strong>other</strong> side. The <strong>Wolf</strong> does the same to the goat. Can he ferry all 3 to the other side under these rules/constraints?</p>
<p>sakharov.net has a very nice description (calling it "Russian"). I read long ago the story's traces get lost in the Middle Ages. Cabbage (soup) and wolf (Peter and) being typical Russian things. Here's sakharov's version:</p>
<blockquote>
<p>This is an old and famous Russian puzzle. Try to carry Wolf, Goat and
Cabbage across a river in a boat. You can take on the boat with you
only one of them in each trip. If you leave Wolf and Goat on the same
bank, Wolf will eat Goat. If you leave Goat and Cabbage on the same
bank, Goat will eat Cabbage. Although, they will never eat one another
while you stay with them. Make sure they all safely reach the other
river bank.</p>
</blockquote>
<p>Then you can realistically "play". Loading and unloading is separate from crossing, a nice way to distract the player a bit. You get a message when you make an "illegal" move.</p>
<blockquote>
<p>You can move a <strong>person/animal/object</strong> to the boat by clicking on its
image. Clicking on an image in the boat moves one back.</p>
<p>To move the boat to another bank, press the '<<' or '>>' buttons.</p>
</blockquote>
<p><strong>person/animal/object</strong>: I had and have the same problem. I chose "Animals". It feels wrong now to turn "cabbage" into "salad". But the salad (to me) is as edible as a wolf is dangerous. Some use fox, hen and beans. Some sell their soul just to extend the problem and call it cannibals and missionaries.</p>
<hr />
<p>I am thinking of adding an interactive version (called instead of <code>backtrack_fsgw()</code> from <code>main()</code>), giving the user (who has to play blindly) messages like:</p>
<p>"Can't take the Salad. Goat and wolf would be left together."</p>
<p>"There is no goat here"</p>
<p>"You just brought the wolf from that side"</p>
<p>"You are turning in circles. You were with the goat on that side 6 crossings ago"</p>
<hr />
<p>On first view it seems a dilemma. Then you realize it <em>can</em> be solved (by taking the goat back at step 4). Then you realize: it can almost <strong>not be not solved</strong>: every choice is compulsory, except silly direct repetitions.</p>
<p>You have to look closely to find a way to prolong the procedure, by constantly rotating the 3 passengers. Instead of going back empty at the end to fetch the lone goat, you can take back the wolf or salad, whichever you did <strong>not</strong> carry last. (if you do choose the other, it is not the start of a cycle, but a (silly) direct repetition)</p>
<p>Here is the output. Farmer(=empty ferry), Salad, Goat and Wolf are 0, 1, 2 and 3 resp.</p>
<pre class="lang-none prettyprint-override"><code>ALL CROSSED - Level= 7 2012302
ALL CROSSED - Level=13 2012312312302
ALL CROSSED - Level=19 2012312312312312302
ALL CROSSED - Level=25 2012312312312312312312302
ALL CROSSED - Level=31 2012312312312312312312312312302
MAXLEVEL reached - backtracking to escape cycle: ...12312312
ALL CROSSED - Level= 7 2032102
ALL CROSSED - Level=13 2032132132102
ALL CROSSED - Level=19 2032132132132132102
ALL CROSSED - Level=25 2032132132132132132132102
ALL CROSSED - Level=31 2032132132132132132132132132102
MAXLEVEL reached - backtracking to escape cycle: ...32132132
</code></pre>
<p>It goes on of course finding "solutions" if not stopped by a maxlevel. It is a kind of benign, non-branching cycle. WITH silly reps included, you get an enormous number of boring branches.</p>
<p>This is the filtered output lines (both kinds).</p>
<p>The full output displays the "state of the riversides". Here the lines 20-70 with the first solution.</p>
<pre class="lang-none prettyprint-override"><code>...
[ 5 LEVEL] cur:[-1] parent: 2
0: *.**
1: .*..
--> new node:[3] and state:
0: ..*.
1: **.*
[ 6 LEVEL] cur:[-1] parent: 3
0: ..*.
1: **.*
--> new node:[0] and state:
0: *.*.
1: .*.*
[ 7 LEVEL] cur:[-1] parent: 0
0: *.*.
1: .*.*
--> new node:[2] and state:
0: ....
1: ****
ALL CROSSED - Level= 7 2012302
[ 6 LEVEL] cur:[0] parent: 3
0: ..*.
1: **.*
--> new node:[1] and state:
0: ***.
1: ...*
...
</code></pre>
<p>This quite sums up what the program does.</p>
<p>To my surprise I ended up with a 3D-array via <code>typedef</code>. With <code>int **sh</code> I had to use it like <code>(*sh)[fside]</code>. Plus other pointer-is-not-array related warnings and errors. Now it is:</p>
<pre><code> next_node(Shores_t sh, ...
...
ferry(sh, anim, fside);
if (is_unsafe(sh[fside]))
</code></pre>
<p>Questions:</p>
<p>I guess if you want arrays, this is one of many right ways to do it. Might even work with variable/runtime stack size.</p>
<p>Would a <code>struct shores</code> be more flexible for passing, for putting in an array and for accessing?</p>
<p>What to put inside that struct? I don't think <code>sh.goat</code> works if enum item <code>Goat</code> is integer <code>2</code>. Maybe the way to go if you use pure logic.</p>
<p>Or do I just <em>wrap</em> a <code>struct</code>around the existing typedef?</p>
<p><code>struct shores { Shores_t sht };</code></p>
<p>and then <code>sh->sht[Dest][Farmer]</code> ?</p>
<p>This is even worse than <code>(*sh)[Dest][Farmer]</code>.</p>
<p>Do I have to make an array of pointers? Like usual with dynamic 2D arrays?</p>
<p>Eight or even just four bits would be enough to hold a complete state. But I don't want it small and fast.</p>
<p>Any general ideas for this specific case ?</p>
<p>Any comments about the code below?</p>
<pre><code>/* Farmer, Wolf, Goat and Cabbage
River Crossing Problem/Puzzle/Dilemma
Here the cabbage is a salad - "fsgw" instead of FWGC (or FCGW).
The 'none' option (or 'Alone') was renamed 'Farmer' to use it better
(see all_on_side() and ferry()). These four items (symbols) are numerically represented
as 'Animals' (as living beings) via enum.
The first Shores_t (both Sides_t of the river) looks like:
{ {1,1,1,1}, {0,0,0,0} }
This is a bit redundant, but robust/clear (see is_unsafe()).
Alternative: only 4 bools e.g. "1010" as "FcGw"; the other side then is virtual/the inverse.
By avoiding simple node/move repeats (ferry *directly* back what you just ferried),
there is only a 3-cycle pattern (rotating the items after 6 cycles) amd it can easily be broken.
An alternative would be to check for *state* repetitions in the *whole* stack. */
#include <stdio.h>
#include <string.h>
/* For different backtrack patterns (and for testing) the sequence can be changed */
enum {Farmer, Salad, Goat, Wolf, Animals};
//enum {Salad, Wolf, Goat, Farmer, Animals};
enum {Start, Dest, Sides};
typedef int Side_t [Animals]; /* For real 2D array without 'int...[2][4]' everywhere */
typedef Side_t Shores_t [Sides];
int
is_unsafe(Side_t b) { /* b: where the farmer is NOT */
return b[Goat] && ( b[Salad] || b[Wolf] );
}
int
all_on_side(Side_t d) { /* d: 'Dest' side to test for success */
return d[Farmer] && d[Salad] && d[Goat] && d[Wolf];
}
/* Visualize a "shore[2][4]" (Two sides with four slots).
A bit of Conway life, just as jumpy on small scale */
/* The enum determines which of f,s,g and w is 0,1,2 or 3 */
void
show_state(Shores_t sh) {
for (int s = 0; s < Sides; s++) {
printf("%d: ", s);
for (int i = 0; i < Animals; i++)
printf(sh[s][i] ? "*" : ".");
putchar('\n');
}
}
/* Show chain of nodes up to level 'end', for solutions. One-based. */
void
show_nodes(int *n, int end) {
for (int i = 1; i <= end; i++)
printf("%d", n[i]);
putchar('\n');
}
/* Cross the river alone or with an 'anim' =
Check-out at 'from' and check-in at NOT-'from' */
void
ferry(Shores_t sh, int anim, int from) {
int to = !from;
sh[from][anim] = 0;
sh[to] [anim] = 1;
if (anim != Farmer) { /* (or just repeat with same value) */
sh[from][Farmer] = 0;
sh[to] [Farmer] = 1;
}
}
/* Returns next valid node, above current, and different from lower node (no direct repetition!). */
/* Or -1 if none left. Also updates the state stack by reference 'Shores_t sh'. */
int
next_node(Shores_t sh, Shores_t sh_0, int anim, int anim_0) {
memcpy(sh, sh_0, sizeof(Shores_t)); /* Work on last state in new level on stack */
const int fside = sh[1][Farmer]; /* Where is the farmer at all? (note [1], not [Dest], makes that trick (?) less confusing)*/
while (++anim < Animals) {
if (sh[fside][anim] && anim != anim_0) {
ferry(sh, anim, fside); /* Test crossing... */
if (is_unsafe(sh[fside]))
ferry(sh, anim, !fside); /* ...undone by ferry() in reverse */
else
return anim; /* ...confirmed, done */
}
}
return -1;
}
/* Backtrack FWGC (fsgw) using next_node() */
/* With indep. tests for max. level (cycle breaker) and for end state */
void
backtrack_fsgw(int *nodes, Shores_t *states, int MAX) {
int LVL = 1;
while (LVL > 0) {
/* Display I: current level, old vars */
printf("[%2.d LEVEL] cur:[%d] parent: %d\n", LVL, nodes[LVL], nodes[LVL-1]);
show_state(states[LVL-1]);
nodes[LVL] = next_node(states[LVL], states[LVL-1],
nodes[LVL], nodes[LVL-1]);
if (nodes[LVL] == -1)
LVL--;
else {
/* Display II: after successful next_node() */
printf(" --> new node:[%d] and state: \n", nodes[LVL]);
show_state(states[LVL]);
putchar('\n');
if (all_on_side(states[LVL][Dest])) {
printf("ALL CROSSED - Level=%2.d ", LVL);
show_nodes(nodes, LVL);
nodes[LVL--] = -1;
continue;
}
if (LVL == MAX) {
printf("MAXLEVEL reached - backtracking to escape cycle: ...");
show_nodes(&nodes[LVL-8], 8); /* not too much back, if MAX is very low...todo; but then again it only shows 123... or 321... */
nodes[LVL--] = -1;
continue;
}
LVL++;
}
}
return;
}
/* Stacks for (i.e. Arrays of) the nodes (moves) and the states (Shores_t, int[2][4]) */
int main(void) {
/* Maximum level:
- 32 is enough to give solution pairs at levels 7, 13, 19, 25 and 31. Also enough crossings to give up.
- 8 is enough for the first/best solution pair */
#define MAXLEV 32
int nodes [MAXLEV];
Shores_t states[MAXLEV];
int i;
/* Unvisited nodes have -1 */
for (i = 0; i < MAXLEV; i++)
nodes[i] = -1;
/* Starting position of F,S,G,W on Shore Zero */
for (i = 0; i < Animals; i++) {
states[0][Start][i] = 1;
states[0][Dest] [i] = 0;
}
backtrack_fsgw(nodes, states, MAXLEV-1);
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-25T00:12:44.197",
"Id": "506255",
"Score": "2",
"body": "The question would be greatly improved if you provided a simple text explanation of exactly what the \"farmer-wolf-goat-cabbage\" problem is. It's familiar to some of us, but there are many variations, and so describing your *particular* version would be very helpful in reviewing the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-25T08:45:09.727",
"Id": "506267",
"Score": "0",
"body": "Done. Now I prefer WGC as abbrev., but FSGW is my name for it in the code. The farmer is not really needed, only in the real-world story, and in most implementations including this one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T23:36:40.410",
"Id": "506532",
"Score": "0",
"body": "I understand, from your description, this requires three bits _per_ move?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T08:07:17.610",
"Id": "506545",
"Score": "0",
"body": "I would say a move is two bits: one of W, G or C. The state (i.e. who is where after n moves) is 3 bits, *plus* where is the farmer; but that info is also in \"number of moves modulo 2\". I prefer to handle the farmer like a constantly moving object,"
}
] |
[
{
"body": "<p>Starting with a 3D-Array <code>a[][][]</code></p>\n<pre><code> int a[100][2][4];\n a[16][1][2] = 123456;\n</code></pre>\n<p>There are two ways to get the "reference" of <code>a[xx]</code>. With or without <code>typedef int Side_t[4]</code>. I even take <code>a[14]</code> and then <code>[1+4][2]</code>, because the first index is optional / array has no bounds.</p>\n<pre><code> int (*p)[4] = a[14];\n /* Same as: */\n Side_t *p = a[14];\n</code></pre>\n<p>Now I can access all values relative to <code>a[14]</code>. For the second int in the fifth Side_t:</p>\n<pre><code> printf("%d\\n", p[5][2]); \n</code></pre>\n<p>And I get the number in <code>a[16][1][2]</code> skipping the four <code>...[0]</code> and <code>...[1]</code> entries in <code>a[14]</code> and <code>a[15]</code>.</p>\n<h2>typedefs and function paramaters</h2>\n<p>By renaming <code>Sides_t</code> with <code>FSGW_t</code>, and duplicating it manually, you can also live without <code>Shores_t</code>. Here some ideas:</p>\n<p>The array dimensions [2][4] could be more "officially" named:</p>\n<pre><code>enum {Farmer, Salad, Goat, Wolf, N_fsgw};\nenum {Start, Dest, N_sides};\n</code></pre>\n<p>The array of 4 ints (i.e. F, S, G and W):</p>\n<pre><code>typedef int FSGW_t [N_fsgw]; \n//typedef FSGW_t Shores_t [N_sides];\n</code></pre>\n<p>In <code>main()</code>:</p>\n<pre><code>FSGW_t states[MAXLEV][2];\n</code></pre>\n<p>or even:</p>\n<pre><code>int states[MAXLEV][2][4]; // 2 sides, 4 items FSGW\n</code></pre>\n<p>to see the whole thing.</p>\n<p>The <code>backtrack_fsgw()</code> declaration is one of:</p>\n<pre><code>//backtrack_fsgw(int *nodes, Shores_t *states, int MAX) {\nbacktrack_fsgw(int *nodes, int states[][2][4], int MAX) {\nbacktrack_fsgw(int *nodes, int (*states)[2][4], int MAX) {\nbacktrack_fsgw(int nodes[], FSGW_t states[][2], int MAX) {\n</code></pre>\n<p>...</p>\n<p>In <code>next_node()</code> there is a small problem without <code>sizeof(Shores_t)</code>.</p>\n<pre><code>int\nnext_node(FSGW_t sh[], void *sh_0, int anim, int anim_0) { \n \n //memcpy(sh, sh_0, sizeof(FSGW_t)*2); \n //memcpy(sh, sh_0, sizeof(FSGW_t[2])); \n //memcpy(sh, sh_0, sizeof(int[2][4])); \n memcpy(sh, sh_0, (void*)sh - sh_0);\n</code></pre>\n<p>I prefer the last version: it shows that we want only address and size of <code>sh_0</code>. <code>sizeof sh</code> does not work, because it is "only" a paramter array.</p>\n<p>(But it needs no parens <code>(*sh)[...]</code>. It is a 3/4 array.</p>\n<hr />\n<pre><code>ferry(FSGW_t sh[2], int anim, int from) {\n</code></pre>\n<p>...or <code>sh[]</code> or <code>*sh</code>. The "2" is just to give information and reflects the limited range of 'from' and 'to' (0 and 1).</p>\n<p>Then arriving back at the top:</p>\n<pre><code>int\nis_unsafe(FSGW_t b) { /* b: where the farmer is NOT */\n return b[Goat] && ( b[Salad] || b[Wolf] )\n</code></pre>\n<p>I am not saying this <code>FSGW_t</code> single typedef version is better than the <code>Side_t/Shores_t</code> version. I just wanted to show how to handle multiple layers of arrays, even if there is no matching <code>typedef</code></p>\n<hr />\n<p>Array rule: "The first dimension is free" (the others are not). A first <code>[]</code> on the right is same as a <code>(*...)</code> around the identifer.</p>\n<hr />\n<p><code>next_node()</code> <em>could</em> be called more simple:</p>\n<pre><code>nodes[LVL] = next_node(nodes, states, LVL);\n</code></pre>\n<p>Then it has to define the working objects itself:</p>\n<pre><code>int\nnext_node(int nodes[], FSGW_t states[][2], int LVL) {\n\n int anim = nodes[LVL];\n int anim_0 = nodes[LVL-1];\n FSGW_t *sh = states[LVL];\n FSGW_t *sh_0 = states[LVL-1];\n\n memcpy(sh, sh_0, (sh-sh_0)*sizeof(FSGW_t));\n</code></pre>\n<p>Now <code>sh</code> and <code>sh_0</code> have difference of two (<code>FSGW_t</code>s), so in <code>memcpy()</code> the diff has to be multiplied.</p>\n<p>All this only because <code>states[][][]</code> is not global...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T14:23:45.213",
"Id": "256473",
"ParentId": "256422",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-24T23:47:53.747",
"Id": "256422",
"Score": "5",
"Tags": [
"c",
"backtracking"
],
"Title": "Farmer, Wolf, Goat and Cabbage Problem: full decision tree in C"
}
|
256422
|
<p>My first client-server application. It's a simple Python script that gets a list of running processes from <code>Server_1</code> and writes it to a datetime-named file on <code>Server_2</code>, every 5 seconds.</p>
<p>I am planning on refactoring this code into one or two functions, maybe one for securing the connection and one for implementing the logic.</p>
<p>I also know nothing about security best-practices, and I'm looking for some pointers. Any feedback on any aspect of the code is welcome.</p>
<pre class="lang-py prettyprint-override"><code>
import os
import paramiko
from time import sleep
from datetime import datetime
SERVER_1 = os.getenv('HOST_1') or ""
SERVER_1_PASS = os.getenv('PASS_1') or ""
SERVER_2 = os.getenv('HOST_2') or ""
SERVER_2_PASS = os.getenv('PASS_2') or ""
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(SERVER_1, username='root', password=SERVER_1_PASS)
ssh2 = paramiko.SSHClient()
ssh2.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh2.connect(SERVER_2, username='root', password=SERVER_2_PASS)
while True:
now = datetime.now()
dt_string = now.strftime("%d-%m-%YT%H:%M:%S")
stdin, stdout, stderr = ssh.exec_command("ps -aux")
processes = stdout.readlines()
output = [line.strip() for line in processes]
ftp = ssh2.open_sftp()
try:
file = ftp.file(dt_string, "a", -1)
file.write('\n'.join(output))
file.flush()
ftp.close()
except IOError as e:
print("Could not write to file")
print(e)
sleep(5)
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-25T08:05:57.277",
"Id": "506265",
"Score": "0",
"body": "Don't use root. Create another account that just has permissions to do these commands. Also, the loop will be 5 seconds plus the time to execute all the code. Maybe it doesn't matter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T23:51:33.160",
"Id": "506464",
"Score": "0",
"body": "@RootTwo does that mean create a new user and put them in a specific group, then modify the group privileges of the directory they operate in? Or what do you mean? Thanks"
}
] |
[
{
"body": "<blockquote>\n<pre><code>SERVER_1_PASS = os.getenv('PASS_1') or ""\nSERVER_2_PASS = os.getenv('PASS_2') or ""\n</code></pre>\n</blockquote>\n<p>I don't think it's a good idea to pass secrets in the environment - that's too easily read by other processes. Instead, prefer to hold them in a file that's accessible only by the user. Since we're using SSH, we even already have such a file (<code>$HOME/.ssh/config</code>), though a better choice would be to use public-key authentication.</p>\n<blockquote>\n<pre><code>ssh.connect(SERVER_1, username='root', password=SERVER_1_PASS)\n</code></pre>\n</blockquote>\n<p>Ouch - why to we need to connect as <code>root</code>? We should have a dedicated user for this, with the minimum level of capability to perform the task.</p>\n<p>What does <code>connect()</code> do when <code>SERVER_1</code> is the empty string (our default if not passed in environment)? Is that what we want, or should we error out in that case?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T22:39:16.173",
"Id": "506461",
"Score": "0",
"body": "can you expand on having a \"dedicated user\"? I'm confused: do I create a new user and put them in a group and then modify the group's priviledges? Or do I modify group privildges on the directory I want the new user to work in?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T11:18:16.120",
"Id": "506495",
"Score": "0",
"body": "That's quite a broad topic to expand on (and maybe worth looking over on [security.se] (and perhaps [unix.se]) for ideas on how best to set up a user to run a particular task). Something you could do with SSH is permit only a particular command to be run, thus denying a login shell even to someone with the correct private key."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-25T09:26:57.927",
"Id": "256430",
"ParentId": "256426",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "256430",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-25T04:01:52.043",
"Id": "256426",
"Score": "2",
"Tags": [
"python",
"security",
"server",
"client"
],
"Title": "Client-server application for logging running processes"
}
|
256426
|
<p>I have a simple task.</p>
<ol>
<li>Array of people object comes in, up to a thousand.</li>
<li>Need to iterate over it, and create a custom payload for external service.</li>
</ol>
<p>I have created a working solution, but I would like to see if I am totally off course, and what changes should I make.</p>
<p>I have reduced non-important details from the code (errors, and similar), so it might not work. But the point is to show how it works, and hopefully get some advice.</p>
<pre><code>User struct {
Name string `json:"name"`
Lastname string `json:"lastname"`
}
func HandleLambda(event events.SQSEvent) {
var userRecords []map[string]interface{}
for idx := range event.Records {
record := event.Records[idx]
ev, err := e.NewEvent(record.Body)
if err != nil {
continue
}
u, err := repository.NewUser(ev)
if err != nil {
continue
}
user := make(map[string]interface{})
user["1"] = u.Name
user["2"] = u.Lastname
userRecords = append(userRecords, user)
}
uJSON, _ := json.Marshal(userRecords)
// I send this to external service
}
</code></pre>
<p>External service is using numbers as keys, that's why I need "1" and "2". I do not have control over it.
That's the way it works.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-25T11:23:01.587",
"Id": "506274",
"Score": "0",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-25T12:49:41.957",
"Id": "506277",
"Score": "2",
"body": "Welcome to Code Review! You mentioned you removed non-important details, but it would actually be really good to see the fully, working code, you might never know what review comments you get about those non-essentials. Enjoy your stay!"
}
] |
[
{
"body": "<p>I guess I might as well then. To prefix that with: It looks fine as is,\nthere's a few details that could be improved, although those also depend\non your team and style guide. Also read it in the context of a bigger\nproject, not everything always applies, especially if it's one-off code,\netc.</p>\n<p>I'm gonna assume (since the formatting is a bit off) that you're using\n<code>gofmt</code> or <code>goimports</code> already, if you don't, check them out, it helps\nimmensely.</p>\n<p>For the <code>User</code> struct, even if the JSON name is <code>lastname</code>, consider the\nGo-side name to be <code>LastName</code> to keep in line with normal style guides.\nDepending on whether you need it the JSON annotation could also use an\n<code>omitempty</code>, but that depends on your external service of course.</p>\n<p>For the <code>HandleLambda</code> loop a few things stand out:</p>\n<ul>\n<li><code>for idx := range event.Records</code> might as well be\n<code>for idx, record := event.Records</code>, no need have an extra line to get\nthe actual item. And if you're never using it,\n<code>for _, record := event.Records</code> even.</li>\n<li>Errors are ignored? Consider logging them if don't error our\nimmediately.</li>\n<li><code>user := make(map ...)</code> I'd usually make that a literal to avoid\nrepeating myself even more.</li>\n<li><code>userRecords</code> could perhaps already be pre-allocated to the right size. Then there'd be no need for <code>append</code> at all. Or, like here, if you still need to use <code>continue</code>, pre-allocating the maximum length it could take, so it definitely wouldn't have to\nbe resized might also be a good idea. Usually this also doesn't matter that much if you don't have a\nlot of entries, but it's good to keep in mind for situations where it\n<em>does</em> matter.</li>\n<li>Also consider making the to-map conversion a new method on <code>User</code>, or\na helper function, you might want to test it or reuse in other places.</li>\n<li><code>repository</code> looks like a global variable, that's usually not the best\nidea. Consider making that a parameter for <code>HandleLambda</code>, or making\n<code>HandleLambda</code> a method and put the <code>repository</code> as one of its\nmembers. It will help with testability in the end to not have\ndependencies scattered around like that.</li>\n</ul>\n<pre class=\"lang-golang prettyprint-override\"><code>type User struct {\n Name string `json:"name"`\n LastName string `json:"lastname"`\n}\n\nfunc (u *User) toMap() map[string]interface{} {\n return map[string]interface{}{\n "1": u.Name,\n "2": u.LastName,\n }\n}\n\nfunc HandleLambda(event events.SQSEvent) {\n userRecords := make([]map[string]interface{}, 0, len(event.Records))\n\n for _, record := range event.Records {\n ev, err := event.NewEvent(record.Body)\n if err != nil {\n continue\n }\n\n user, err := repository.NewUser(ev)\n if err != nil {\n continue\n }\n\n userRecords = append(userRecords, user.toMap())\n }\n\n uJSON, _ := json.Marshal(userRecords)\n // I send this to external service\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T10:54:26.030",
"Id": "506338",
"Score": "2",
"body": "Awesome. I learned new things from your answer! Thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T19:28:32.137",
"Id": "506395",
"Score": "1",
"body": "I have one question. You mentioned:\n\"userRecords could already be pre-allocated to the right size, then there'd be no need for append,\". But append is still used?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T22:54:01.907",
"Id": "506462",
"Score": "0",
"body": "@Wexoni yes, given that `continue` is used, it doesn't seem likely that the final length can be set immediately, however, normally I'd have expected that those errors would not just be skipped. I'll add a note. Suffice to say creating the slice with an upper bound is probably good, although if lots of entries would be skipped, perhaps even worse than allocating nothing at all upfront. That's something only more knowledge about the actual data would reveal."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T07:05:21.530",
"Id": "506481",
"Score": "1",
"body": "Not many errors will be skipped. This comes form AWS SQS. I think I will keep only one error check, the first one that checks the record.body, Second one is my mistake and it should not be there at all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T07:57:06.463",
"Id": "506483",
"Score": "1",
"body": "On a side note, when you declared that slice. I was able to find and read about it. But that zero is confusing me. What is it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T17:03:59.970",
"Id": "506519",
"Score": "0",
"body": "@Wexoni yeah, if you haven't come across it so far, take a look at https://golang.org/pkg/builtin/#make - it's basically initialising the length of the slice to zero, but the capacity to something else, so `append` will simply make use of that capacity."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T08:53:53.100",
"Id": "506547",
"Score": "1",
"body": "I tried to implement the suggestions, but I run in a problem. The to Map() function, in my IDE (Goland) it has many issues, it seems it is a Syntax Error that creates them all. I tried, but I cant fix it. Do you maybe have an idea?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T10:20:12.660",
"Id": "506550",
"Score": "1",
"body": "@Wexoni yeah I missed a few parentheses, should be fixed now above."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T10:33:22.803",
"Id": "256462",
"ParentId": "256431",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "256462",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-25T09:33:20.203",
"Id": "256431",
"Score": "3",
"Tags": [
"go"
],
"Title": "Proper way to map the object"
}
|
256431
|
<p>The program transfers a data array from a Zynq-7000 PS DDR to a BRAM IP (block RAM) memory in a PL part of a FPGA due to a PL AXI DMA IP. Inferring a xilinx axi dma driver (not scatter-gather mode), an interrupt controller and the vendor's printf function the data array is carried from the DDR to the BRAM.</p>
<p>main.c</p>
<pre><code>#include "xstatus.h"
#include "platform_.h"
#include "axi_dma_intr_poll.h"
#define TX_BUFFER (uint32_t *) 0x01100000
#define RX_BUFFER (uint32_t *) XPAR_BRAM_0_BASEADDR
#define RESET_TIMEOUT_CNTR_VAL 0x1000
#define MAX_TX_VALUE 0x100
#define PAYLOAD_SIZE MAX_TX_VALUE
volatile _Bool tx_done_flag, rx_done_flag, tx_error, rx_error;
axi_dma_init_str init;
axi_dma_poll_str poll;
axi_dma_handler_str handler;
static void tx_intr_handler(void *callback);
static void rx_intr_handler(void *callback);
static inline void printf_array(uint32_t *p_array, size_t size);
int main(void) {
uint8_t mul_coefficient = 0;
const uint8_t c_ascii_num_offset = 0x30;
uint32_t i = 0;
memset((uint8_t *) XPAR_BRAM_0_BASEADDR,0,0x100);
init.dma_id = XPAR_AXIDMA_0_DEVICE_ID;
init.rx_intr_handler = rx_intr_handler;
init.tx_intr_handler = tx_intr_handler;
init.rx_intr_id = XPAR_FABRIC_AXIDMA_0_S2MM_INTROUT_VEC_ID;
init.tx_intr_id = XPAR_FABRIC_AXIDMA_0_MM2S_INTROUT_VEC_ID;
poll.p_tx_buf = TX_BUFFER;
poll.p_rx_buf = RX_BUFFER;
poll.size = PAYLOAD_SIZE;
axi_dma_init(&init, &handler);
while(1) {
xil_printf("AXI DMA %d: ready. Insert multiplier coefficient (1 - 9): ", init.dma_id);
mul_coefficient = inbyte();
mul_coefficient -= c_ascii_num_offset;
if ((0 == mul_coefficient) || (mul_coefficient > 9)) {
xil_printf("\n\rAXI DMA %d ERROR: the coefficient must have a value from 1 to 9\n\r", init.dma_id);
continue;
}
xil_printf("%d\n\r", mul_coefficient);
for(i = 0; i < MAX_TX_VALUE; i++) {
poll.p_tx_buf[i] = (i * mul_coefficient) % MAX_TX_VALUE;
}
tx_done_flag = FALSE;
rx_done_flag = FALSE;
axi_dma_poll(&poll, &handler.axi_dma, init.dma_id);
xil_printf("AXI DMA %d: waiting completion of the poll...", init.dma_id);
while((FALSE == tx_done_flag) || (FALSE == rx_done_flag)) {
asm("NOP");
}
if ((TRUE == tx_error) || (TRUE == rx_error)) {
xil_printf("AXI DMA %d ERROR: the polling ERROR", init.dma_id);
}
else {
xil_printf("\n\n\rAXI DMA %d: the tx buffer:\n\r", init.dma_id);
printf_array(TX_BUFFER ,PAYLOAD_SIZE);
xil_printf("\n\n\rAXI DMA %d: the rx buffer:\n\r", init.dma_id);
printf_array(RX_BUFFER, PAYLOAD_SIZE);
}
xil_printf("\n\n\r");
}
return XST_SUCCESS;
}
static void tx_intr_handler(void *callback) {
uint32_t status = 0;
int reset_cntr = RESET_TIMEOUT_CNTR_VAL;
XAxiDma *axi_dma = (XAxiDma *) callback;
status = XAxiDma_IntrGetIrq(axi_dma, XAXIDMA_DMA_TO_DEVICE);
XAxiDma_IntrAckIrq(axi_dma, status, XAXIDMA_DMA_TO_DEVICE);
tx_done_flag = TRUE;
if (FALSE != (status & XAXIDMA_IRQ_ALL_MASK) &&
(TRUE == (status & XAXIDMA_IRQ_ERROR_MASK))) {
tx_error = TRUE;
XAxiDma_Reset(axi_dma);
while (reset_cntr--) {
if (XAxiDma_ResetIsDone(axi_dma)) {
break;
}
}
}
}
static void rx_intr_handler(void *callback)
{
uint32_t status = 0;
int reset_cntr = RESET_TIMEOUT_CNTR_VAL;
XAxiDma *axi_dma = (XAxiDma *) callback;
status = XAxiDma_IntrGetIrq(axi_dma, XAXIDMA_DEVICE_TO_DMA);
XAxiDma_IntrAckIrq(axi_dma, status, XAXIDMA_DEVICE_TO_DMA);
rx_done_flag = TRUE;
if ((FALSE != (status & XAXIDMA_IRQ_ALL_MASK)) &&
(TRUE == (status & XAXIDMA_IRQ_ERROR_MASK))) {
rx_error = TRUE;
XAxiDma_Reset(axi_dma);
while (reset_cntr--) {
if (XAxiDma_ResetIsDone(axi_dma)) {
break;
}
}
}
}
static inline void printf_array(uint32_t *p_array, size_t size) {
const uint8_t c_values_per_line = 10;
uint32_t i = 0;
for(i = 0; i < size; i++) {
xil_printf("%d ", *(TX_BUFFER + i));
if (FALSE == (i % c_values_per_line) && (0 != i)) {
xil_printf("\n\r");
}
}
}
</code></pre>
<p>axi_dma_intr_poll.c</p>
<pre><code>#include "xil_exception.h"
#include "axi_dma_intr_poll.h"
static int enable_intr_(axi_dma_handler_str *p_handler, axi_dma_init_str *p_init);
int axi_dma_init(axi_dma_init_str *p_init, axi_dma_handler_str *p_handler) {
if ((NULL == p_init) || (NULL == p_handler)) {
xil_printf("AXI DMA %d ERROR: the entire axi_dma_init function ERROR\r\n", p_init->dma_id);
return XST_FAILURE;
}
memset(p_handler, 0, sizeof(axi_dma_handler_str));
p_handler->p_config = XAxiDma_LookupConfig(p_init->dma_id);
if (NULL == p_handler->p_config) {
xil_printf("AXI DMA %d ERROR: the dma lookup config FAILED\r\n", p_init->dma_id);
return XST_FAILURE;
}
if (XST_SUCCESS != XAxiDma_CfgInitialize(&(p_handler->axi_dma), p_handler->p_config)) {
xil_printf("AXI DMA %d ERROR: the dma initialization FAILED\r\n", p_init->dma_id);
return XST_FAILURE;
}
if(TRUE == XAxiDma_HasSg(&(p_handler->axi_dma))){
xil_printf("AXI DMA %d ERROR: the device configured as SG mode\r\n", p_init->dma_id);
return XST_FAILURE;
}
if (XST_SUCCESS != enable_intr_(p_handler, p_init)) {
xil_printf("AXI DMA %d ERROR: the interrupt setup FAILED\r\n");
return XST_FAILURE;
}
return XST_SUCCESS;
}
int axi_dma_poll(axi_dma_poll_str *p_poll, XAxiDma *p_axi_dma, uint32_t dma_id) {
if ((NULL == p_poll) || (NULL == p_axi_dma)) {
xil_printf("AXI DMA %d ERROR: the entire axi_dma_poll function ERROR\r\n", dma_id);
return XST_FAILURE;
}
Xil_DCacheFlushRange((UINTPTR) (p_poll->p_tx_buf), p_poll->size);
if (XST_SUCCESS != XAxiDma_SimpleTransfer(p_axi_dma,(UINTPTR) (p_poll->p_tx_buf),
p_poll->size, XAXIDMA_DMA_TO_DEVICE)) {
xil_printf("AXI DMA %d ERROR: the tx buffer setting FAILED\r\n", dma_id);
return XST_FAILURE;
}
if (XST_SUCCESS != XAxiDma_SimpleTransfer(p_axi_dma,(UINTPTR) (p_poll->p_rx_buf),
p_poll->size, XAXIDMA_DEVICE_TO_DMA)) {
xil_printf("AXI DMA %d ERROR: the rx buffer setting FAILED\r\n", dma_id);
return XST_FAILURE;
}
return XST_SUCCESS;
}
int axi_dma_release(XScuGic *p_scu_gic, uint32_t tx_intr_id, uint32_t rx_intr_id) {
if ((NULL == p_scu_gic) || (0 == tx_intr_id) || (0 == rx_intr_id)) {
xil_printf("AXI DMA %d ERROR: the entire axi_dma_release function ERROR\r\n", p_scu_gic->Config->DeviceId);
return XST_FAILURE;
}
XScuGic_Disconnect(p_scu_gic, tx_intr_id);
XScuGic_Disconnect(p_scu_gic, rx_intr_id);
return XST_SUCCESS;
}
static int enable_intr_(axi_dma_handler_str *p_handler, axi_dma_init_str *p_init) {
const uint8_t c_priority = 0xA0, c_trigger_type = 0x3;
p_handler->p_intc_config = XScuGic_LookupConfig(XPAR_SCUGIC_SINGLE_DEVICE_ID);
if (NULL == p_handler->p_intc_config) {
xil_printf("AXI DMA %d ERROR: the scu gic lookup config FAILED\r\n", p_init->dma_id);
return XST_FAILURE;
}
if (XST_SUCCESS != XScuGic_CfgInitialize(&(p_handler->scu_gic), p_handler->p_intc_config,
p_handler->p_intc_config->CpuBaseAddress)) {
xil_printf("AXI DMA %d ERROR: the scu gic initialization FAILED\r\n", p_init->dma_id);
return XST_FAILURE;
}
XScuGic_SetPriorityTriggerType(&(p_handler->scu_gic), p_init->tx_intr_id, c_priority, c_trigger_type);
XScuGic_SetPriorityTriggerType(&(p_handler->scu_gic), p_init->rx_intr_id, c_priority, c_trigger_type);
if (XST_SUCCESS != XScuGic_Connect(&(p_handler->scu_gic), p_init->tx_intr_id,
(Xil_InterruptHandler)p_init->tx_intr_handler,
&(p_handler->axi_dma))) {
xil_printf("AXI DMA %d ERROR: the scu gic tx connection FAILED\r\n", p_init->dma_id);
return XST_FAILURE;
}
if (XST_SUCCESS != XScuGic_Connect(&(p_handler->scu_gic), p_init->rx_intr_id,
(Xil_InterruptHandler)p_init->rx_intr_handler,
&(p_handler->axi_dma))) {
xil_printf("AXI DMA %d ERROR: the scu gic rx connection FAILED\r\n", p_init->dma_id);
return XST_FAILURE;
}
XScuGic_Enable(&(p_handler->scu_gic), p_init->tx_intr_id);
XScuGic_Enable(&(p_handler->scu_gic), p_init->rx_intr_id);
Xil_ExceptionInit();
Xil_ExceptionRegisterHandler(XIL_EXCEPTION_ID_INT, (Xil_ExceptionHandler)XScuGic_InterruptHandler,
(void *)&(p_handler->scu_gic));
Xil_ExceptionEnable();
XAxiDma_IntrDisable(&(p_handler->axi_dma), XAXIDMA_IRQ_ALL_MASK,
XAXIDMA_DMA_TO_DEVICE);
XAxiDma_IntrDisable(&(p_handler->axi_dma), XAXIDMA_IRQ_ALL_MASK,
XAXIDMA_DEVICE_TO_DMA);
XAxiDma_IntrEnable(&(p_handler->axi_dma), XAXIDMA_IRQ_ALL_MASK,
XAXIDMA_DMA_TO_DEVICE);
XAxiDma_IntrEnable(&(p_handler->axi_dma), XAXIDMA_IRQ_ALL_MASK,
XAXIDMA_DEVICE_TO_DMA);
return XST_SUCCESS;
}
</code></pre>
<p>axi_dma_intr_poll.h</p>
<pre><code>#ifndef INC_AXI_DMA_POLL_H
#define INC_AXI_DMA_POLL_H
#include "xaxidma.h"
#include "xscugic.h"
#include "platform_.h"
typedef struct {
uint32_t *p_tx_buf;
uint32_t *p_rx_buf;
size_t size;
} axi_dma_poll_str;
typedef struct {
uint32_t tx_intr_id;
uint32_t rx_intr_id;
void (*rx_intr_handler)(void *);
void (*tx_intr_handler)(void *);
uint32_t dma_id;
} axi_dma_init_str;
typedef struct {
XAxiDma axi_dma;
XAxiDma_Config *p_config;
XScuGic scu_gic;
XScuGic_Config *p_intc_config;
} axi_dma_handler_str;
int axi_dma_init(axi_dma_init_str *p_init, axi_dma_handler_str *p_handler);
int axi_dma_poll(axi_dma_poll_str *p_poll, XAxiDma *p_axi_dma, uint32_t dma_id);
int axi_dma_release(XScuGic *p_scu_gic, uint32_t tx_intr_id, uint32_t rx_intr_id);
#endif
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T11:30:21.033",
"Id": "512535",
"Score": "0",
"body": "You don't poll interrupts. You configure interrupts and set their jump points."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-25T11:48:59.793",
"Id": "256436",
"Score": "1",
"Tags": [
"c",
"embedded",
"fpga"
],
"Title": "a simple interrupt polling program due to AXI DMA IP"
}
|
256436
|
<h3>Problem</h3>
<p>Write a command line application or script which parses a cron string and expands each field
to show the times at which it will run.</p>
<blockquote>
<p>~$ your-program "*/15 0 1,15 * 1-5 /usr/bin/find"</p>
</blockquote>
<pre><code>minute 0 15 30 45
hour 0
day of month 1 15
month 1 2 3 4 5 6 7 8 9 10 11 12
day of week 1 2 3 4 5
command /usr/bin/find
</code></pre>
<h3>Code</h3>
<pre><code>/*
* (minute)(hour)(day of month)(month)(day of week)(command)
* * = means all possible values
* - = range of time units
* , = comma seperated time units
* / = increments where start is left and right is how much to increment by till max hit
*/
const COLUMN_SIZE = 14;
const fields = [
"minute",
"hour",
"dayOfMonth",
"month",
"dayOfWeek",
"command",
];
const labels = {
minute: "minute",
hour: "hour",
dayOfMonth: "day of month",
month: "month",
dayOfWeek: "day of week",
command: "command",
};
const fieldMap = {
minute: {
label: "minute",
range: [0, 59],
},
hour: {
label: "hour",
range: [0, 23],
},
dayOfMonth: {
label: "day of month",
range: [1, 31],
},
month: {
label: "month",
range: [1, 12],
},
dayOfWeek: {
label: "day of week",
range: [1, 7],
},
};
const numberParser = (field, value) => {
if (!isNaN(value)) {
value = Number(value);
const [low, high] = fieldMap[field].range;
if (value < low || value > high) {
throw new RangeError(`Invalid range.`);
}
return "" + value;
}
};
const commaParser = (field, value, separator = " ") => {
if (/^[0-9]+(,[0-9]+)*$/.test(value)) {
const parts = value.split(",");
return parts.join(separator);
}
};
const rangeParser = (field, value) => {
if (/^[0-9]+-[0-9]+$/.test(value)) {
const [low, high] = value.split("-");
return expand({
low,
high,
range: fieldMap[field].range,
});
}
};
const starParser = (field, value) => {
if (value === "*") {
const [low, high] = fieldMap[field].range;
return expand({ low, high });
}
};
const stepParser = (field, value) => {
if (value.indexOf("/") > 0) {
const [start, step] = value.split("/");
let [low, high] = fieldMap[field].range;
if (start !== "*") {
low = Number(start);
}
return expand({ low, high, step });
}
};
const parsers = [
numberParser,
stepParser,
commaParser,
rangeParser,
starParser,
];
const expand = ({ low, high, range = [], step = 1 }) => {
low = Number(low);
high = Number(high);
step = Number(step);
if (low > high) return [];
const [min, max] = range;
const result = [];
let current = low;
while (current <= high) {
if ((min != null && current < min) || (max != null && current > max)) {
throw new RangeError(`Invalid range.`);
}
result.push(current);
current += step;
}
return result.join(" ");
};
const formattedOutput = (parsed, padding = COLUMN_SIZE) => {
const output = [];
for (let field of fields) {
output.push(`${labels[field].padEnd(padding)} ${parsed[field]}`);
}
return output.join("\n");
};
const parse = (str) => {
if (typeof str !== "string") {
throw new TypeError("Expected a string");
}
str = str.trim();
const parts = str.split(" ");
if (parts.length !== 6) {
throw new TypeError("Invalid cron format");
}
const command = parts[5];
const result = Object.create(null);
for (let idx = 0; idx < fields.length; idx++) {
const field = fields[idx];
let value = field === "command" ? command : "-";
if (field === "command") {
result[field] = value;
continue;
}
for (let i = 0; i < parsers.length; i++) {
const parser = parsers[i];
const result = parser(field, parts[idx]);
if (result != null) {
value = result;
break;
}
}
result[field] = value;
}
return result;
};
module.exports = {
parse,
formattedOutput,
};
</code></pre>
<h3>Test</h3>
<pre><code>const test = require("ava");
const { parse } = require("./lib");
test("throws", (t) => {
let error = t.throws(
() => {
parse();
},
{ instanceOf: TypeError }
);
t.is(error.message, "Expected a string");
error = t.throws(
() => {
parse(1234);
},
{ instanceOf: TypeError }
);
t.is(error.message, "Expected a string");
error = t.throws(
() => {
parse("* * * *");
},
{ instanceOf: TypeError }
);
t.is(error.message, "Invalid cron format");
});
test("parse", (t) => {
const { minute, hour, month, dayOfMonth, dayOfWeek, command } = parse(
"*/15 0 1,15 * 1-5 /usr/bin/find"
);
t.is(month, "1 2 3 4 5 6 7 8 9 10 11 12");
t.is(dayOfMonth, "1 15");
t.is(dayOfWeek, "1 2 3 4 5");
t.is(command, "/usr/bin/find");
t.is(parse("*/15 0 1,15 * 1-5 /usr/bin/find").minute, "0 15 30 45");
t.is(parse("1/30 0 1,15 * 1-5 /usr/bin/find").minute, "1 31");
t.is(parse("1/30 1 1,15 * 1-5 /usr/bin/find").hour, "1");
t.is(parse("1/30 1-3 1,15 * 1-5 /usr/bin/find").hour, "1 2 3");
t.is(parse("1/30 0 1,15,16 * 1-5 /usr/bin/find").dayOfMonth, "1 15 16");
t.is(parse("1/30 0 21 * 1-5 /usr/bin/find").dayOfMonth, "21");
t.is(
parse("1/30 1 1,15 * 1-5 /usr/bin/find").month,
"1 2 3 4 5 6 7 8 9 10 11 12"
);
t.is(parse("1/30 1 1,15 */2 1-5 /usr/bin/find").month, "1 3 5 7 9 11");
t.is(parse("1/30 0 1,15 * 1-7 /usr/bin/find").dayOfWeek, "1 2 3 4 5 6 7");
t.is(parse("1-6 0 1,15 * 1-7 /usr/bin/find").minute, "1 2 3 4 5 6");
t.is(parse("1/30 1 1,15 * 1-5 /usr/bin/find").command, "/usr/bin/find");
});
test("throws on invalid input range", (t) => {
let error = t.throws(
() => {
parse("1-60 0 1,15 * 1-7 /usr/bin/find");
},
{ instanceOf: RangeError }
);
t.is(error.message, "Invalid range.");
error = t.throws(
() => {
parse("1-59 24 1,15 * 1-8 /usr/bin/find");
},
{ instanceOf: RangeError }
);
t.is(error.message, "Invalid range.");
error = t.throws(
() => {
parse("1-59 23 1,15 * 1-8 /usr/bin/find");
},
{ instanceOf: RangeError }
);
t.is(error.message, "Invalid range.");
error = t.throws(
() => {
parse("1-59 -23 1,15 * 1-7 /usr/bin/find");
},
{ instanceOf: RangeError }
);
t.is(error.message, "Invalid range.");
});
</code></pre>
<h3>Questions</h3>
<ol>
<li>I would like to understand how can I make this code production ready?</li>
<li>How can I do to make sure it runs on multiple platform?</li>
<li>Are the test cases good enough?</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T06:31:58.283",
"Id": "506543",
"Score": "0",
"body": "Why multiple parsers? They should parse every level of expression by invoke each other. For example, how would you handle `3,4-6,8-20/2,30/5 * * * *` and even `*,3,4 * * * *`? Why parser return an string instead of array of integers? May command includes spaces?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-25T14:11:58.823",
"Id": "256439",
"Score": "2",
"Tags": [
"javascript",
"programming-challenge",
"design-patterns",
"node.js",
"interview-questions"
],
"Title": "Cron expression parser"
}
|
256439
|
<p>In order to learn Rust I'm going through The Rust Book and did the implemented a program for <a href="https://doc.rust-lang.org/stable/book/ch03-05-control-flow.html#summary" rel="noreferrer">the following exercise</a>:</p>
<blockquote>
<p>Print the lyrics to the Christmas carol “The Twelve Days of Christmas,” taking advantage of the repetition in the song.</p>
</blockquote>
<p>I have decided to use lookup tables for the repeating lines of the song and ordinals because I believe those to be good for performance.</p>
<p>I'd appreciate any comments on my code, especially any suggestions on how to avoid the recurring magic number <code>12</code>.</p>
<pre class="lang-rust prettyprint-override"><code>type Day = u8;
const LYRICS: [&str; 12] = [
"a partridge in a pear tree",
"two turtle doves",
"three French hens",
"four calling birds",
"five gold rings",
"six geese a laying",
"seven swans a swimming",
"eight maids a milking",
"nine ladies dancing",
"ten lords a leaping",
"eleven pipers piping",
"twelve drummers drumming",
];
const ORDINALS: [&str; 12] = [
"first",
"second",
"third",
"fourth",
"fifth",
"sixth",
"seventh",
"eigth",
"ninth",
"tenth",
"eleventh",
"twelfth",
];
fn main() {
for day in 0..12 {
if day != 0 {
println!();
}
print_first_line(day);
print_lyrics(day);
}
}
fn print_first_line(day: Day) {
println!(
"On the {} day of Christmas my true love gave to me",
ORDINALS[day as usize],
)
}
fn print_lyrics(day: Day) {
for line in (0..=day).rev() {
if line == 0 && day != 0 {
println!("And {}", LYRICS[line as usize]);
} else {
println!("{}", capitalize(LYRICS[line as usize]));
}
}
}
fn capitalize(text: &str) -> String {
let mut chars = text.chars();
let mut new_text = String::with_capacity(text.len());
if let Some(c) = chars.next() {
new_text.extend(c.to_uppercase());
new_text.extend(chars);
}
new_text
}
</code></pre>
|
[] |
[
{
"body": "<p>Nicely done, I have very little negative to say!\nMost of this answer will be an exploration into some more advanced ways of doing what you are doing, overkill for this case, but very useful in larger projects.</p>\n<ul>\n<li><p>The <code>day as usize</code> everywhere is a bit of a distraction. I definitely understand the desire to store a small int when your data is known to be small (i.e. at most 11), but in this case you are only using <code>Day</code> as an index, so using <code>type Day = usize</code> directly seems like better design.</p>\n</li>\n<li><p>However, if you want to be fancy (and/or learn a bit about implementing your own types in Rust), you have an alternative which I will describe below: the basic idea is to implement your own types (use <code>struct A(B)</code> instead of <code>type A = B</code>), then implement the <code>Index</code> trait to index using <code>Day</code> directly.\nFor a small piece of code like this, it doesn't make a huge difference, but for large projects it's really helpful to avoid accidental mistakes like indexing an array with the wrong variable (i.e. in your case, indexing with some random usize in context instead of a <code>Day</code> between 0 and 11).\nIf you do that you get a type error, and this also allows you to abstract better: treating <code>Day</code> as an opaque type that is used to get the lyrics from your lyrics objects, rather than as an integer with arbitrary functionality. As an added bonus, this also helps avoid the magic number 12 problem that you mention.</p>\n<p>Diving in, we start by defining new types (<code>struct A(B)</code>) for <code>Day</code> and for a list indexed by <code>Day</code>.\nThe <code>#[derive(...)]</code> is telling Rust that we want Days to be able to be copied, checked for equality, and printed out, copying over that functionality from <code>u8</code>.</p>\n<pre><code>#[derive(Clone, Copy, Debug, Eq, PartialEq)]\nstruct Day(u8);\n\n#[derive(Debug)]\nstruct DayList<T>([T; 12]);\n\nconst FIRST_DAY: Day = Day(0);\nconst LAST_DAY: Day = Day(11);\n\nconst LYRICS: DayList<&str> = DayList([\n ...\n</code></pre>\n<p>Then, we implement the ability to index <code>DayList</code> objects with <code>Day</code>.\nFor a variable of type <code>A</code> where we defined <code>struct A(B)</code>, we use <code>x.0</code> to get the underlying <code>B</code> data.\n(This explicitness is part of the point of doing this, we make sure to keep <code>A</code> variables and <code>B</code> variables separate.)</p>\n<pre><code>impl<T> Index<Day> for DayList<T> {\n type Output = T;\n fn index(&self, day: Day) -> &T {\n self.0.index(day.0 as usize)\n }\n}\n</code></pre>\n<p>Finally, we want to be able to iterate over days, something like this utility function seems most useful for your code:</p>\n<pre><code>fn days_upto(day: Day) -> impl DoubleEndedIterator<Item = Day> {\n (0..=day.0).map(Day)\n}\n</code></pre>\n<p>This takes a <code>Day</code> and iterates over all days up to and including it. Perhaps this seems like overkill! But we get a lot of benefit out of it: now we can modify the rest of your code to not have indices at all, and only iterate over Days directly and index <code>DayList</code> with <code>Day</code>. Type safety! Here's how it looks:</p>\n<pre><code>fn main() {\n for day in days_upto(LAST_DAY) {\n if day != FIRST_DAY {\n println!();\n }\n\n print_first_line(day);\n print_lyrics(day);\n }\n}\n\nfn print_first_line(day: Day) {\n println!(\n "On the {} day of Christmas my true love gave to me",\n ORDINALS[day],\n )\n}\n\nfn print_lyrics(day: Day) {\n for line in days_upto(day).rev() {\n if line == FIRST_DAY && day != FIRST_DAY {\n println!("And {}", LYRICS[line]);\n } else {\n println!("{}", capitalize(LYRICS[line]));\n }\n }\n}\n</code></pre>\n</li>\n<li><p>Finally: the if block</p>\n<pre><code>if day != FIRST_DAY {\n println!();\n}\n</code></pre>\n<p>can be avoided if you print a title with the lyrics as well, which seems realistic. E.g.:</p>\n<pre><code>println!("The Twelve Days of Christmas");\nprintln!("----------------------------");\nfor day in days_upto(LAST_DAY) {\n println!();\n print_first_line(day);\n print_lyrics(day);\n}\n</code></pre>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-25T18:41:46.567",
"Id": "256445",
"ParentId": "256444",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "256445",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-25T17:17:26.453",
"Id": "256444",
"Score": "5",
"Tags": [
"performance",
"rust",
"lookup"
],
"Title": "Rust Book: The Twelve Days of Christmas"
}
|
256444
|
<p>I have been working on a function which I call <code>report</code>. What it does is that whenever I call the <code>report</code> function. I can give it a payload of my dict with some data and as well as <code>reason</code> where I can have custom message or the exception errors of whatever can happened.</p>
<p>For now I have created something simple where I create names for <code>file_path</code> and <code>filename</code>. I check if there is a path for that name already and if not then we create. We create a JSON file with the report data to my local PC and then I send it to discord. Both the JSON file and a small text that describes that there has been and error and to check it out ASAP.</p>
<p>My question here is pretty simple to see if there is anything I can actually improve my code somehow. Make it less code or a better report, I take whatever possible!</p>
<pre><code>#!/usr/bin/python3
# -*- coding: utf-8 -*-
import json
import os
import time
from datetime import datetime
from typing import List
from discord_webhook import DiscordEmbed, DiscordWebhook
# payload example payload = {"store": "burger-king"}
# reason = Custom message or exception err
def report(payload=None, reason=None):
webhook = DiscordWebhook(
url="https://discord....."
)
embed = DiscordEmbed(title="An error has occurred", color=16711680)
# -------------------------------------------------------------------------
# Create file path and filename
# -------------------------------------------------------------------------
file_path = f'./error/{payload["store"] if payload else "Other"}'
filename = f'{datetime.strftime(datetime.now(), "%Y-%m-%d_%H-%M-%S-%f")}.json'
# Check if the path already exists
if not os.path.exists(file_path):
os.makedirs(file_path)
# Write to a JSON file
with open(f"{file_path}/{filename}", "w", encoding="utf-8") as f:
f.write(json.dumps(
{
"payload": payload if payload else None,
"reason": str(reason)
},
indent=4,
ensure_ascii=False
))
# -------------------------------------------------------------------------
# Filename embed
# -------------------------------------------------------------------------
embed.add_embed_field(name="Filename", value=filename, inline=False)
# -------------------------------------------------------------------------
# Send files to discord
# -------------------------------------------------------------------------
with open(f"{file_path}/{filename}", "rb") as f:
webhook.add_file(file=f.read(), filename=f"{filename}")
# -------------------------------------------------------------------------
# Footer timestamp
# -------------------------------------------------------------------------
embed.set_footer(text=f'AutoSnkr | {datetime.now().strftime("%Y-%m-%d [%H:%M:%S.%f")[:-3]}]')
webhook.add_embed(embed)
# -------------------------------------------------------------------------
# Send to discord with exceptions
# -------------------------------------------------------------------------
while True:
response = webhook.execute()
# Workaround bug from discord_webhook pypi
if isinstance(response, List):
assert (len(response) == 1)
response = response[0]
# Successful requests
if response.ok:
return
# Rate limit. Wait until the limitation is gone
elif response.status_code == 429:
sleep_time = int(response.headers["retry-after"]) / 1000
time.sleep(sleep_time)
else:
print("Big error here! This text needs to be replaced later on")
return
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li>There's comments above <code>report</code> which should really be a docstring,\nsince they explain the function's workings.</li>\n<li>The default parameters for <code>report</code> are a bit suspect:\n<ul>\n<li>The expression <code>payload if payload else None</code> is redundant, can just\nbe <code>payload</code> then.</li>\n<li><code>str(reason)</code> for the default value <code>None</code> for <code>reason</code> is odd,\nmaybe that also needs special casing and could be left out of the\nJSON body?</li>\n</ul>\n</li>\n<li>Does the value from <code>payload["store"]</code> need escaping / is it safe?\nE.g. if it's coming from the server you'd have to validate it before\nusing it as part of a filename to prevent attacks.</li>\n<li>I feel it's a bit over-commented. Consider "Create file path and\nfilename" - that's basically what I can discern from the block below,\nsame as "Check if the path already exists", that's basically the same\nas the line <code>if not os.path.exists(file_path)</code>. Consider splitting\noff smaller functions that have descriptive names instead of one huge\nfunction, that way you wouldn't have to comment on blocks of code (and\nwould instead use the function names as descriptors).</li>\n<li><code>with</code> is used, good.</li>\n<li><code>os.makedirs</code> won't do anything if the path already exists, so the\ncheck before it is redundant.</li>\n<li>Consider making <code>webhook</code> and <code>embed</code> (global) constants, they\notherwise don't seem to add anything to the function.</li>\n<li>After writing the JSON to the file, it's immediately being read back\nfor the <code>webhook.add_file</code> - avoid that unnecessary computation and\nreuse the in-memory representation of the data.</li>\n<li>Again, consider splitting the setup phase and the <code>while True</code> loop\ninto separate functions to help understanding and, potentially,\ntestability.</li>\n<li>The only thing I'd have to complain about in the loop is the fetching\nof the retry timeout value: Be conservative in what you expect. The\nserver doesn't <em>have</em> to send that value and if it doesn't you'll get\nexceptions. Consider providing a default value and a maximum sleep\namount to not open yourself up to a malicious server (yes, that's a\nstretch, but still).</li>\n<li>Just noticed: You're importing <code>typing.List</code> just to check\n<code>isinstance</code> - AFAIK you can just use <code>isinstance(response, list)</code>\nwithout the need to import the <code>typing</code> module. Of course using\n<code>typing</code> is great, you'd just have annotate your functions most likely\nand use <code>mypy</code> or a similar type-checker ...</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T17:30:42.830",
"Id": "506384",
"Score": "1",
"body": "Appreciate the beautiful code review! There was alot of new stuff I wouldn't think of and will of course add it to my code! Thank you so much for it!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T11:07:08.557",
"Id": "256464",
"ParentId": "256446",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "256464",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-25T19:40:49.463",
"Id": "256446",
"Score": "2",
"Tags": [
"python",
"python-3.x"
],
"Title": "Create file path and filename in JSON and send it to Discord"
}
|
256446
|
<p>I've just started doing programming problems.</p>
<p><a href="https://icpcarchive.ecs.baylor.edu/external/58/p5880.pdf" rel="nofollow noreferrer">https://icpcarchive.ecs.baylor.edu/external/58/p5880.pdf</a></p>
<p>The code below works fine, but my run time is 2.715 seconds and the time limit is 3 seconds.</p>
<p>How can I improve speed of this code?</p>
<p><em>I've already started to use <code>sys.stdin</code> instead of <code>input()</code>.</em></p>
<pre><code>import string
import sys
while True:
key = sys.stdin.readline().strip()
key = int(key) if key.isdigit() else key
if key == 0: break
decrypted_msg = sys.stdin.readline().strip()
decrypted_msg = int(decrypted_msg) if decrypted_msg.isdigit() else decrypted_msg
if decrypted_msg == 0: break
key = (len(decrypted_msg)//len(key) + 1) * key
key = key[0:len(decrypted_msg)]
encrypted_msg = ""
for i in range(len(decrypted_msg)):
key_idx = string.ascii_uppercase.index(key[i])
deciphered_idx = string.ascii_uppercase.index(decrypted_msg[i])
enciphered_idx = (deciphered_idx + key_idx + 1) % len(string.ascii_uppercase)
encrypted_msg += string.ascii_uppercase[enciphered_idx]
print(encrypted_msg)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-25T23:08:46.590",
"Id": "506320",
"Score": "0",
"body": "Where can solutions be submitted?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T16:37:50.347",
"Id": "506376",
"Score": "2",
"body": "Welcome to Code Review! Thanks for providing a link to the specification, but do note that a question should be complete in itself. Please [edit] to [include a short description of the requirements **in the body of the question**.](//codereview.meta.stackexchange.com/q/1993) Obviously, you should take care not to infringe copyrights in the process of fixing this."
}
] |
[
{
"body": "<h2>Comments</h2>\n<ul>\n<li><code>decrypted_msg</code> is misleading. It's not decrypted but rather "not encrypted". But really just call it "plaintext", as the problem statement does.</li>\n<li>Similarly, "enciphered" and "encrypted" are not just inconsistent (make up your mind), but go against the problem statement's term "ciphertext".</li>\n<li>The end-signal string <code>'0'</code> can simply be checked as a string.</li>\n<li>No need to check the plaintext against <code>'0'</code>.</li>\n<li>Mapping <code>str.strip</code> over <code>sys.stdin</code> makes the code a bit nicer. We can even use a nice <code>for</code> statement then.</li>\n<li>Better just <code>zip</code> the plaintext and key instead of iterating over indices.</li>\n<li>Searching the letters in the alphabet string isn't super terrible, but it's apparently faster to look up letter pairs in a dictionary.</li>\n<li><a href=\"https://docs.python.org/3/library/itertools.html#itertools.cycle\" rel=\"noreferrer\"><code>itertools.cycle</code></a> is a nicer (and I think faster) way to cycle the key.</li>\n<li>Repeatedly extending a string with <code>+=</code> might <a href=\"https://stackoverflow.com/q/44487537/12671057\">degrade to quadratic time</a> overall. Better use <code>''.join</code> on an iterable.</li>\n<li>A little time can be saved by storing <code>string.ascii_uppercase.index</code> in a variable instead of looking up the attributes <code>ascii_uppercase</code> and <code>index</code> over and over again.</li>\n</ul>\n<h2>Solution 1: My fastest<sup>[*]</sup>, using a lookup-table mapping letter pairs to single letters</h2>\n<p>This gets accepted in 0.382 seconds <a href=\"https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=3891\" rel=\"noreferrer\">here</a>, where I believe you submitted yours (tried four times, impressively always got the exact same time).</p>\n<p>[*] In my <a href=\"https://codereview.stackexchange.com/a/256478/219610\">other answer</a> benchmarking a worst case, actually my solution 3 is fastest.</p>\n<pre><code>import sys\nfrom itertools import cycle\nfrom string import ascii_uppercase as abc\n\ntable = {(abc[i], abc[j]): abc[(i + j + 1) % 26]\n for i in range(26)\n for j in range(26)}.get\n\nlines = map(str.strip, sys.stdin)\nfor key in lines:\n if key == '0':\n break\n plaintext = next(lines)\n\n print(''.join(map(table, zip(plaintext, cycle(key)))))\n</code></pre>\n<p>I did get it down to 0.372 seconds by using <code>sys.stdout.write</code>, but meh, not worth it.</p>\n<h2>Solution 2: My fastest with <code>str.index</code>:</h2>\n<p>Here's the fastest I got with <code>str.index</code>, got accepted in 0.699 seconds. Note that my <code>bcd</code> is <em>twice</em> the alphabet and starts with "B", so I can use <code>bcd[p + k]</code> instead of the slower <code>abc[(p + k + 1) % 26]</code>.</p>\n<pre><code>from string import ascii_uppercase as abc\nimport sys\nfrom itertools import cycle\n\nindex = abc.index\nbcd = abc[1:] + abc\n\nlines = map(str.strip, sys.stdin)\nfor key in lines:\n if key == '0':\n break\n plaintext = next(lines)\n\n key = cycle(map(index, key))\n plaintext = map(index, plaintext)\n \n print(''.join([bcd[p + k] for p, k in zip(plaintext, key)]))\n</code></pre>\n<h2>Solution 3: O(|key|) Python operations</h2>\n<p>Since the plaintext has up to 100,000 letters but the key has only up to 1,000 letters, and since Python operations are slow, I also tried doing just O(|key|) Python operations instead of O(|plaintext|) Python operations. By using <code>str.translate</code>. For example if the key is <code>'KEY'</code>, then the entire string slice <code>plaintext[0::3]</code> is translated with the key letter <code>'K'</code>. And <code>[1::3]</code> and <code>[2::3]</code> get translated with <code>'E'</code> and <code>'Y'</code>, respectively. Sadly, it was slower, got accepted in 0.985 seconds:</p>\n<pre><code>import sys\nfrom string import ascii_uppercase as abc\n\ntables = {c: str.maketrans(abc, abc[i:] + abc[:i])\n for i, c in enumerate(abc, 1)}\n\nlines = map(str.strip, sys.stdin)\nfor key in lines:\n if key == '0':\n break\n plaintext = next(lines)\n\n ciphertext = [None] * len(plaintext)\n n = len(key)\n for i, k in enumerate(key):\n ciphertext[i::n] = plaintext[i::n].translate(tables[k])\n\n print(''.join(ciphertext))\n</code></pre>\n<h2>Solution 3b: Using <code>bytearray</code></h2>\n<p>Solution 3 but with <code>bytes</code>/<code>bytearray</code> instead of <code>str</code>. Accepted in 0.619 seconds. Not sure whether it's the input/output or the <code>bytearray.translate</code> that's responsible for the speed-up:</p>\n<pre><code>import sys\nfrom string import ascii_uppercase as abc\n\nabc = abc.encode()\ntables = {c: bytearray.maketrans(abc, abc[i:] + abc[:i])\n for i, c in enumerate(abc, 1)}\n\nlines = map(bytes.strip, sys.stdin.buffer)\nwrite = sys.stdout.buffer.write\nfor key in lines:\n if key == b'0':\n break\n plaintext = next(lines)\n\n ciphertext = bytearray(plaintext)\n n = len(key)\n for i, k in enumerate(key):\n ciphertext[i::n] = ciphertext[i::n].translate(tables[k])\n\n write(ciphertext)\n write(b'\\n')\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T02:37:49.190",
"Id": "506324",
"Score": "1",
"body": "This is a good answer -- well done. I had a couple beers and typed my response without thinking too hard about the algorithm. Anyway, I encourage the OP to focus on this reply, but I'll leave my answer up, because it does have some useful points about how to set up an overall program in a useful way for experimentation."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T00:26:43.463",
"Id": "256453",
"ParentId": "256447",
"Score": "13"
}
},
{
"body": "<p>Start with some of the low-hanging fruit. (1) Inside your primary for-loop, you\nrepeatedly used <code>index()</code> to hunt for a value that can be easily computed in\nadvance. (2) You are assembling the output data via string concatenation, but\nPython strings are immutable, which implies the creation of an entirely new\nstring on each iteration of the loop. That can become problematic when\ndealing with larger inputs. Here's an edited version with those\nissues in mind. It sticks fairly closely to your original code.</p>\n<pre><code>import string\nimport sys\n\n# Create an dict mapping each uppercase letter to its index in\n# string.ascii_uppercase. In addition, (and these changse are much less\n# important) make `letters` a local variable so we don't have to perform an\n# attribute lookup on `string.ascii_uppercase` inside the loop. And define\n# a constant to eliminate the need to call `len()` repeatedly.\nletters = string.ascii_uppercase\nletter_indexes = {c : i for i, c in enumerate(letters)}\nn_letters = len(letters)\n\nwhile True:\n key = sys.stdin.readline().strip()\n\n # Simplifying the loop-break logic.\n if key == '0':\n break\n\n decrypted_msg = sys.stdin.readline().strip()\n\n # Simplifying the key-creation logic.\n # We don't care whether `key` is too long.\n key = (len(decrypted_msg)//len(key) + 1) * key\n\n # We will append characters to a list rather\n # than creating a fresh string each time.\n encrypted_chars = []\n\n for i in range(len(decrypted_msg)):\n key_idx = letter_indexes[key[i]]\n deciphered_idx = letter_indexes[decrypted_msg[i]]\n\n enciphered_idx = (deciphered_idx + key_idx + 1) % n_letters\n encrypted_chars.append(letters[enciphered_idx])\n\n # Assemble the final string.\n enciphered_msg = ''.join(encrypted_chars)\n print(enciphered_msg)\n</code></pre>\n<p>Your program is difficult to test and debug, due to its larger design. For\nexample, your linked pdf provided some sample inputs and expected outputs, but\nthe program itself did not provide easy ways to toggle between its "real life"\nusage (reading from <code>stdin</code>, in this case) and various testing/debugging usages.\nThis adds friction to attempts to experiment with program, hampering the\nability to make refinements, simplifications, and speed enhancements. A more\nflexible approach is to keep the Vigenère algorithm completely isolated from\nthe orchestration tasks of handling inputs and different usage modes.</p>\n<p>The code below provides a sketch of a more flexible structure. It also\nillustrates how to take advantage of <code>zip()</code> and <code>itertools.cycle()</code> to\nsimplify the code logic -- and, in particular, to rely less on manual indexing\ninto strings. Although this part of the answer was not intended to provide\nadditional speed-ups, at least in my not-very-sophisticated experiments, these\nchanges also made the algorithm notably faster.</p>\n<p>Finally, the edited <code>vigenere()</code>\nfunction provides a nice illustration of the way that <strong>carefully chosen,\nshorter variable names</strong> can increase code readability and clarity -- provided\nthat those shorter names are within a narrow context (i.e., a short function)\nand have sufficient contextual information (e.g., code comments and nearby\nfunction/variable names that are more explicit).</p>\n<pre><code>import string\nimport sys\nfrom itertools import cycle\n\n# Test data from the pdf file.\nTESTS = [\n ['ICPC', 'THISISSECRETMESSAGE', 'CKYVRVIHLUUWVHIVJJU'],\n ['ACM', 'CENTRALEUROPEPROGRAMMINGCONTEST', 'DHAUUNMHHSRCFSEPJEBPZJQTDRAUHFU'],\n ['LONGKEY', 'CERC', 'OTFJ'],\n]\n\ndef main(args):\n if args and args[0] == 'test':\n # Make sure our vigenere() is still OK.\n for key, text, expected in TESTS:\n encrypted = vigenere(text, key)\n print(encrypted == expected, encrypted)\n else:\n # The coding challenge use case.\n while True:\n key = sys.stdin.readline().strip()\n if key == '0':\n break\n text = sys.stdin.readline().strip()\n encrypted = vigenere(text, key)\n print(encrypted)\n\ndef vigenere(text, key):\n # Takes text and a key.\n # Returns encrypted text.\n\n # Prepare letter index lookup.\n letters = string.ascii_uppercase\n indexes = {c : i for i, c in enumerate(letters)}\n n_letters = len(letters)\n\n # Encrypt the text.\n encrypted_chars = []\n for t, k in zip(text, cycle(key)):\n ti = indexes[t]\n ki = indexes[k]\n ei = (ti + ki + 1) % n_letters\n encrypted_chars.append(letters[ei])\n\n # Return as string.\n return ''.join(encrypted_chars)\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T03:54:41.510",
"Id": "506325",
"Score": "1",
"body": "Good point with the separate `vigenere` function and structure. Since you didn't post times, I took the liberty to submit your solutions myself, got accepted in 1.499 seconds and 0.782 seconds. While strings are ostensibly immutable, they aren't really, and optimizations in Python/C/OS can keep the string-building with `+=` fast."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T16:34:10.827",
"Id": "506374",
"Score": "0",
"body": "Added a [benchmarks answer](https://codereview.stackexchange.com/a/256478/219610). Oddly, your two solutions are almost equally fast. Maybe I made some mistake, but I don't see it :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T16:41:52.613",
"Id": "506378",
"Score": "0",
"body": "@KellyBundy I'm not entirely surprised by that. My 2nd answer wasn't intended to provide a speed boost. It did seem faster in a \"test\" I ran (I just multiplied the input text to make it 50000x longer, and used Unix `time` to measure), but I wasn't rigorous at all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T16:43:18.267",
"Id": "506379",
"Score": "0",
"body": "Yeah, just changed that answer to say it's probably more odd that the difference was so large on the judge site."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T18:56:34.247",
"Id": "506388",
"Score": "0",
"body": "@KellyBundy Regarding the performance of large-scale string concatenation, I understand your point. But over the years I have observed real impacts – not disastrous ones (affirming your main point), but still significant (indicating that it's good practice to behave *as if* strings were immutable under the hood). If we take my v1 code and use the pdf example inputs (multiplied in size to 50000x), I get the following from Unix `time`: 1.6 sec for string-concatenation (using `+=`) vs 1.3 sec for list-append. Admittedly, not the most robust test, but the result agrees with past recollections."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T23:44:57.187",
"Id": "506416",
"Score": "1",
"body": "Yes, I agree `''.join` is better. At first, my list of comments didn't even include that even though my code did, I guess I'm so used to it that I forgot I had done it :-). I took another look at your solutions at the judge site. Originally I had submitted them as-is (since they're made for that), now I also submitted the first one after putting the algorithm and all its variables into a function. That made it almost as fast as your second solution there (see comments under my newer answer). So apparently the *function*-local variables are the main reason your second solution is faster."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T02:30:45.407",
"Id": "256454",
"ParentId": "256447",
"Score": "3"
}
},
{
"body": "<p><strong>Benchmarking</strong> a worst-case (key with 1,000 random letters and plaintext with 100,000 random letters).</p>\n<p>As @FMc <a href=\"https://codereview.stackexchange.com/a/256454/219610\">pointed out</a>, isolating the Vigenère algorithm in a function is helpful. Here I do that for benchmarking.</p>\n<p><strong>Benchmark results:</strong></p>\n<pre><code>74.76 ms 73.98 ms 73.28 ms original\n 8.97 ms 8.34 ms 8.01 ms Kelly_Bundy_1\n20.81 ms 20.70 ms 21.24 ms Kelly_Bundy_2\n 4.28 ms 4.18 ms 4.10 ms Kelly_Bundy_3\n22.58 ms 22.18 ms 22.62 ms FMc_1\n21.22 ms 20.92 ms 21.62 ms FMc_2\n</code></pre>\n<p>I'm quite happy to see that my third solution (encrypting entire slices with <code>str.translate</code>) is fastest at this. So apparently the judge site's test suite differs significantly from this worst case.</p>\n<p><strong>Benchmark code:</strong></p>\n<pre><code>def main():\n\n from timeit import repeat\n import random\n import string\n \n funcs = original, Kelly_Bundy_1, Kelly_Bundy_2, Kelly_Bundy_3, FMc_1, FMc_2\n \n def random_string(length):\n return ''.join(random.choices(string.ascii_uppercase, k=length))\n\n key = random_string(1_000)\n plaintext = random_string(100_000)\n number = 10\n\n args = key, plaintext\n\n # Correctness\n expect = original(*args)\n for func in funcs:\n result = func(*args)\n print(result == expect, func.__name__)\n if result != expect:\n print(len(expect), len(result), expect[:20], result[:20])\n print()\n\n # Speed\n tss = [[] for _ in funcs]\n for _ in range(3):\n for func, ts in zip(funcs, tss):\n t = min(repeat(lambda: func(*args), number=number)) / number\n ts.append(t)\n print(*('%5.2f ms ' % (t * 1e3) for t in ts), func.__name__)\n print()\n\n\ndef prep_original():\n import string\n return string,\n\ndef original(key, decrypted_msg, prepped=prep_original()):\n string, = prepped\n\n key = (len(decrypted_msg)//len(key) + 1) * key\n key = key[0:len(decrypted_msg)]\n\n encrypted_msg = ""\n\n for i in range(len(decrypted_msg)):\n key_idx = string.ascii_uppercase.index(key[i])\n deciphered_idx = string.ascii_uppercase.index(decrypted_msg[i])\n\n enciphered_idx = (deciphered_idx + key_idx + 1) % len(string.ascii_uppercase)\n encrypted_msg += string.ascii_uppercase[enciphered_idx]\n\n return encrypted_msg\n\n\ndef prep_Kelly_Bundy_1():\n from itertools import cycle\n from string import ascii_uppercase as abc\n table = {(abc[i], abc[j]): abc[(i + j + 1) % 26]\n for i in range(26)\n for j in range(26)}.get\n return cycle, table\n\ndef Kelly_Bundy_1(key, plaintext, prepped=prep_Kelly_Bundy_1()):\n cycle, table = prepped\n \n return ''.join(map(table, zip(plaintext, cycle(key))))\n\n\ndef prep_Kelly_Bundy_2():\n from string import ascii_uppercase as abc\n from itertools import cycle\n index = abc.index\n bcd = abc[1:] + abc\n return cycle, index, bcd\n \ndef Kelly_Bundy_2(key, plaintext, prepped=prep_Kelly_Bundy_2()):\n cycle, index, bcd = prepped\n \n key = cycle(map(index, key))\n plaintext = map(index, plaintext)\n \n return ''.join([bcd[p + k] for p, k in zip(plaintext, key)])\n\n\ndef prep_Kelly_Bundy_3():\n from string import ascii_uppercase as abc\n tables = {c: str.maketrans(abc, abc[i:] + abc[:i])\n for i, c in enumerate(abc, 1)}\n return tables,\n\ndef Kelly_Bundy_3(key, plaintext, prepped=prep_Kelly_Bundy_3()):\n tables, = prepped\n\n ciphertext = [None] * len(plaintext)\n n = len(key)\n for i, k in enumerate(key):\n ciphertext[i::n] = plaintext[i::n].translate(tables[k])\n\n return ''.join(ciphertext)\n\n\ndef prep_FMc_1():\n import string\n letters = string.ascii_uppercase\n letter_indexes = {c : i for i, c in enumerate(letters)}\n n_letters = len(letters)\n return letters, letter_indexes, n_letters\n\ndef FMc_1(key, decrypted_msg, prepped=prep_FMc_1()):\n letters, letter_indexes, n_letters = prepped\n \n key = (len(decrypted_msg)//len(key) + 1) * key\n encrypted_chars = []\n\n for i in range(len(decrypted_msg)):\n key_idx = letter_indexes[key[i]]\n deciphered_idx = letter_indexes[decrypted_msg[i]]\n\n enciphered_idx = (deciphered_idx + key_idx + 1) % n_letters\n encrypted_chars.append(letters[enciphered_idx])\n\n enciphered_msg = ''.join(encrypted_chars)\n return enciphered_msg\n\n\ndef prep_FMc_2():\n import string\n from itertools import cycle\n letters = string.ascii_uppercase\n indexes = {c : i for i, c in enumerate(letters)}\n n_letters = len(letters)\n return cycle, letters, indexes, n_letters\n\ndef FMc_2(key, text, prepped=prep_FMc_2()):\n cycle, letters, indexes, n_letters = prepped\n\n encrypted_chars = []\n for t, k in zip(text, cycle(key)):\n ti = indexes[t]\n ki = indexes[k]\n ei = (ti + ki + 1) % n_letters\n encrypted_chars.append(letters[ei])\n return ''.join(encrypted_chars)\n\nmain()\n</code></pre>\n<p><strong>Why does this differ from the judge site?</strong> Why is my third solution <em>slower</em> than my other two there, when it's faster here? As I explained in my other answer, the intuition for why it could be faster is that the length limits of 1,000 for the key and 100,000 for the plaintext suggest that the plaintext might typically be 100 times longer than the key. Or at least that there are a few test cases at those limits, which would dominate the overall ratio (small cases don't contribute much to the totals and thus to the overall ratio unless there are really many of them). So my third solution is based on the assumption that the total length of all plaintexts divided by the total length of all keys is about 100, making the overhead of using <code>str.translate</code> worth it. But it turns out that the real ratio is only between 2.14 and 2.15, as can be tested with this code that gets accepted (note the assertion at the end):</p>\n<pre><code>import sys\nfrom itertools import cycle\nfrom string import ascii_uppercase as abc\n\ntable = {(abc[i], abc[j]): abc[(i + j + 1) % 26]\n for i in range(26)\n for j in range(26)}.get\n\nk = p = 0\n\nlines = map(str.strip, sys.stdin)\nfor key in lines:\n if key == '0':\n break\n plaintext = next(lines)\n\n k += len(key)\n p += len(plaintext)\n\n print(''.join(map(table, zip(plaintext, cycle(key)))))\n\nassert 2.14 < p / k < 2.15\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T23:23:10.453",
"Id": "506413",
"Score": "0",
"body": "@Peilonrayz That judge is pretty consistent. I had already noticed that in my previous 43 submissions for this problem, and now I submitted FMc's two solutions again, each five times, alternating between the two (just like I cycle through the solutions in my benchmark, btw). The first solution took 1.372, 1.372, 1.378, 1.439, 1.368 seconds and the second took 0.759, 0.765, 0.775, 0.775, 0.779 seconds."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T23:25:13.240",
"Id": "506414",
"Score": "0",
"body": "Oh wow. Those are some consistent timings."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T23:33:42.430",
"Id": "506415",
"Score": "0",
"body": "@Peilonrayz Submitted FMc's first solution twice more, after modifying it just by putting stuff into a function. Improved to 0.839 and 0.836 seconds that way. Previously I had just submitted it as-is. So apparently most of the speed difference came from the speed of local vs global variables."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T16:32:31.310",
"Id": "256478",
"ParentId": "256447",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-25T20:04:21.557",
"Id": "256447",
"Score": "6",
"Tags": [
"python",
"performance"
],
"Title": "Vigenère Cipher problem in competitive programming"
}
|
256447
|
<p>What do you think about this assignment "idiom"?</p>
<pre><code>template <typename ...A>
constexpr auto assign(A& ...a) noexcept
{
return [&](auto&& ...v)
// noexcept(noexcept(((a = std::forward<decltype(v)>(v)), ...)))
{
((a = std::forward<decltype(v)>(v)), ...);
};
}
</code></pre>
<p>It seems a better alternative to me than the <code>std::tie()</code> idiom. Uncommenting the comment could cause a segfault in <code>gcc</code>.</p>
<p>Usage:</p>
<pre><code>int a, b, c;
assign(a, b, c)(1, 2, 3);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-25T21:51:19.823",
"Id": "506312",
"Score": "0",
"body": "Whether the syntax of your assignment idiom is better than std::tie is really questionable. Moreover, in c++17, structured bindings are much more neater. But +1 for use of lambda, I love lambdas in c++ they’re so op."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-25T22:18:34.987",
"Id": "506315",
"Score": "0",
"body": "structured bindings for assignment? How?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-25T22:47:45.117",
"Id": "506318",
"Score": "0",
"body": "One way: `auto [a, b, c] = std::array<int, 3>{1,2,3};`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-25T23:20:21.540",
"Id": "506321",
"Score": "2",
"body": "@SᴀᴍOnᴇᴌᴀ fwiw, I believe OP's question is OK (if brief, and looking for \"what do you think\" feedback instead of code review). The \"a,b,c\" business is just sample usage, like a unit test. The 9-line snippet at the top of the question really _is_ valid C++ — the `...` in it are real C++17 syntax."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T07:44:12.380",
"Id": "506328",
"Score": "0",
"body": "@user1095108, could you clarify the line about causing a segfault in GCC? Is that a current development GCC, or an older release? If the former, is there a bug report for it? I find it's very rare to crash the compiler, largely because of good bug-reporting."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T08:02:37.457",
"Id": "506330",
"Score": "0",
"body": "I reported the bug a long time ago and wasn't even the first person to do so. Supposedly, it's fixed now in the latest dev version, but not in 10.2 I currently use. Clang never had the bug."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T08:37:31.720",
"Id": "506331",
"Score": "0",
"body": "Why is there a close vote to this question? It is perfectly reasonable"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T14:13:04.770",
"Id": "506364",
"Score": "0",
"body": "My close vote is because this is stub code without context."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T15:31:28.583",
"Id": "506444",
"Score": "0",
"body": "What context could there possibly be? Assignment is universal."
}
] |
[
{
"body": "<p>This "idiom" seems strictly more confusing than the <code>std::tie(a,b,c) = std::make_tuple(1,2,3)</code> idiom. (I mean, the latter is an idiom because multiple people use it and know it. Your thing doesn't count as an idiom yet because nobody uses or understands it.)</p>\n<p>Your thing <em>does</em> save a lot of template instantiations — you don't have to instantiate <code>std::tuple</code> at all, for example. That's potentially nice for people who are doing lots of multiple assignments in header files and care about compile times. But who's doing lots of multiple assignments in header files??</p>\n<p>Your thing <em>doesn't</em> fix the <em>most</em> important shortcoming of <code>std::tie</code>, which is that you can't use it to introduce a new variable. It's still fundamentally a <code>std::cin</code>-style API, where the caller is supposed to define all their variables with garbage values and then use this API to <em>mutate</em> them into the desired state.</p>\n<pre><code>// To mutate three variables:\n\nint a, b, c;\nassign(a, b, c)(1, 2, 3);\nstd::tie(a, b, c) = std::tuple{1, 2, 3}; // same deal, easier to read, harder to compile\n\n// To define three new variables (ish):\n\nauto [a, b, c] = std::tuple{1, 2, 3};\n</code></pre>\n<p><a href=\"https://stackoverflow.com/questions/42590449/c17-structured-binding-that-also-includes-an-existing-variable\">"C++17 structured binding that also includes an existing variable"</a> gives the skeleton of an API that could be used to define and mutate different sets of variables at the same time:</p>\n<pre><code>// To define one new variable and mutate two others:\n\nauto [a] = AndTie(_1, b, c) = std::tuple{1, 2, 3};\n</code></pre>\n<p>But again, I wouldn't describe this as an "idiom", because if you showed it to an ordinary C++ programmer who knew all the C++ idioms, they likely still wouldn't understand it at a glance.</p>\n<hr />\n<p>Oh, and a code-style nit: I would prefer to see your fold-expression with spaces around the <code>,</code> operator, to emphasize that it's an operator and not a separator. Like this:</p>\n<pre><code>((a = std::forward<decltype(v)>(v)) , ...);\n</code></pre>\n<p>and in fact as long as we're saving on function template instantiations, let's do</p>\n<pre><code>((a = static_cast<decltype(v)>(v)) , ...);\n</code></pre>\n<p>The inner set of parentheses is redundant, I think, but I'm keeping them. (Precisely because I had to say "I think." I'm not even gonna go find out. They're a good idea.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-25T23:32:09.507",
"Id": "506322",
"Score": "0",
"body": "In a professional setting, I can imagine, that my \"idiom\" would be a big \"no no\" :) But in my personal projects, I really hate many lines of assignments. The \"idiom\" seems to have something going for it, one liner assignments, certain to confuse the uninitiated and maybe there's room for improvement."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-25T23:18:27.223",
"Id": "256451",
"ParentId": "256449",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-25T21:31:10.440",
"Id": "256449",
"Score": "2",
"Tags": [
"c++",
"c++17",
"template"
],
"Title": "Assignment function as alternative to std::tie"
}
|
256449
|
<p>I have a simple service class here which import csv or xml file into database using .NET Standard library C#.</p>
<p>Do you have any comments? Are there any recommended techniques to use instead of the <code>switch</code> statement in the method <code>ProcessPaymentFile</code>?</p>
<pre><code>public class AbcPaymentService : IAbcPaymentService
{
private readonly IAbcPaymentContext _abcPaymentContext;
private readonly IConfiguration _configuration;
public AbcPaymentService(IAbcPaymentContext abcPaymentContext, IConfiguration configuration)
{
_abcPaymentContext = abcPaymentContext;
_configuration = configuration;
}
public List<PaymentTransactionDetailResponse> GetTransactionsByCurrency(string currency)
{
var paymentTransactions = _abcPaymentContext.PaymentTransactions.Where(p => p.CurrencyCode == currency).ToList();
return MapPaymentTransactions(paymentTransactions);
}
public List<PaymentTransactionDetailResponse> GetTransactionsByDateRange(DateTime dateFrom, DateTime dateTo)
{
var paymentTransactions = _abcPaymentContext.PaymentTransactions
.Where(p => p.TransactionDate >= dateFrom && p.TransactionDate <= dateTo).ToList();
return MapPaymentTransactions(paymentTransactions);
}
public List<PaymentTransactionDetailResponse> GetTransactionsByStatus(string status)
{
// add more validation. ie. check length.
var paymentTransactions = _abcPaymentContext.PaymentTransactions.Where(p => p.Status == status).ToList();
return MapPaymentTransactions(paymentTransactions);
}
public void ProcessPaymentFile(IFormFile file)
{
#region Validation
var fileExtension = Path.GetExtension(file.FileName);
var validFileTypes = new[] { ".csv",".xml"}; // move to appsetting for easier configuration.
bool isValidType = validFileTypes.Any(t => t.Trim() == fileExtension.ToLower());
if (isValidType == false)
throw new ArgumentException($"Unknown format.");
if(file.Length > 1000) // move to appsetting for easier configuration.
throw new ArgumentException($"Invalid file size. Only less than 1 MB is allowed.");
#endregion
// Upload file to server
var target = _configuration["UploadPath"];
var filePath = Path.Combine(target, file.FileName);
try
{
using (var stream = new FileStream(filePath, FileMode.Create))
{
file.CopyTo(stream);
}
switch (fileExtension.ToLower())
{
case ".csv":
var config = new CsvConfiguration(CultureInfo.InvariantCulture)
{
HasHeaderRecord = false,
};
using (var reader = new StreamReader(filePath)) {
using (var csv = new CsvReader(reader, config))
{
csv.Context.RegisterClassMap<CsvMap>();
var paymentTransactionCsv = csv.GetRecords<Models.Xml.Transaction>().ToList();
SaveToDb(paymentTransactionCsv);
}
}
break;
case ".xml":
var serializer = new XmlSerializer(typeof(Models.Xml.Transactions));
using (TextReader reader = new StreamReader(new FileStream(filePath, FileMode.Open)))
{
var paymentTransactionXml = (Models.Xml.Transactions)serializer.Deserialize(reader);
SaveToDb(paymentTransactionXml.Transaction);
}
break;
default:
throw new ArgumentException($"Invalid file type. Only {string.Join(",", validFileTypes)} allowed.");
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
#region PrivateFunctions
private void SaveToDb(List<Models.Xml.Transaction> paymentTransactions)
{
if (PaymentTransactionXmlIsValid(paymentTransactions) == false)
throw new Exception("Invalid transaction."); // todo: write into log file or db
// if all validation passed, map objects and
var paymentTransactionsEntity = paymentTransactions.Select(p => new PaymentTransaction()
{
TransactionId = p.Id,
TransactionDate = p.TransactionDate,
Amount = Convert.ToDecimal(p.PaymentDetails.Amount),
CurrencyCode = p.PaymentDetails.CurrencyCode,
Status = Mapper.MapStatus(p.Status)
})
.ToList();
// save into db.
_abcPaymentContext.PaymentTransactions.AddRange(paymentTransactionsEntity);
_abcPaymentContext.SaveChanges();
// todo: don't insert duplicate transaction
}
private bool PaymentTransactionXmlIsValid(List<Models.Xml.Transaction> paymentTransactions)
{
foreach (var trans in paymentTransactions)
{
if (string.IsNullOrEmpty(trans.Id)) return false;
if (trans.TransactionDate == null) return false;
if(trans.PaymentDetails.Amount == 0) return false;
if (string.IsNullOrEmpty(trans.PaymentDetails.CurrencyCode)) return false;
if (string.IsNullOrEmpty(trans.Status)) return false;
}
return true;
}
private List<PaymentTransactionDetailResponse> MapPaymentTransactions(List<PaymentTransaction> paymentTransactions) {
// Construct Dto responses model.
var paymentTransactionDetailResponses = paymentTransactions.Select(p => new PaymentTransactionDetailResponse()
{
Id = p.TransactionId.ToString(),
Payment = $"{p.Amount} {p.CurrencyCode}",
Status = p.Status
}).ToList();
return paymentTransactionDetailResponses;
}
#endregion
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T17:10:35.390",
"Id": "506382",
"Score": "1",
"body": "`file.Length > 1000` A megabyte is 1024 kilobytes"
}
] |
[
{
"body": "<p>Quick remarks:</p>\n<ul>\n<li><p>IMHO the code inside <code>ProcessPaymentFile</code> (and its related methods) should be a class of its own. It's 50+ lines and should be broken into smaller methods; the fact that you're using <code>#region</code>s is already telling.</p>\n</li>\n<li><p>I'm not a fan of <code>_configuration["UploadPath"];</code>. You should consider the approach <a href=\"https://stackoverflow.com/a/31453663/648075\">detailed here</a>: have a POCO object representing the configuration.</p>\n</li>\n<li><p><code>".csv"</code> and <code>".xml"</code> appear multiple times, and thus should be <code>const string</code>.</p>\n</li>\n<li><p>Instead of doing <code>.ToLower()</code> when comparing <code>string</code>s, consider using <a href=\"https://stackoverflow.com/a/29750349/648075\">string.Equals()</a>. Alternatively, since you always need the lowercase <code>fileExtension</code>, why not make it lowercase when you call <code>Path.GetExtension(file.FileName)</code>?</p>\n</li>\n<li><p>Comments should say why something is done (if necessary), not what is done. <code>// save into db.</code> is useless, I can see that is what is happening. Most of the time your code should be self-explanatory and comments shouldn't be necessary.</p>\n</li>\n<li><p>Do not pointlessly abbreviate. <code>trans</code> doesn't gain you anything, just call it <code>transaction</code>.</p>\n</li>\n<li><p>Consider logging precisely why a transaction is invalid. Moreover, consider validating <em>all</em> transactions and logging <em>all</em> deficiencies, that way you can report back all possible issues in one go, instead of having one problem, reporting that to your users, them fixing it, them re-uploading the file and again being confronted with an error message.</p>\n<p>I have experienced this recently when writing code to access an external service and it was deeply frustrating to experience that when I fixed one issue and re-did my test -- which took a significant amount of time to run -- I experienced another issue, because the service I was connecting to broke on the first error. If I had gotten a full list of problems (which were caused by their documentation being incorrect, BTW) I could have solved them in one go, instead it took two days of whack-a-mole to iron out all the kinks.</p>\n</li>\n<li><p>There is no point to have <code>throw new ArgumentException($"Invalid file type. Only {string.Join(",", validFileTypes)} allowed.");</code> However, that is a far clearer error message than the one users will get when they upload an invalid file: <code>throw new ArgumentException($"Unknown format.");</code>.</p>\n</li>\n<li><p><code>"Invalid file size. Only less than 1 MB is allowed."</code> is barely comprehensible. Sure, the user will figure out what you mean, but it would be better to present them with a message that they don't need to "translate". Simply say something like <code>"Uploaded files should be smaller than 1 MB."</code>.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T08:43:06.767",
"Id": "506428",
"Score": "0",
"body": "Thanks for code review :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T07:52:29.753",
"Id": "256458",
"ParentId": "256450",
"Score": "3"
}
},
{
"body": "<p>Just two things.</p>\n<p>The using keyword is just synctatic sugar for a try/finally block. There's no need here to embed using block in a try block. In general you can use either:</p>\n<pre><code> try {\n sr = new StreamReader(filename);\n txt = sr.ReadToEnd();\n }\n finally {\n if (sr != null) sr.Dispose();\n }\n</code></pre>\n<p>or</p>\n<pre><code>using (StreamReader sr = new StreamReader(filename)) {\n txt = sr.ReadToEnd();\n }\n</code></pre>\n<p>If you use a try/catch block you can catch the exceptions for both the StreamReader and DBContext, so I would add a finally block and get rid of using.</p>\n<p>In general is good that a method does a single thing. Here, ProcessPaymentFile does more than one thing. I would break it into smaller parts by adding the following methods:</p>\n<pre><code>bool IsValidFile()\nFileType GetFileType()\nbool ProcessCSVFile()\nbool ProcessXMLFIle()\n</code></pre>\n<p>The ProcessPaymentFile would be something along these lines:</p>\n<pre><code>public bool ProcessPaymentFile(IFormFile file)\n {\n if(IsValidFile(file))\n {\n var fileType = GetFileType(file);\n \n result = fileType is FileType.CSVFile ? ProcessCSVFile(file) : ProcessXMLFile(file);\n \n return result;\n }\n \n return false;\n }\n</code></pre>\n<p>To ease reading, following the flow, testing and to improve thread safety a method should not mutate global variables (i.e. variables not defined in its scope).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T08:43:15.463",
"Id": "506429",
"Score": "0",
"body": "Thanks for code review :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T08:13:10.813",
"Id": "256459",
"ParentId": "256450",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "256458",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-25T21:50:46.763",
"Id": "256450",
"Score": "0",
"Tags": [
"c#"
],
"Title": "Import Xml and Csv files into database"
}
|
256450
|
<p>I implemented an <code>ExpireLRUCache</code> class, which will clear the data when it times out. There are two ways to achieve this:</p>
<ol>
<li>Use a timer to clear the expire data</li>
<li>Call the clean function in <code>Add</code> and <code>Get</code></li>
</ol>
<p>If I use a struct in class, and it use the template typename, how to deal with this?</p>
<p>I put the declaration of <code>Node</code> at the top, because it will be used when it is used. Is it reasonable?</p>
<pre class="lang-cpp prettyprint-override"><code>template <typename K, typename V>
class ExpireLRUCache {
private:
using Timestamp = std::chrono::time_point<std::chrono::system_clock>;
struct Node {
K key;
V value;
Timestamp timestamp;
};
public:
using NodePtr = std::shared_ptr<Node>;
using NodeIter = typename std::list<NodePtr>::iterator;
using ExpiredCallBack = std::function<void(K, V)>;
// Default timeout is 3000ms.
ExpireLRUCache(size_t max_size)
: max_size_(max_size), time_out_(3000), expired_callback_(nullptr) {}
ExpireLRUCache(size_t max_size, uint32_t time_out, ExpiredCallBack call_back)
: max_size_(max_size), time_out_(time_out), expired_callback_(call_back) {}
void Add(K key, V value);
V Get(K key);
size_t Size() const;
private:
void Expired();
mutable std::mutex mutex_;
std::list<NodePtr> list_;
std::unordered_map<K, NodeIter> map_;
size_t max_size_;
// ms
uint32_t time_out_;
ExpiredCallBack expired_callback_;
};
template <typename K, typename V>
void ExpireLRUCache<K, V>::Add(K key, V value) {
std::lock_guard<std::mutex> lock(mutex_);
// if full, delete oldest
if (list_.size() >= max_size_) {
auto oldest = list_.back();
list_.pop_back();
map_.erase(oldest->key);
}
// if exist, delete it in the list, and then add to the front
// then overwrite in map.
if (map_.find(key) != map_.end()) {
NodeIter iter = map_[key];
list_.erase(iter);
}
auto timestamp = std::chrono::system_clock::now();
NodePtr node = std::make_shared<Node>(Node{key, value, timestamp});
list_.push_front(node);
map_[key] = list_.begin();
}
template <typename K, typename V>
V ExpireLRUCache<K, V>::Get(K key) {
std::lock_guard<std::mutex> lock(mutex_);
// Todo(zero): how to call
Expired();
if (map_.find(key) != map_.end()) {
return (*map_[key])->value;
} else {
return V{};
}
}
template <typename K, typename V>
void ExpireLRUCache<K, V>::Expired() {
auto time_now = std::chrono::system_clock::now();
while( !list_.empty() ) {
auto oldest = list_.back();
auto diff = std::chrono::duration_cast<std::chrono::milliseconds>(
time_now - oldest->timestamp);
if (diff.count() > time_out_) {
list_.pop_back();
map_.erase(oldest->key);
expired_callback_(oldest->key, oldest->value);
} else {
break;
}
}
}
template <typename K, typename V>
size_t ExpireLRUCache<K, V>::Size() const {
std::lock_guard<std::mutex> lock(mutex_);
return map_.size();
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>I don't see why the typenames <code>NodePtr</code> and <code>NodeIter</code> are public. <code>Node</code> itself is private, and none of the public interface uses these two types, so I think they should be private, too.</p>\n<hr />\n<p>I'm not sure I like this interface:</p>\n<pre><code>V Get(K key);\n</code></pre>\n<p>This means we can only cache value types. Not only that, but there's no way to indicate "not in the cache"; I see the implementation default-constructs a return value in that case - further limiting the types that can be used.</p>\n<hr />\n<p><code>Expired()</code> expects that the mutex is held, but is missing a comment stating that, so it took too long to confirm that it's used correctly.</p>\n<hr />\n<p>What's going on here?</p>\n<blockquote>\n<pre><code>NodePtr node = std::make_shared<Node>(Node{key, value, timestamp});\n</code></pre>\n</blockquote>\n<p>Why construct a <code>Node</code> and pass it to <code>make_shared()</code> to copy? It would be better to <code>make_shared()</code> directly:</p>\n<pre><code>NodePtr node = std::make_shared<Node>(key, value, timestamp);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T11:54:07.200",
"Id": "506339",
"Score": "1",
"body": "Thx for you advice, `Why construct a Node and pass it to make_shared() to copy?` because `Node` is a struct and I don’t want to implement a constructor for it. But now I think it is necessary!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T10:59:14.537",
"Id": "256463",
"ParentId": "256452",
"Score": "2"
}
},
{
"body": "<p>Excellent points by Toby on the code side, I'll focus on data structure usage.</p>\n<p>I'm not sold on the way you use the map and list to store the data. By having the map store an iterator into the list you add an indirection on the get operation which is arguably the operation you should optimize for in a cache, as the cache relies on the same objects being frequently accessed for it to be useful for its purpose.</p>\n<p>I would swap these around so that the map stores the value and an iterator into the list and the list stores a key into the map (iirc unordered_map iterators are not stable if the map resizes). This way get() avoids the indirection and you can still grab the exact list element to move to the top when refreshing an object in the cache.</p>\n<p>Another option is to avoid the list and use a priority queue (typically a heap) storing {timestamp, key} and the map stores key->{value, timestamp}. On insert you blind insert into the map with a new timestamp and you blindly insert into the priority queue the new timestamp and key. Then if you've exceeded the size limit or you want to expire items. Pop the top item of the priority queue and lookup the key in the map, compare the timestamps, if they match, evict from the map, if not then there's an element later on in the priority queue that references the map element and we can just discard this timestamp in the queue and pop the next.</p>\n<p>I have a feeling that the latter will be faster because you'll need less branching in the insert operation meaning CPU branch predictor is going to a better job at keeping the execution pipeline from stalling, the get operation will also be faster as it doesn't need the extra indirection. Expiration might have to process more elements in the priority queue but that likely won't matter because of CPU cache prefetching will be very efficient on the heap as opposed to a list.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T09:25:00.733",
"Id": "256497",
"ParentId": "256452",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T00:16:14.483",
"Id": "256452",
"Score": "3",
"Tags": [
"c++",
"cache"
],
"Title": "An expirable LRU cache implementation"
}
|
256452
|
<h1>Preamble</h1>
<p>This is an Alarm Clock app. The way it works is pretty simple: you change the time by pressing the +/- buttons and set the time by pressing the play button. When the time is up, the alarm will ring at which point you can stop it by pressing the pause button. This question is already long as it is so I won't be including everything required to run the application yourself. But if you'd like to do that, the project is hosted on Github and can be found <a href="https://github.com/joaobzrr/react-alarm-clock/tree/codereview" rel="nofollow noreferrer">here</a>. A live version of the app is also available and can be found <a href="https://joaobzrr.github.io/react-alarm-clock/" rel="nofollow noreferrer">here</a>.</p>
<h1>Comments</h1>
<p>In the the beginning, from thinking about how the application would look like, I identified five components:</p>
<ul>
<li>a <code>ChangeTimeButton</code> component which would be the +/- buttons for changing the hour and minute;</li>
<li>an <code>ArmButton</code> component to set the alarm to ring at the specified time;</li>
<li>a <code>Controls</code> component that would contain the ArmButton and ChangeTimeButtons;</li>
<li>a <code>Clock</code> component which would simply display the time;</li>
<li>an <code>App</code> component that would contain the Clock and Controls components.</li>
</ul>
<p><a href="https://i.stack.imgur.com/qrTtU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qrTtU.png" alt="Components" /></a></p>
<p>After working with this structure for some time, I felt that ChangeTimeButton had become too complicated. It needed to be a button, which means it had to trigger some action after it was pressed; furthermore, it should be possible for the user to hold it in order to change the hour or minute continuously, and it's appearance while being pressed should be different; it would need to handle both mouse and touch events; a sound should play when it was pressed, and so on. All of this, I thought, had more to do with the fact that this was a button (even if it was a specific type of button) than the fact that it would be used to change the time. So I refactored ChangeTimeButton into two components: one concerned with changing the time and another concerned with being a button. I also broke up ArmButton in a similar way.</p>
<p>Something else that made ChangeTimeButton complicated was that, after the alarm was armed, I did not want the user to still be able to change the time, so there would have to be some notion of ChangeTimeButton being off, which would mean that the user would not be able to interact with it, and that it's appearance would need to change in order to convey that idea. Later, I also found out that I needed to prevent more than one ChangeTimeButton from being pressed at the same time, so it was necessary to maintain state about which one was currently being pressed and disallow all others from modifying the time. But this did not require a change in appearance, so I decided I needed to separate the notion of ChangeTimeButton being <em>off</em> from the notion of it being simply <em>disabled</em>.</p>
<p>Another problem I had was that, because the ChangeTimeButtons would be positioned on each side of the ArmButton, I couldn't think of a good way to make a container component for them. The solution I came up with was to use a custom hook that triggers an update on all registered components whenever the shared state changes. This allowed me to access and modify state shared by all instances of ChangeTimeButton without the need for a container component or a context.</p>
<hr />
<h1>Components</h1>
<p>↓ App.tsx</p>
<pre><code>import React, { useState, useRef, useCallback } from "react";
import Clock from "@components/Clock";
import Controls from "@components/Controls";
import useConstructor from "@hooks/useConstructor";
import HighResolutionTimer from "@src/HighResolutionTimer";
import { calcTimeUntilAlert, changeTime, getCurrentTime } from "@src/time";
import "./App.scss";
export default function App() {
const [mode, setMode] = useState<types.AlarmClockMode>("idle");
const [time, setTime] = useState<types.Time>();
const timeoutId = useRef<number>();
useConstructor(() => {
const json = localStorage.getItem("time");
let time;
if (json === null) {
time = getCurrentTime();
} else {
time = JSON.parse(json);
}
setTime(time);
});
const armButtonCallback = useCallback(() => {
if (mode === "idle") {
setMode("armed");
let delta = calcTimeUntilAlert(time);
timeoutId.current = window.setTimeout(() => {
setMode("fired");
}, delta);
localStorage.setItem("time", JSON.stringify(time));
} else {
setMode("idle");
clearTimeout(timeoutId.current);
}
}, [mode, time])
const changeTimeButtonCallback = useCallback((type: types.ChangeTimeButtonType) => {
const f = {
"h+": (time: types.Time) => changeTime(time, 1, 0),
"h-": (time: types.Time) => changeTime(time, -1, 0),
"m+": (time: types.Time) => changeTime(time, 0, 1),
"m-": (time: types.Time) => changeTime(time, 0, -1)
}[type];
setTime(time => f(time));
}, []);
return (
<div className="outerContainer">
<div className="innerContainer">
<Clock time={time} />
<Controls
mode={mode}
armButtonCallback={armButtonCallback}
changeTimeButtonCallback={changeTimeButtonCallback}
/>
</div>
</div>
);
}
</code></pre>
<p>↓ Clock.tsx</p>
<pre><code>import React from "react";
import { formatTime } from "@src/time";
import "./Clock.scss";
type PropsType = { time: types.Time };
export default function Clock(props: PropsType) {
return (
<div className="Clock">
<span className="Clock_fg">{formatTime(props.time)}</span>
<span className="Clock_bg">88:88</span>
</div>
);
};
</code></pre>
<p>↓ Controls.tsx</p>
<pre><code>import React, { useEffect, useMemo } from "react";
import ArmButton from "@components/ArmButton";
import ChangeTimeButton from "@components/ChangeTimeButton";
import { useClasses, serializeClasses } from "./useClasses";
import "./Controls.scss";
type PropsType = {
mode: types.AlarmClockMode;
armButtonCallback: () => void;
changeTimeButtonCallback: (type: types.ChangeTimeButtonType) => void;
};
export default function Controls(props: PropsType) {
const {mode, armButtonCallback, changeTimeButtonCallback} = props;
const [classes, setClasses] = useClasses();
const isNotIdle = mode !== "idle";
useEffect(() => setClasses({Controls__isNotIdle: isNotIdle}), [isNotIdle]);
return (
<div className={serializeClasses(classes)}>
<ChangeTimeButton
callback={changeTimeButtonCallback}
off={isNotIdle}
type="h+"
className="ChangeTimeButton__left"
/>
<ChangeTimeButton
callback={changeTimeButtonCallback}
off={isNotIdle}
type="h-"
className="ChangeTimeButton__left"
/>
<ArmButton
callback={armButtonCallback}
mode={mode}
/>
<ChangeTimeButton
callback={changeTimeButtonCallback}
off={isNotIdle}
type="m-"
className="ChangeTimeButton__right"
/>
<ChangeTimeButton
callback={changeTimeButtonCallback}
off={isNotIdle}
type="m+"
className="ChangeTimeButton__right"
/>
</div>
);
}
</code></pre>
<p>↓ ChangeTimeButton.tsx</p>
<pre><code>import React, { memo, useMemo, useCallback } from "react";
import HoldableButton from "@components/HoldableButton";
import { PlusIcon, MinusIcon } from "./icons";
import usePressed from "./usePressed";
import ChangeTimeButtonPressAndHoldSoundPath from "./ChangeTimeButtonPressAndHold.mp3";
import "./ChangeTimeButton.scss";
type PropsType = {
callback: (type: types.ChangeTimeButtonType) => void;
off: boolean;
type: types.ChangeTimeButtonType;
className: string;
};
const ChangeTimeButton = memo((props: PropsType) => {
const { callback, type, off, className } = props;
const [pressed, setPressed] = usePressed();
const disabled = pressed !== null && pressed !== type;
const onPress = useCallback(() => { callback(type); setPressed(type) }, [type]);
const onRelease = useCallback(() => setPressed(null), []);
const onHold = useCallback(() => callback(type), [type]);
const icon = useMemo(() => {
return (type === "h+" || type === "m+") ? <PlusIcon/> : <MinusIcon/>;
}, []);
return (
<HoldableButton
onPress={onPress}
onRelease={onRelease}
onHold={onHold}
disabled={disabled}
off={off}
sound={ChangeTimeButtonPressAndHoldSoundPath}
className={`ChangeTimeButton ${className}`}
>
{icon}
</HoldableButton>
);
});
export default ChangeTimeButton;
</code></pre>
<p>↓ HoldableButton.tsx</p>
<pre><code>import React, { memo, useEffect, useRef } from "react";
import useConstructor from "@hooks/useConstructor";
import { useClasses, serializeClasses } from "./useClasses";
import HighResolutionTimer from "@src/HighResolutionTimer";
import AudioManager, { Sound } from "@src/AudioManager";
type PropsType = React.PropsWithChildren<{
onPress: Function;
onRelease: Function;
onHold: Function;
disabled: boolean;
off: boolean;
sound: string;
className: string;
}>;
const HoldableButton = memo((props: PropsType) => {
const [classes, setClasses] = useClasses();
useEffect(() => setClasses({HoldableButton__off: props.off}), [props.off]);
const spanRef = useRef<HTMLAnchorElement>();
const timer = useRef<HighResolutionTimer>();
const sound = useRef<Sound>();
const isPressed = useRef(false);
useConstructor(() => {
timer.current = new HighResolutionTimer(110, 400);
const audioManager = AudioManager.getInstance();
sound.current = audioManager.createSound(props.sound);
});
const press = (e: any) => {
e.preventDefault();
if (e.type === "mousedown" && (("buttons" in e && e.buttons !== 1) || ("which" in e && e.which !== 1))) {
return;
}
if (props.off || props.disabled) {
return;
}
isPressed.current = true;
setClasses("HoldableButton__pressed");
props.onPress();
sound.current.play();
timer.current.setCallback(() => {
props.onHold();
sound.current.play();
});
timer.current.start();
};
const release = (e: any) => {
e.preventDefault();
if (!isPressed.current) {
return;
}
isPressed.current = false;
setClasses("HoldableButton__released");
props.onRelease();
timer.current.stop();
};
useEffect(() => {
spanRef.current.addEventListener("touchstart", press, {passive: false});
spanRef.current.addEventListener("touchend", release, {passive: false});
return () => {
spanRef.current.removeEventListener("touchstart", press);
spanRef.current.removeEventListener("touchend", release);
}
}, [props.off, props.disabled]);
const className = `${serializeClasses(classes)} ${props.className}`;
return (
<span
ref={spanRef}
onMouseDown={press}
onMouseUp={release}
onMouseLeave={release}
className={className}
>
{props.children}
</span>
);
});
export default HoldableButton;
</code></pre>
<p>↓ ArmButton.tsx</p>
<pre><code>import React, { useEffect, useMemo } from "react";
import BlinkingButton from "@components/BlinkingButton";
import { PlayIcon, PauseIcon } from "./icons";
import { useClasses, serializeClasses } from "./useClasses";
import ArmButtonPressSoundPath from "./ArmButtonPress.mp3";
import ArmButtonBlinkSoundPath from "./ArmButtonBlink.mp3";
import "./ArmButton.scss";
type PropsType = {
callback: () => void;
mode: types.AlarmClockMode;
};
export default function ArmButton(props: PropsType) {
const [classes, setClasses] = useClasses();
useEffect(() => setClasses({
ArmButton__isArmed: props.mode !== "idle"
}), [props.mode]);
const icon = useMemo(() => {
return (props.mode === "idle") ? <PlayIcon/> : <PauseIcon/>;
}, [props.mode]);
return (
<BlinkingButton
onPress={props.callback}
blinking={props.mode === "fired"}
pressSound={ArmButtonPressSoundPath}
blinkSound={ArmButtonBlinkSoundPath}
className={serializeClasses(classes)}
>
{icon}
</BlinkingButton>
);
}
</code></pre>
<p>↓ BlinkingButton.tsx</p>
<pre><code>import React, { useRef, useEffect } from "react";
import HighResolutionTimer from "@src/HighResolutionTimer";
import AudioManager, { Sound } from "@src/AudioManager";
import useConstructor from "@hooks/useConstructor";
import { useClasses, serializeClasses } from "./useClasses";
type PropsType = React.PropsWithChildren<{
onPress: Function;
blinking: boolean;
pressSound: string;
blinkSound: string;
className: string;
}>;
export default function BlinkingButton(props: PropsType) {
const [classes, setClasses] = useClasses();
const timer = useRef<HighResolutionTimer>();
const pressSound = useRef<Sound>();
const blinkSound = useRef<Sound>();
const isLit = useRef(false);
const blink = (lit: boolean) => {
isLit.current = lit;
setClasses({BlinkingButton__isLit: lit});
}
useConstructor(() => {
timer.current = new HighResolutionTimer(500, 500, () => {
blink(!isLit.current);
blinkSound.current.playIf(isLit.current);
});
const audioManager = AudioManager.getInstance();
pressSound.current = audioManager.createSound(props.pressSound);
blinkSound.current = audioManager.createSound(props.blinkSound);
});
useEffect(() => {
if (props.blinking) {
timer.current.start();
} else {
timer.current.stop();
blink(false);
}
}, [props.blinking]);
const callback = (e: React.MouseEvent) => {
props.onPress();
pressSound.current.play();
}
const className = `${serializeClasses(classes)} ${props.className}`;
return (
<span
onClick={callback}
className={className}
>
{props.children}
</span>
);
}
</code></pre>
<h1>Hooks</h1>
<p>↓ makeUseClasses.ts</p>
<pre><code>import { useState } from "react";
import { isString, isFunction } from "@src/utils";
type StringSet = Set<string>;
type GroupDictionary = {[key: number]: Set<string>};
type Spec = {[key: string]: {init: boolean; group: number; precedence: number;}};
type SetClassesArgument = string|types.BoolDictionary|UpdateFunction;
type SetClassesFunction = (...args: SetClassesArgument[]) => void;
type UseClassesFunction = (...initialState: string[]) => [StringSet, SetClassesFunction];
type UpdateFunction = (oldState: StringSet) => string|string[]|types.BoolDictionary;
type SerializeClassesFunction = (state: StringSet) => string;
export default function makeUseClasses(spec: Spec): [UseClassesFunction, SerializeClassesFunction] {
const groups = getGroups(spec, Object.keys(spec));
const useClasses = (...initialState: string[]): [StringSet, SetClassesFunction] => {
checkNames(spec, ...initialState);
const [classes, _setClasses] = useState<StringSet>(() => {
const defaultState = Object.keys(spec).filter((key: string) => spec[key].init);
return new Set([...defaultState, ...initialState]);
});
const setClasses = (...args: SetClassesArgument[]) => {
_setClasses((oldState: StringSet) => {
let [insert, remove] = parseArguments(oldState, ...args);
checkNames(spec, ...insert);
checkNames(spec, ...remove);
const diff = getDiff(groups, getGroups(spec, [...insert]));
remove = new Set([...remove, ...diff]);
const newState = new Set([...oldState, ...insert].filter((key: string) => !remove.has(key)));
return newState;
});
};
return [classes, setClasses];
}
const serializeClasses = (state: StringSet) => {
const sorted = [...state].sort((a: string, b: string) => {
return spec[a].precedence - spec[b].precedence
});
const result = sorted.join(" ");
return result;
}
return [useClasses, serializeClasses];
}
const parseArguments = (oldState: StringSet, ...args: SetClassesArgument[]) => {
let insert = new Set<string>();
let remove = new Set<string>();
for (let x of args) {
const value = isFunction(x) ? (x as UpdateFunction)(oldState) : x;
if (isString(value)) {
const name = value as string;
insert.add(name);
} else if (Array.isArray(value)) {
const names = value as string[];
insert = new Set([...insert, ...names]);
} else {
const dictionary = value as types.BoolDictionary;
for (let key of Object.keys(value)) {
(dictionary[key] ? insert : remove).add(key);
}
}
}
return [insert, remove];
}
const getDiff = (x: GroupDictionary, y: GroupDictionary): StringSet => {
let result = new Set<string>();
for (let key of Object.keys(y)) {
const group = parseInt(key);
if (group === 0) return;
const a = x[group];
const b = y[group];
const c = [...a].filter((key: string) => !b.has(key));
result = new Set([...result, ...c]);
}
return result;
}
const getGroups = (spec: Spec, keys: string[]) => {
let result: {[key: number]: Set<string>} = {};
for (let key of keys) {
const group = spec[key].group;
if (group in result) {
result[group].add(key);
} else {
result[group] = new Set([key]);
}
}
return result;
}
const checkNames = (spec: Spec,...names: string[]) => {
for (let name of names) {
console.assert(name in spec, `${name} not in spec.`);
}
}
</code></pre>
<p>↓ makeUseGlobal.ts</p>
<pre><code>import { useState, useEffect } from "react";
export default function makeUseGlobal<T>(initialState: T) {
let globalState = initialState;
const listeners = new Set();
const setState = (value: T) => {
globalState = value;
listeners.forEach((listener: Function) => {
listener();
});
}
return (): [T, Function] => {
const [state, _setState] = useState<T>(globalState);
useEffect(() => {
const listener = () => {
_setState(globalState);
}
listeners.add(listener);
listener();
return () => {
return () => listeners.delete(listener);
}
}, []);
return [state, setState];
}
}
</code></pre>
<p>↓ useConstructor.ts</p>
<pre><code>import { useRef } from "react";
export default function useConstructor(callback: Function, args: any[] = []) {
const hasBeenCalled = useRef(false);
if (hasBeenCalled.current) {
return;
} else {
callback(...args);
hasBeenCalled.current = true;
}
}
</code></pre>
<h1>Misc</h1>
<p>↓ HighResolutionTimer.ts</p>
<pre><code>type Callback = (timer: HighResolutionTimer) => void;
export default class HighResolutionTimer {
callback: Callback;
duration: number;
delay: number;
startTime: number|undefined;
currentTime: number|undefined;
timeoutId: number|undefined;
totalTicks: number = 0;
deltaTime: number = 0;
constructor(duration: number, delay: number = 0, callback: Callback = null) {
this.duration = duration;
this.delay = delay;
this.callback = callback;
}
reset() {
this.startTime = this.currentTime = this.timeoutId = undefined;
this.totalTicks = this.deltaTime = 0;
}
tick() {
const lastTime = this.currentTime;
this.currentTime = Date.now();
if (this.startTime === undefined) {
this.startTime = this.currentTime;
}
if (lastTime !== undefined) {
this.deltaTime = this.currentTime - lastTime;
}
this.callback(this);
const nextTick = this.duration - (this.currentTime - (this.startTime + (this.totalTicks * this.duration)));
this.totalTicks++;
this.timeoutId = window.setTimeout(() => this.tick(), nextTick);
}
start() {
console.assert(this.callback !== null, "Timer callback was not set.");
this.reset();
this.timeoutId = window.setTimeout(() => this.tick(), this.delay);
}
stop() {
if (this.timeoutId !== undefined) {
clearTimeout(this.timeoutId);
this.timeoutId = undefined;
}
}
setCallback(callback: Callback) {
this.callback = callback;
}
}
</code></pre>
<p>↓ AudioManager.ts</p>
<pre><code>type BufferInfo = {
buffer: AudioBuffer|null,
path: string;
ready: boolean;
};
export default class AudioManager {
static instance: AudioManager = null;
context: AudioContext;
buffers: {[path: string]: BufferInfo} = {};
constructor() {
this.context = new (window.AudioContext || window.webkitAudioContext)();
this.buffers = {};
}
static getInstance() {
if (AudioManager.instance === null) {
AudioManager.instance = new AudioManager();
}
return AudioManager.instance;
}
load(bufferInfo: BufferInfo) {
const request = new XMLHttpRequest();
request.open("GET", bufferInfo.path);
request.responseType = "arraybuffer";
request.onload = () => {
this.context.decodeAudioData(request.response, (buffer: AudioBuffer) => {
bufferInfo.buffer = buffer;
bufferInfo.ready = true;
});
}
request.send();
}
createSound(url: string) {
if (url in this.buffers) {
return new Sound(this, this.buffers[url]);
}
const bufferInfo: BufferInfo = {buffer: null, path: url, ready: false};
this.buffers[url] = bufferInfo;
this.load(bufferInfo);
return new Sound(this, bufferInfo);
}
}
export class Sound {
manager: AudioManager;
bufferInfo: BufferInfo;
currentSource: AudioBufferSourceNode;
constructor(manager: AudioManager, bufferInfo: BufferInfo) {
this.manager = manager;
this.bufferInfo = bufferInfo;
this.currentSource = null;
}
play() {
if (!this.bufferInfo.ready) {
return
}
if (this.currentSource !== null) {
this.currentSource.stop();
}
const context = this.manager.context;
this.currentSource = context.createBufferSource();
this.currentSource.buffer = this.bufferInfo.buffer;
this.currentSource.connect(context.destination);
this.currentSource.start();
}
playIf(condition: boolean) {
if (condition) {
this.play()
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I have the strong impression that your code can be simplified drastically. I would love to check it out and give it a try. Don't know if I will find the (spare-)time though.</p>\n<p><strong>UPDATE</strong>: I <a href=\"https://github.com/teetotum/react-alarm-clock\" rel=\"nofollow noreferrer\">forked</a> it and currently browse through your code and see what I can simplify. I'm impressed by how clean it is. This is really an astonishingly well written piece of software. (And I learn a good deal in the process. Didn't know that I could use <code>webpack serve</code> and always used <code>webpack-dev-server</code> on the commandline.)</p>\n<p>Here is a list of things that I think needs fixing. I will amend the list as I progress through the code:</p>\n<ul>\n<li><p>Your <code>makeUseClasses</code> seems to cover the functionality of <a href=\"https://www.npmjs.com/package/classnames\" rel=\"nofollow noreferrer\">classnames</a> which is the de-factor standard package for this kind of classname fiddelydoo as far as I can tell from (comercial) React projects I have worked on</p>\n</li>\n<li><p>Your alarm clock functionality could probably be completely hidden away in a single custom hook with a signature something like:</p>\n</li>\n</ul>\n<pre><code>const { incHours, decHours, incMinutes, decMinutes, arm, time } = useAlarmClock();\n</code></pre>\n<ul>\n<li>Your <code>useConstructor</code> seems like you are unaware of the more idomatic:</li>\n</ul>\n<pre><code>useEffect( () => callOnFirstRenderAndNevermore(), [] );\n</code></pre>\n<ul>\n<li>if you only use your <code>useConstructor</code> to initialize state you should better use the built-in initializer capability of the <code>useState</code> hook:</li>\n</ul>\n<pre><code>const initTime = () => {\n const json = localStorage.getItem("time");\n let time;\n if (json === null) {\n time = getCurrentTime();\n } else {\n time = JSON.parse(json);\n }\n return time;\n};\n\nconst [time, setTime] = useState<types.Time>(initTime);\n</code></pre>\n<ul>\n<li><p>you use a string based type for <code>type AlarmClockMode = "idle"|"armed"|"fired";</code> and I think an enum type is cleaner <code>export enum AlarmClockMode { IDLE, ARMED, FIRED }</code></p>\n</li>\n<li><p>I would ditch the <code>default</code> exports and switch to <code>named exports</code> completely. This is also the advice given by popular linters and the reasoning behind it is sensible. I experienced it in my work projects myself. The reasons: a named export must be imported by that name, so it is way easier to find all usages with a full-text search reliably. As soon as you notice that you must add something to the file that also needs to be available outside that file (for example an option type for your component) you must introduce named exports, and requires to change the syntax of all places where an import happens. This can be avoided if you use named exports from the beginning.</p>\n</li>\n<li><p>I would introduce a Type for your functional components that specifies the prop type and additionally allows the intrinsic properties (className, tabindex, aria-<em>, data-</em>, etc.)</p>\n</li>\n</ul>\n<pre><code>type ArmButtonProps = {\n callback: () => void;\n mode: AlarmClockMode;\n};\n\nexport const ArmButton: HTMLAttributesFunctionComponent<ArmButtonProps> = ({\n callback, mode, className, tabindex,\n}) => {\n return (\n <div className={classnames('arm-button', className)} tabindex={tabindex} etc.\n\n</code></pre>\n<ul>\n<li><p>You use <code>@svgr/webpack</code> which is wonderful because it allows to import any SVG and directly use it as a React component with full className and intrinsic attribute support. I feel it complicates matters unnecessary when you wrap it in an Icon component of your own.</p>\n</li>\n<li><p>You really don't need to optimize the resulting JSX because React is very good at comparing your previous result with your current result when render is called and only updates the parts of the DOM that actually changed (that is one reason for the <code>key</code> property in iterated items). So what you are doing here is doing more harm than good:</p>\n</li>\n</ul>\n<pre><code>const icon = useMemo(() => {\n return (mode === AlarmClockMode.IDLE) ? <PlayIcon className="icon" /> : <PauseIcon className="icon" />;\n }, [mode]);\n</code></pre>\n<ul>\n<li><p>The on/off switching of a css class for the blinking animation is better done by using a css based animation. just activate the class an the element and let the browser css rendering do the rest. You can even define the interval length in an SCSS file and from there <a href=\"https://stackoverflow.com/questions/66126256/how-to-get-scss-variables-in-js-code-nodejs-server/66133716#66133716\">export it and import it in your js code</a> so that the value is not suplicated throughout the source code and can be changed in one single place.</p>\n</li>\n<li><p>Currently only an idea: I think it might be worth the try to develop a custom hook for the long-button-press behavior. Generally I'm quite in favor of moving functionality into hooks instead of creating specialized components.</p>\n</li>\n<li><p>The file path for the sound files is currently propagated through props, but as it is information that is available during compile time I think this might be a good candidate to move it out of the component code and into some form of <code>export const</code> from some <code>configuration.js</code></p>\n</li>\n<li><p>more to come ;)</p>\n</li>\n</ul>\n<p>I have pushed some of the proposed changes to my forked repo, so you can see what I have done, but I will stop for now and proceed later.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T19:02:56.823",
"Id": "507015",
"Score": "0",
"body": "If you'd like, we can talk in [chat](https://chat.stackexchange.com/rooms/120464/alarm-clock-in-react-js)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T13:10:37.100",
"Id": "256720",
"ParentId": "256457",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T06:12:14.947",
"Id": "256457",
"Score": "5",
"Tags": [
"beginner",
"react.js",
"typescript"
],
"Title": "Alarm Clock with React.js"
}
|
256457
|
<p>According to <a href="https://html.spec.whatwg.org/multipage/syntax.html#attributes-2" rel="nofollow noreferrer">https://html.spec.whatwg.org/multipage/syntax.html#attributes-2</a> an HTML 5 attribute name is defined like this:</p>
<blockquote>
<p>Attribute names must consist of one or more characters other than
controls, U+0020 SPACE, U+0022 ("), U+0027 ('), U+003E (>), U+002F
(/), U+003D (=), and noncharacters. In the HTML syntax, attribute
names, even those for foreign elements, may be written with any mix of
ASCII lower and ASCII upper alphas.</p>
</blockquote>
<p>Creating a class which can handle or sanitize HTML 5 attribute names I have ended up with the following code - especially the following regex:</p>
<pre><code>class AttributeNameValidator
{
public const ATTRIBUTE_NAME_MATCHER = "/[\s\x{0000}\x{0020}\x{0022}\x{0027}\x{003E}\x{002F}\x{003D}\x{200B}-\x{200D}\x{FDD0}-\x{FDEF}\x{FEFF}[:cntrl:]]+/u";
/**
* Checks if a given string is a valid HTML attribute name.
* @param string $attributeName
* @return bool: True if the given attribute name is a valid HTML attribute name.
*/
public static function isAttributeNameValid(string $attributeName): bool
{
return (bool)preg_match(self::ATTRIBUTE_NAME_MATCHER, $attributeName);
}
/**
* Sanitizes a string to be a valid HTML5 attribute name.
* @param string $attributeName
* @return string
* @throws NonSanitizeableException
*/
public static function sanitizeAttributeName(string $attributeName): string
{
$sanitizedAttributeName = preg_replace(self::ATTRIBUTE_NAME_MATCHER, '', $attributeName);
if(!$sanitizedAttributeName) {
throw new NonSanitizeableException("Failed to sanitize attribute name");
}
return $sanitizedAttributeName;
}
}
</code></pre>
<p>My manual tests seem to work well still I am not sure if the regex exactly matches the standard or if I have forgotten something. Is there still something to improve?</p>
|
[] |
[
{
"body": "<ul>\n<li>The <code>\\x{0020}</code> (SPACE) character is already included in <code>\\s</code>, you can omit that part.</li>\n<li>I prefer to use <code> \\p{Cc}</code> over <code>[:cntrl:]</code> for consistency and because I don't like to have nested square braces in a character class.</li>\n<li>I expect <code>isAttributeNameValid()</code> to be checking that the whole string contains NO blacklisted characters. If you want to match the entire string then you will need "start of string" and "end of string" anchors and a negated character class in your pattern. But wait, you have a regular character class and you are returning <code>true</code> if one or more blacklisted characters are in the string -- this seems precisely the opposite of what the method name suggests. Unless I am confused, you should replace <code>(bool)</code> with <code>!</code> so that you return <code>false</code> when a match is made and <code>true</code> when there are no blacklisted characters found.</li>\n<li>I don't know if I agree with the wording of <code>Failed to sanitize attribute name</code>; it seems more truthful to say that the <code>Attribute name had no salvagable characters</code>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T15:19:21.500",
"Id": "506370",
"Score": "0",
"body": "Good answer. Do not know why I did not recognize 3), thanks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T14:24:16.823",
"Id": "256474",
"ParentId": "256470",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "256474",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T12:05:50.387",
"Id": "256470",
"Score": "2",
"Tags": [
"php",
"html",
"regex",
"validation",
"utf-8"
],
"Title": "Validator and Sanitizer for HTML 5 attribute regex according to current HTML living standard"
}
|
256470
|
<p>I've been asked to create some code to help automate the loading of data into a system based on employee data in a spreadsheet. However, the data isn't clean, so some people may have no manager, some may be their own manager, some have managers who already exist in the system, so aren't included in the export, and others managers are somewhere in the export. Ideally we'd create managers before creating their subordinates, to set both values in one pass (rather than creating all accounts, then updating the managers).</p>
<p>The below sort algorithm is to allow a sort of such dirty data, to ensure that where a dependency chain can be resolved it is and the items are returned in the appropriate order; but if the data's bad, we'll still be able to do as much good as possible.</p>
<p>Sharing it here as there may be a more efficient solution. I've seem similar solutions which build a tree then traverse it; but all those I've seen require clean data to function correct, and I can't think of a way to amend them whilst keeping their efficiency.</p>
<pre><code>Function Sort-ParentChild {
[CmdletBinding()]
Param (
[Parameter(Mandatory, ValueFromPipeline)]
[PSCustomObject[]]$ListItems
,
[Parameter(Mandatory)]
[string]$ParentPropertyName
,
[Parameter(Mandatory)]
[string]$CurrentPropertyName
)
Begin {
[System.Collections.Generic.List[PSCustomObject]]$Pending = [System.Collections.Generic.List[PSCustomObject]]::new()
}
Process {
foreach ($item in $ListItems) {
# first return items which have no parent, or which are their own parent (since circular dependencies would otherwise never be resolved
if (($null -eq $item."$ParentPropertyName") -or (($item."$CurrentPropertyName" -eq $item."$ParentPropertyName"))) {
$item
} else {
$Pending.Add($item)
}
}
}
End {
while ($Pending.Count) {
$circularLoop = $true
# return any items whose parents are not in the pending list (i.e. they already existed so weren't in the todo list, or we've returned them earlier in the process)
for ($i = ($Pending.Count-1); $i -ge 0; $i--) { # work down, so that removing an item won't have any odd impacts
if ($Pending[$i]."$ParentPropertyName" -notin @($Pending | Select-Object -ExpandProperty $CurrentPropertyName)) {
$Pending[$i]
$Pending.RemoveAt($i)
$circularLoop = $false # if we've found something to return, we're not in a loop yet
}
}
if ($circularLoop) {
# in case there are any circular dependencies, to avoid getting stuck, return a single item, then try to unravel in dependency order from there
Write-Warning "Circular dependency found; breaking loop by returning $($Pending[0]."$CurrentPropertyName")"
$Pending[0]
$Pending.RemoveAt(0)
}
}
}
}
</code></pre>
<h2>Example Usage</h2>
<pre><code>$users = @(
@{Id = 'Subordinate17'; ManagerId = 'MiddleManager1'}
@{Id = 'Subordinate15'; ManagerId = 'MiddleManager1'}
@{Id = 'Subordinate14'; ManagerId = 'MiddleManager3'}
@{Id = 'Subordinate13'; ManagerId = 'MiddleManager1'}
@{Id = 'TopDog'; ManagerId = $null} # this person's the top dog; they don't have a manager
@{Id = 'MiddleManager1'; ManagerId = 'BigBoss1'}
@{Id = 'BigBoss1'; ManagerId = 'BigBoss1'} # Big Boss is their own boss
@{Id = 'AmbassadorX'; ManagerId = 'PilotX'}
@{Id = 'MiddleManager2'; ManagerId = 'BigBoss1'}
@{Id = 'PilotX'; ManagerId = 'InstructorX'}
@{Id = 'Subordinate17'; ManagerId = 'MiddleManager1'}
@{Id = 'MiddleManager3'; ManagerId = 'TopDog'}
@{Id = 'Subordinate16'; ManagerId = 'MiddleManager3'}
@{Id = 'Mya'; ManagerId = 'PilotX'}
@{Id = 'Subordinate12'; ManagerId = 'MiddleManager2'}
@{Id = 'Subordinate11'; ManagerId = 'MiddleManager1'}
@{Id = 'InstructorX'; ManagerId = 'AmbassadorX'}
@{Id = 'Subordinate10'; ManagerId = 'MiddleManager2'}
@{Id = 'Subordinate09'; ManagerId = 'MiddleManager2'}
@{Id = 'Subordinate08'; ManagerId = 'MiddleManager2'}
@{Id = 'Subordinate07'; ManagerId = 'MiddleManager2'}
@{Id = 'Subordinate06'; ManagerId = 'MiddleManager2'}
@{Id = 'Subordinate05'; ManagerId = 'TopDog'}
@{Id = 'Subordinate04'; ManagerId = 'BigBoss1'}
@{Id = 'Subordinate03'; ManagerId = 'MiddleManager3'}
@{Id = 'Shark'; ManagerId = $null} # alone shark :S
@{Id = 'Subordinate02'; ManagerId = 'MiddleManager3'}
@{Id = 'Subordinate01'; ManagerId = 'MiddleManager3'}
) | %{[pscustomobject]$_} #| Sort -Property @{E={[Guid]::NewGuid()}} # optional chaos sort, to avoid any chance of my data being in some helpful order before testing
$users | Sort-ParentChild -ParentPropertyName 'ManagerId' -CurrentPropertyName 'Id'
</code></pre>
<h1>Example Output</h1>
<pre><code>WARNING: Circular dependency found; breaking loop by returning AmbassadorX
Id ManagerId
-- ---------
TopDog
BigBoss1 BigBoss1
Shark
Subordinate04 BigBoss1
Subordinate05 TopDog
MiddleManager3 TopDog
MiddleManager2 BigBoss1
MiddleManager1 BigBoss1
Subordinate13 MiddleManager1
Subordinate14 MiddleManager3
Subordinate15 MiddleManager1
Subordinate17 MiddleManager1
Subordinate01 MiddleManager3
Subordinate02 MiddleManager3
Subordinate03 MiddleManager3
Subordinate06 MiddleManager2
Subordinate07 MiddleManager2
Subordinate08 MiddleManager2
Subordinate09 MiddleManager2
Subordinate10 MiddleManager2
Subordinate11 MiddleManager1
Subordinate12 MiddleManager2
Subordinate16 MiddleManager3
Subordinate17 MiddleManager1
AmbassadorX PilotX
InstructorX AmbassadorX
PilotX InstructorX
Mya PilotX
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T16:53:14.677",
"Id": "256479",
"Score": "2",
"Tags": [
"sorting",
"powershell"
],
"Title": "Sort items so that parents are created before their children"
}
|
256479
|
<pre><code>const generateFibonnaciSequence = (n) => {
return [
(arr = new Array(n).fill(1).reduce((arr, _, i) => {
arr.push(i <= 1 ? 1 : arr[i - 2] + arr[i - 1]);
return arr;
}, [])),
arr[n - 1],
];
};
const [fibonacciSequence, fibonacciNthNumber] = generateFibonnaciSequence(n);
</code></pre>
<p>My idea is to return an array holding fibonacci sequence up to <code>n</code> in index 0 and fibonnaci's n-th value in index 1. Can someone help me with a prettier way of constructing this function. I'd like to avoid holding the array in temp arr variable if possible, but still use a single expression for return statement.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T22:45:53.370",
"Id": "506410",
"Score": "1",
"body": "`push` method mutates the data. A cool improvement would be to use the `...` ES6 spread syntax in order to create this array in the return statement"
}
] |
[
{
"body": "<h2>Quick review</h2>\n<p>Try to avoid very long names "generateFibonnaciSequence" can be "fibonnaciSequence".</p>\n<p>The new array <code>arr</code> is undeclared and thus will be in the global scope. Chrome has recently improved how it handles optional parameters so there is no penalty to declare the array as an argument scoped to the function.</p>\n<p>It seems to me that the reducer can return the last Fibonnaci number rather than a array which will make the code a little cleaner.</p>\n<p>You can also reduce the iteration by one because you are starting the sequence at 1 rather than 0.</p>\n<p>Filling the array is a lot of extra work as you only need the first value set.</p>\n<p>Putting all that together you can so it all with just the one array (ignoring the returned array)</p>\n<pre><code>const fibSeq = (n, arr = new Array(n - 1)) => [\n arr, arr.reduce((fib, _, i) => arr[i + 1] = i ? fib + arr[i - 1]: 1, arr[0] = 1)\n];\n</code></pre>\n<p>The reduction in overheads makes it run about 4 times quicker.</p>\n<p>However there is a dangerous behavioral change. If n is 0 it will throw when trying to create an array with a negative value, and n = 1 will return [[1,1], 1] rather than [[1], 1].</p>\n<p>If you need it to return for these values you can check for 0 and 1 returning the static values when needed.</p>\n<pre><code>const fidSeq = (n, a = --n > 0 && new Array(n)) => \n a? [a, a.reduce((f, _, i) => a[i+1] = i? f + a[i-1]: 1, a[0] = 1)]: n? [[],]: [[1], 1];\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T09:49:16.567",
"Id": "506489",
"Score": "0",
"body": "`fidSeq` made me giggle. Also, that last piece of code belong on CodeGolf, not CodeReview."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T07:52:47.740",
"Id": "256494",
"ParentId": "256480",
"Score": "0"
}
},
{
"body": "<p>A short review;</p>\n<ul>\n<li>I prefer fat arrow syntax <code>=></code> for inline functions</li>\n<li>Its a good exercise to code this with <code>reduce</code> but it is definitely not the best option for production code. (That would be a non-recursive old skool loop)</li>\n<li>The modern approach to <a href=\"https://en.wikipedia.org/wiki/Fibonacci_number\" rel=\"nofollow noreferrer\">Fibonacci numbers</a> has them start with <code>[0,1,1]</code> not <code>[1,1]</code></li>\n<li>If you have control over what the function returns, then I would just return the sequence. It is trivial for the caller to get the last value in the array</li>\n</ul>\n<p>Please find below a counter proposal, I like that it support both the old and new style sequence.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function buildFibonnaciSequence(n){\n const start = [0,1];\n //Recursion exit lane\n if(n <= 1){\n return [start.slice(0,n+1), start[n]];\n }\n //Recurse\n const priorSequence = buildFibonnaciSequence(n-1);\n //Build return value\n const nValue = priorSequence[0][n-2] + priorSequence[0][n-1];\n return [[...priorSequence[0], nValue], nValue];\n}\n\nconsole.log(buildFibonnaciSequence(0));\nconsole.log(buildFibonnaciSequence(1));\nconsole.log(buildFibonnaciSequence(5));\nconsole.log(buildFibonnaciSequence(45));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T12:24:22.243",
"Id": "256568",
"ParentId": "256480",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "256494",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T17:56:10.950",
"Id": "256480",
"Score": "1",
"Tags": [
"javascript",
"fibonacci-sequence"
],
"Title": "Fibonacci sequence and nth number with reduce()"
}
|
256480
|
<p>Example of usage with header:</p>
<pre><code>public class AccountBalanceConfig : IExcelTypeConfiguration<AccountBalanceFile>
{
public void Configure(IExcelTypeBuilder<AccountBalanceFile> builder)
{
builder
.WithHeader(3, file => file.Balance)
.Property("Kontobenämning", ab => ab.AccountName)
.AutoFormat()
.Property("Nummer", ab => ab.BankAccount)
.AutoFormat()
.Property(1, 1, ab => ab.BalanceDate)
.UseConvention<BalanceDateConvention>()
.Property("Bokfört saldo", ab => ab.Balance)
.AutoFormat();
}
private class BalanceDateConvention : IConvention
{
private static readonly Regex BalanceDateMatcher = new Regex(@"\d\d\d\d-\d\d-\d\d");
public object To(string value)
{
var match = BalanceDateMatcher.Match(value);
return DateTime.Parse(match.Value, CultureInfo.InvariantCulture);
}
}
}
</code></pre>
<p>Example with headerless excel:</p>
<pre><code>public class AccountTransactionConfig : IExcelTypeConfiguration<AccountTransactionFile>
{
public void Configure(IExcelTypeBuilder<AccountTransactionFile> builder)
{
builder
.WithNoHeader(file => file.Transactions)
.Property(0, at => at.Account)
.AutoFormat()
.Property(1, at => at.TransactionDate)
.AutoFormat()
.Property(4, at => at.Reference)
.AutoFormat()
.Property(6, at => at.Amount)
.AutoFormat()
.Property(7, at => at.Type)
.AutoFormat()
.Property(8, at => at.Information)
.AutoFormat()
.Property(9, at => at.RemoteAccountNumber)
.AutoFormat()
.Property(10, at => at.RemoteClearingOrAddress)
.AutoFormat()
.Property(11, at => at.RemoteName)
.AutoFormat();
}
}
</code></pre>
<p>Example read file</p>
<pre><code>[TestClass]
public class When_parsing_a_balance_excel : ExcelTest
{
private AccountBalanceFile _balance;
[TestInitialize]
public async Task Context()
{
await using var stream = GetResource("xlsx");
_balance = await Get<ExcelSerializer<AccountBalanceFile>>().DeserializeAsync(stream);
}
[TestMethod]
public void It_should_parse_file_correctly()
{
Assert.AreEqual(3, _balance.Balance.Count());
}
}
</code></pre>
<p>Entry point for fluent mapping</p>
<pre><code>public class ExcelTypeBuilder<TExcelFileType> : IExcelTypeBuilder<TExcelFileType>
{
private readonly List<IMapper> _mappers = new List<IMapper>();
public INamedColumnTypeBuilder<TEntity> WithHeader<TEntity>(int headerRow, Expression<Func<TExcelFileType, IEnumerable<TEntity>>> entities) where TEntity : new()
{
var mapper = new NamedColumnTypeBuilder<TEntity>(headerRow, (entities.Body as MemberExpression)?.Member as PropertyInfo);
_mappers.Add(mapper);
return mapper;
}
public IIndexedTypeBuilder<TEntity> WithNoHeader<TEntity>(Expression<Func<TExcelFileType, IEnumerable<TEntity>>> entities) where TEntity : new()
{
var mapper = new IndexedColumnTypeBuilder<TEntity>((entities.Body as MemberExpression)?.Member as PropertyInfo);
_mappers.Add(mapper);
return mapper;
}
public Task<TRead> ReadAsync<TRead>(Stream stream) where TRead : TExcelFileType, new()
{
if (!_mappers.Any()) throw new Exception("No config exists for entity type");
using var reader = ExcelReaderFactory.CreateReader(stream, new ExcelReaderConfiguration { LeaveOpen = true });
var dataSet = reader.AsDataSet();
var instance = new TRead();
foreach (var mapper in _mappers)
{
mapper.Read(instance, dataSet);
}
return Task.FromResult(instance); //We have other parsers that are async they share interface
}
}
</code></pre>
<p>Property mapper for named column (Excel with header)</p>
<pre><code>public class NamedColumnTypeBuilder<TEntity> : INamedColumnTypeBuilder<TEntity>, IMapper where TEntity : new()
{
private readonly int _headerRow;
private readonly PropertyInfo _propertyInfo;
private readonly List<IColumnReader> _columnReaders = new List<IColumnReader>();
public NamedColumnTypeBuilder(int headerRow, PropertyInfo propertyInfo)
{
_headerRow = headerRow;
_propertyInfo = propertyInfo ?? throw new ArgumentException("Property expression could not be resolved");
}
IPropertyMapper<INamedColumnTypeBuilder<TEntity>> INamedColumnTypeBuilder<TEntity>.Property<TProperty>(int row, int column, Expression<Func<TEntity, TProperty>> property)
{
var formatter = new PropertyMapper<INamedColumnTypeBuilder<TEntity>>(this, (property.Body as MemberExpression)?.Member as PropertyInfo);
_columnReaders.Add(new SpecificColumnReader(row, column, formatter));
return formatter;
}
public IPropertyMapper<INamedColumnTypeBuilder<TEntity>> Property<TProperty>(string column, Expression<Func<TEntity, TProperty>> property)
{
var formatter = new PropertyMapper<INamedColumnTypeBuilder<TEntity>>(this, (property.Body as MemberExpression)?.Member as PropertyInfo);
_columnReaders.Add(new NamedColumnReader(column,formatter));
return formatter;
}
public void Read(object parentInstance, DataSet dataSet)
{
var table = dataSet.Tables[0];
var rows = table.Rows;
var header = rows[_headerRow].ItemArray.Select((o, i) => (o, i)).ToDictionary(info => ((string)info.o).ToLower(), info => info.i);
var collection = new List<TEntity>();
for (int i = _headerRow + 1; i < rows.Count; i++)
{
var row = rows[i];
var instance = new TEntity();
var cancelRead = _columnReaders.Any(reader =>
{
if (!reader.CanRead(table, header, row)) return true;
reader.Read(instance, table, header, row);
return false;
});
if (cancelRead) break;
collection.Add(instance);
}
_propertyInfo.SetValue(parentInstance, collection);
}
}
</code></pre>
<p>Property config</p>
<pre><code>public class PropertyMapper<TParent> : IPropertyMapper<TParent>, IFormatter
{
private readonly TParent _parent;
private readonly PropertyInfo _propertyInfo;
private PropertyReader _reader;
public PropertyMapper(TParent parent, PropertyInfo propertyInfo)
{
_parent = parent;
_propertyInfo = propertyInfo ?? throw new ArgumentException("Property expression could not be resolved");
}
public TParent AutoFormat()
{
_reader = new PropertyReader(_propertyInfo);
return _parent;
}
public TParent Format(string format)
{
_reader = new FormatPropertyReader(format, _propertyInfo);
return _parent;
}
public TParent UseConvention<TConvention>() where TConvention : IConvention, new()
{
_reader = new ConventionPropertyReadWriter(_propertyInfo, new TConvention());
return _parent;
}
public void Read(object instance, object value)
{
_reader.Read(instance, value);
}
public bool AcceptsNull => _reader.AcceptsNull;
}
</code></pre>
<p>Property reader example:</p>
<pre><code>public class PropertyReader
{
protected readonly PropertyInfo Property;
protected readonly Type PropertyType;
protected readonly bool IsNullable;
public PropertyReader(PropertyInfo property)
{
Property = property;
PropertyType = property.PropertyType;
var underlyingType = Nullable.GetUnderlyingType(Property.PropertyType);
if (underlyingType != null)
{
IsNullable = true;
PropertyType = underlyingType;
}
}
public bool AcceptsNull => IsNullable || PropertyType.IsClass;
public void Read(object instance, object value)
{
var propValue = IsNullable && (value == null || value is DBNull) ? null : value is string str ? ChangeType(str) : TryCast(value);
Property.SetValue(instance, propValue);
}
private object TryCast(object value)
{
if (value == null) return null;
if (value.GetType() != PropertyType)
{
return Convert.ChangeType(value, PropertyType);
}
return value;
}
protected virtual object ChangeType(string value)
{
if (PropertyType.IsEnum)
return Enum.Parse(PropertyType, value);
return Convert.ChangeType(value, PropertyType, CultureInfo.InvariantCulture);
}
}
</code></pre>
<p>Column reader example</p>
<pre><code>public abstract class ColumnReader
{
protected readonly IFormatter Formatter;
protected ColumnReader(IFormatter formatter)
{
Formatter = formatter;
}
protected object Read(DataRow row, int column)
{
if (column >= row.ItemArray.Length)
{
if (!Formatter.AcceptsNull) throw new Exception("Column is missing and Property does not allow null");
return null;
}
return row[column];
}
}
public class NamedColumnReader : ColumnReader, IColumnReader
{
private readonly string _column;
private readonly IFormatter _formatter;
public NamedColumnReader(string column, IFormatter formatter) : base(formatter)
{
_column = column.ToLower();
_formatter = formatter;
}
public void Read(object instance, DataTable table, Dictionary<string, int> header, DataRow row)
{
_formatter.Read(instance, Read(row, header[_column]));
}
public bool CanRead(DataTable table, Dictionary<string, int> header, DataRow row)
{
return _formatter.AcceptsNull || !(row[header[_column]] is DBNull);
}
}
</code></pre>
<p>Public api for reader</p>
<pre><code>public class ExcelSerializer<TExcelFile> : IDeserializeStream<TExcelFile> where TExcelFile : new()
{
private readonly ExcelTypeBuilder<TExcelFile> _builder;
public ExcelSerializer(ExcelTypeConfigurationMapper<TExcelFile> mapper)
{
_builder = mapper.Builder;
}
public Task<TExcelFile> DeserializeAsync(Stream stream)
{
return _builder.ReadAsync<TExcelFile>(stream);
}
}
</code></pre>
<p>The class that connects it all</p>
<pre><code>public class ExcelTypeConfigurationMapper<TEntity>
{
public ExcelTypeConfigurationMapper(IExcelTypeConfiguration<TEntity> config)
{
Builder = new ExcelTypeBuilder<TEntity>();
config.Configure(Builder);
}
public ExcelTypeBuilder<TEntity> Builder { get; }
}
</code></pre>
<p>Service config</p>
<pre><code>private static IServiceCollection AddExcelParsing(this IServiceCollection collection)
{
return collection.AddAllTransient(typeof(IExcelTypeConfiguration<>), typeof(AccountTransactionConfig)) //Helper method that hooks all IExcelTypeConfiguration<> in assembly of type AccountTransactionConfig
.AddSingleton(typeof(ExcelTypeConfigurationMapper<>))
.AddTransient(typeof(IDeserializeStream<>), typeof(ExcelSerializer<>))
.AddTransient(typeof(ExcelSerializer<>));
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T18:09:38.497",
"Id": "256481",
"Score": "1",
"Tags": [
"c#",
"excel",
"fluent-interface"
],
"Title": "Excel datamapper with fluent config"
}
|
256481
|
<p>I am working on designing a simple version of a Connect 4 <a href="https://www.mathsisfun.com/games/connect4.html" rel="nofollow noreferrer">game</a>.</p>
<p>Here is my first draft code.
I would like some feedback on it, and also required modification for these follow up questions:</p>
<ol>
<li>Add some intelligence in the players to select the column optimally.</li>
<li>How will you make the game generic so that it can check for 16 points in a row/column/diagonal</li>
<li>How will you handle a huge grid?</li>
</ol>
<p>Regarding item3, I think since I am not storing the whole grid, my approach is scalable.
I appreciate for any recommendations or feedback.</p>
<pre><code>class Connect4 {
vector <pair<int, map< pair<int,int>,int > > > rows;
vector <pair<int, map< pair<int,int>,int > > > cols;
vector <pair<int, map< pair<int,int>,int > > > diag;
int r;
int c;
int player;
public:
Connect4 (int rr, int cc):r(rr), c(cc){
rows = vector <pair<int, map< pair<int,int>,int > > > (rr);
cols = vector <pair<int, map< pair<int,int>,int > > > (cc);
diag = vector <pair<int, map< pair<int,int>,int > > > (min (rr,cc));
}
int move(int row, int col, int player){
int score = (player ==1)?1:-1; // count player-1 socres with positive and player-2 with negative numbers
rows[row].first +=score;
rows[row].second[{row,col}]=score;
if (abs(rows[row].first) ==4 && isValid(rows[row].second) )
return player;
cols[col].first += score;
cols[col].second[{row,col}]=score;
if (abs(cols[col].first) ==4 && isValid(cols[col].second) )
return player;
if(row ==col+2){
diag[0].first +=score;
if (abs(diag[0].first) ==4 ) //if the score is 4 no extra checking is needed
return player;
} else if (row ==col+1) {
diag[1].first += score;
if (abs(diag[1].first) ==4 && isValid(diag[1].second) )
return player;
} else if (row ==col) {
diag[2].first += score;
if (abs(diag[2].first) ==4 && isValid(diag[2].second) )
return player;
} else if (row+1 ==col) {
diag[3].first += score;
if (abs(diag[3].first) ==4 && isValid(diag[3].second) )
return player;
} else if (row+2 ==col) {
diag[4].first += score;
if (abs(diag[4].first) ==4 && isValid(diag[4].second) )
return player;
} else if (row+3 ==col) {
diag[5].first += score;
if (abs(diag[5].first) ==4 )
return player;
}
}
bool isValid(map<pair<int,int>, int> verify) {
int cnt=1;
map<pair<int,int>, int>::iterator itr = verify.begin();
int prev= itr->second;
itr++;
for (;itr!= verify.end(); ++itr){
int score = itr->second ;
if(prev == score){
cnt++;
if(cnt ==4)
return true;
} else {
cnt=0;
}
prev = score;
}
return (cnt>=4);
}
};
</code></pre>
<p>The logic behind calculating the diagonal is discussed here:
in a grid of 6x7, we can have diagonal score of >=4 only in following matrix indices:</p>
<p>If we have same scores in following (X,Y):</p>
<ul>
<li>(2,0), (3,1), (4,2), (5,3) -> diag[0]</li>
<li>(1,0), (2,1), (3,2), (4,3), (5,4)</li>
<li>(0,0), (1,1), (2,2), (3,3), (4,4), (5,5)</li>
<li>(0,1), (1,2), (2,3), (3,4), (4,5), (5,6)</li>
<li>(0,2), (1,3), (2,4), (3,5), (4,6)</li>
<li>(0,3), (1,4), (2,5), (3,6) -> diag[6]</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T03:08:57.287",
"Id": "506422",
"Score": "3",
"body": "Why are you using those complicated types? A vector (either R*C elements with custom indexing, or a `vector<vector<int>>`) would be easier to use and consume less memory."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T06:25:33.507",
"Id": "506424",
"Score": "0",
"body": "@ 1201ProgramAlarm \nThat is a good question. Here are my points:\n>> Using a 2D vector is a straight forward approach, but you may need to check all the rows and columns and diagonal elements after each move.\n>> With the given approach you only need to check a single row, column, or diagonal line once its corresponding score is 4. This checking is only needed since we need to verify if the coins are located right beside each other. \n\n>> Also the given idea can be expanded in case of having larger boards in which defining a large 2D vector could be a big problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T13:05:48.207",
"Id": "506439",
"Score": "2",
"body": "A flat vector of rows makes it easy to check straight lines - the stride between elements is `1` for a horizontal line, `cols` for a vertical, `cols+1` for a leading diagonal and `cols-1` for a trailing diagonal. Just make sure you get the start and end positions correct, and you're set to go."
}
] |
[
{
"body": "<h1>Naming things</h1>\n<p>Avoid single-character variable names, unless it's something that is very commonly used, like <code>i</code> for a loop index. Consider <code>r</code> and <code>c</code>, even if you guess it has something to do with coordinates, are those positions or sizes? I would personally use <code>width</code> and <code>height</code> here as unambiguous names for the size of the grid.</p>\n<p>Note that in the constructor's initializer list, you can use the same name for the parameter as for the member variable, like so:</p>\n<pre><code>int width;\nint height;\n\npublic:\nConnect4(int width, int height): width(width), height(height) {...}\n</code></pre>\n<p>Not everyone likes this style; some people want to disambiguate between parameter and member variable by writing:</p>\n<pre><code>Connect4(int width_, int height_): width(width_), height(height_) {...}\n</code></pre>\n<p>And you also see projects where all member variables are prefixed with <code>m_</code>, so it will look like:</p>\n<pre><code>int m_width;\nint m_height;\n\npublic:\nConnect4(int width, int height): m_width(width), m_height(height) {...}\n</code></pre>\n<p>Other variable names that could be improved:</p>\n<ul>\n<li><code>cnt</code> -> <code>count</code></li>\n<li><code>itr</code> -> <code>it</code> (the latter is more idiomatic)</li>\n<li><code>diag</code> -> <code>diagonal</code></li>\n<li><code>verify</code> -> <code>line</code></li>\n</ul>\n<h1>Create an <code>enum class</code> for the possibly contents of a grid cell</h1>\n<p>An <code>enum</code>, and even better an <a href=\"https://en.cppreference.com/w/cpp/language/enum#Scoped_enumerations\" rel=\"nofollow noreferrer\"><code>enum class</code></a>, allow you to specify the possible values of a grid cell up front, with names instead of integer values. I suggest you write the following:</p>\n<pre><code>class Connect4 {\n enum class Cell: char {\n EMPTY,\n PLAYER1,\n PLAYER2,\n };\n};\n</code></pre>\n<p>The above also explicitly sets the type to <code>char</code>, so only one byte is necessary to store it.</p>\n<h1>Storing the grid</h1>\n<p>There are several things wrong with how you store the grid. The data structure you are using is very inefficient, both for large and small grids, and for checking for a winning condition. The best way is to use a single vector to store all the grid cells:</p>\n<pre><code>std::vector<Cell> grid;\n</code></pre>\n<p>This ensures things are laid out very compactly in memory, and to look up an arbitrary grid cell, the CPU only has to do one multiplication and two additions, which is very cheap on contemporary processors, and as Toby Speight already mentioned, to check horizontal, vertical and diagonal lines is very easy as well; just calculate the start point, end point and stride to use, and then every step along the line only a single addition has to be done to find out the grid cell to check.</p>\n<p>I would add a function to get a reference to a grid cell given its coordinates, like so:</p>\n<pre><code>Cell &at(int row, int col) {\n return grid[row * c + col];\n}\n</code></pre>\n<h1>Handling huge grids</h1>\n<p>The first thing to consider when dealing with huge grids/arrays/matrices is whether the data structure is going to be densely or sparsely populated. It's easy to think that it should be sparse, after all you start with the grid being completely empty. But consider that during the end game of connect 4, you will probably have used more than half of the grid cells, so a dense grid is likely the best way to store the state.</p>\n<p>With the above <code>Cell</code> type, you use one byte per grid cell. Since a cell only has three possible states, you could pack up to five cells in a byte (since 3⁵ = 243) relatively easily, at the cost of some extra calculations when reading/writing a given cell. With this, a 100,000 by 50,000 grid fits in a little less than a gigabyte.</p>\n<p>You might also think about compressing the grid somehow, but again consider what a connect 4 game looks like near the end. For sure there won't be runs of more than 3 cells with the same color in a row, otherwise there would already have been a winner. And you rarely see a repetitive pattern appearing. So it basically looks like noise, which is not compressible. Perhaps predictive coding could be used to compress the sequence of moves made by the players, but the compressed data would most likely not be in a form suitable for displaying the grid and checking winning conditions.</p>\n<p>The only option I see for significantly reducing the amount of data is to consider that the bulk of the grid cells where players have already played will never be part of the 4 connected cells of the same color. For example, you could mark all cells that are more than 3 positions away (both horizontally and vertically) from any empty cells as being "dead". This way, that in principle, instead of having to store <span class=\"math-container\">\\$\\mathcal{O}(W \\cdot H)\\$</span>, you only have to store <span class=\"math-container\">\\$\\mathcal{O}(W + H)\\$</span> grid cells. But that would mean that you cannot show exactly all the moves made so far anymore.</p>\n<h1>Checking for a winning condition</h1>\n<p>Your idea of keeping a per-line score is unfortunately not really helpful. It is quite easy to create a line where the total score would be four, but there are no 4 consecutive cells with the same player, for example, representing players 1 and 2 with <code>O</code> and <code>X</code> respectively:</p>\n<pre><code>X O O X O O X O O X O O\n</code></pre>\n<p>There are 8 pieces of player 1, and 4 of player 2, so your way of counting score would result in <code>4</code> or <code>-4</code>, but clearly no player has won yet. However, if player 1 adds two more <code>O</code>'s to this line:</p>\n<pre><code>X O O X O O X O O X O O O O\n</code></pre>\n<p>Then player 1 has 4 in a row, but the "line score" would be <code>6</code> or <code>-6</code>. So the line score is not useful.</p>\n<p>The simple solution is to just always check the 9x9 area surrounding the latest move for a horizontal, vertical or diagonal line with 4 in a row. This might seem a bit wasteful in the very early game when only few moves have been made, it doesn't really matter in the long run.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T18:01:10.320",
"Id": "506449",
"Score": "0",
"body": "thanks for the feedback. Just a quick comment regarding \"Checking for a winning condition\". The isValid() function checks if there are 4 consecutive of same players score in a row, col or diagonal. And i intentionally checked first if the score is 4 or -4 and then calling isValid(). In other words isValid is called if and only if the abs(score_value) is equal to 4"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T14:27:58.923",
"Id": "256506",
"ParentId": "256482",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T18:49:26.747",
"Id": "256482",
"Score": "5",
"Tags": [
"c++",
"algorithm",
"connect-four"
],
"Title": "Connect 4 Game Design in C++"
}
|
256482
|
<p>Hello I have written a multi-threaded implementation of the K-means clustering algorithm. The main goals are correctness and scalable performance on multi-core CPUs. I expect to code to not have race conditions and no data races, and to scale good with more CPU cores.</p>
<pre><code>package bg.unisofia.fmi.rsa;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ParallelKmeans {
private static CountDownLatch countDownLatch;
private final int n;
private final int k;
public int numThreads = 1;
List<Node> observations = new ArrayList<>();
float[][] clusters;
public ParallelKmeans(int n, int k) {
this.n = n;
this.k = k;
clusters = new float[k][n];
for (float[] cluster : clusters) {
for (int i = 0; i < cluster.length; i++) {
cluster[i] = (float) Math.random();
}
}
}
public void assignStep(ExecutorService executorService) throws InterruptedException {
Runnable[] assignWorkers = new AssignWorker[numThreads];
final int chunk = observations.size() / assignWorkers.length;
countDownLatch = new CountDownLatch(numThreads);
for (int j = 0; j < assignWorkers.length; j++) {
assignWorkers[j] = new AssignWorker(j * chunk, (j + 1) * chunk);
executorService.execute(assignWorkers[j]);
}
countDownLatch.await();
}
public void updateStep(ExecutorService executorService) throws InterruptedException {
countDownLatch = new CountDownLatch(numThreads);
UpdateWorker[] updateWorkers = new UpdateWorker[numThreads];
final int chunk = observations.size() / updateWorkers.length;
for (int j = 0; j < updateWorkers.length; j++) {
updateWorkers[j] = new UpdateWorker(j * chunk, (j + 1) * chunk);
executorService.execute(updateWorkers[j]);
}
countDownLatch.await();
clusters = new float[k][n];
int[] counts = new int[k];
for (UpdateWorker u : updateWorkers) {
VectorMath.add(counts, u.getCounts());
for (int j = 0; j < k; j++) {
VectorMath.add(clusters[j], u.getClusters()[j]);
}
}
for (int j = 0; j < clusters.length; j++) {
if (counts[j] != 0) {
VectorMath.divide(clusters[j], counts[j]);
}
}
}
void cluster() throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2);
for (int i = 0; i < 50; i++) {
assignStep(executorService);
updateStep(executorService);
}
executorService.shutdown();
}
public static class Node {
float[] vec;
int cluster;
}
class AssignWorker implements Runnable {
int l, r;
public AssignWorker(int l, int r) {
this.l = l;
this.r = r;
}
@Override
public void run() {
List<Node> chunk = observations.subList(l, r);
for (Node ob : chunk) {
float minDist = Float.POSITIVE_INFINITY;
int idx = 0;
for (int i = 0; i < clusters.length; i++) {
if (minDist > VectorMath.dist(ob.vec, clusters[i])) {
minDist = VectorMath.dist(ob.vec, clusters[i]);
idx = i;
}
}
ob.cluster = idx;
}
countDownLatch.countDown();
}
}
class UpdateWorker implements Runnable {
int[] counts;
int l, r;
float[][] clusters;
UpdateWorker(int l, int r) {
this.l = l;
this.r = r;
}
int[] getCounts() {
return counts;
}
public float[][] getClusters() {
return clusters;
}
@Override
public void run() {
this.counts = new int[k];
this.clusters = new float[k][n];
for (Node ob : observations.subList(l, r)) {
VectorMath.add(this.clusters[ob.cluster], ob.vec);
this.counts[ob.cluster]++;
}
countDownLatch.countDown();
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T21:28:43.443",
"Id": "506530",
"Score": "0",
"body": "This code does nothing. `observations` never gets assigned any values."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T00:36:45.330",
"Id": "506538",
"Score": "0",
"body": "Unless you're assigning it from outside this class before running it, in which case the calling context would be necessary to figure out if it works."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T17:16:21.990",
"Id": "506811",
"Score": "0",
"body": "Of course they are set from otuside. I dont see how tht is relevant to the things I care about. I found my own mistake anyway. I need to use volatile keyword."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T14:32:42.160",
"Id": "506992",
"Score": "0",
"body": "please post `VectorMath` class"
}
] |
[
{
"body": "<p>I have local variables in the <code>UpdateWorker</code> class that are later accessed from the main Thread. Unless I mark these variables as <code>volatile</code> there may be visibility issues.\nThe same thing also applies to the <code>cluster</code> field in <code>Observation</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T17:08:41.727",
"Id": "256686",
"ParentId": "256483",
"Score": "0"
}
},
{
"body": "<h1>Interface</h1>\n<p>Your classes interface is confusing. You have an internal method <code>cluster</code>, which appears to be the main entry point into your <code>ParallelKmeans</code> class. However, it then calls two public methods (<code>assignStep</code> and <code>updateStep</code>) that do the actual work. This seems wrong. Particularly since <code>assignStep</code> and <code>updateStep</code> can't be run safely at the same time.</p>\n<h1>countDownLatch</h1>\n<p>You're using a static <code>CoundDownLatch</code>, which you're recreating in your <code>assignStep</code> and <code>updateStep</code> methods. This doesn't really make sense to me. By having it static, you're having it shared across all instances of <code>ParallelKmeans</code> classes. Is this really the expected behaviour? As you're reinitialising the static in both of your public methods, it creates the possibility of it being changed unexpectedly. If you want to stay with a <code>CountDownLatch</code>, consider making it a local variable to each of your public methods and passing it into the constructors for your workers so that they have access to it.</p>\n<h1>How many threads</h1>\n<p>You're creating a threadpool that's based around the number of processors the machine has. However, both your update/assign steps are using the member variable <code>numThreads</code>, which is hard coded to 1. This disconnect is strange. Consider changing your startup code to calculate how many threads you want to use, then perform construction and assignment using this number.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T02:05:49.820",
"Id": "507206",
"Score": "0",
"body": "I agree about the static thing. It makes absolutely no sense for the latch to be static."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T02:07:42.217",
"Id": "507207",
"Score": "0",
"body": "Also agree on the last point. Can you elaborate on the first \"Interface\" one though?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T10:00:24.453",
"Id": "507224",
"Score": "1",
"body": "@TeodorDyakov When I look at a new class, I start by looking at the methods with a public scope. These are advertising that they are the way a class is expected to be interacted with. I think of this as the 'public interface'. For your class, the public methods look like they aren't designed to be called by a client. The next thing I'll look at is the methods with no defined scope, i.e. package-local visibility. These usually offer a bit more control because there's assumed knowledge from other code in the package, the 'internal interface'."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T10:01:13.883",
"Id": "507225",
"Score": "0",
"body": "@TeodorDyakov in your code, `cluster` seems like it should be public, whereas `assignStep` and `updateStep` seems like they should be at least package-local, or more probably private."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T17:48:49.413",
"Id": "256848",
"ParentId": "256483",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "256848",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T18:50:28.443",
"Id": "256483",
"Score": "0",
"Tags": [
"java",
"multithreading",
"machine-learning",
"clustering"
],
"Title": "Multithreaded implementation of K-means clustering algorithm in Java"
}
|
256483
|
<p>I am using .Net 5, and I am making game server using SignalR core.</p>
<p>Ther're 2 ways to inject service to my classes.</p>
<p>1- Constructor injection: where I must separate functions and data, even if it's stored in memory not database.</p>
<p>For example: Instead of Room class that contains data and functions, I will be <code>RoomManager</code> service and <code>Room</code> for data.</p>
<p>Here I inject <code>_masterRepo</code>, <code>_masterHub</code>, <code>_sessionRepo</code>, <code>_logger</code> in the service <code>RoomManager</code> that have scoped lifetime.</p>
<p>But I have to pass data classes to work on.</p>
<pre><code> public async Task AddUser(Room room, string userId, string connId)
{
var rUser = _sessionRepo.AddRoomUser(userId, connId, room);
if (room.Capacity == room.RoomUsers.Count)
{
_logger.LogInformation("a room is ready and will start");
await Start(room);
}
else
{
_sessionRepo.KeepRoom(room);
await _masterHub.Clients.User(rUser.UserId).SendAsync("RoomIsFilling");
}
}
</code></pre>
<pre><code> private async Task Start(Room room)
{
var dUsers = _masterRepo.GetRoomDisplayUsersAsync(room);
var rUsers = room.RoomUsers;
var tasks = new List<Task>();
for (int i = 0; i < room.Capacity; i++)
{
tasks.Add(_masterHub.Groups.AddToGroupAsync(rUsers[i].ConnectionId, "room" + room.Id));
rUsers[i].TurnId = i;
tasks.Add(_masterHub.Clients.User(rUsers[i].UserId).SendAsync("StartRoom", i, dUsers));
}
await Task.WhenAll(tasks);
StartTurn(rUsers[0]);
}
</code></pre>
<p>2- Function injection: where I can combine data and functions in the same class(normal OOP design).</p>
<p>This inside Room class, to call it: <code>someRoom.AddUser(....)</code></p>
<pre><code>public async Task AddUser(SessionRepo _sessionRepo, ILogger _logger, IHubContext<MasterHub> _masterHub, string userId, string connId)
{
var rUser = _sessionRepo.AddRoomUser(userId, connId, room);
if (roomCapacity == RoomUsers.Count)
{
_logger.LogInformation("a room is ready and will start");
await Start(room);
}
else
{
_sessionRepo.KeepRoom(room);
await _masterHub.Clients.User(rUser.UserId).SendAsync("RoomIsFilling");
}
}
</code></pre>
<pre><code>private async Task Start(MasterRepo _masterRepo)
{
var dUsers = _masterRepo.GetRoomDisplayUsersAsync(room);
var tasks = new List<Task>();
for (int i = 0; i < room.Capacity; i++)
{
tasks.Add(_masterHub.Groups.AddToGroupAsync(RoomUsers[i].ConnectionId, "room" + room.Id))
RoomUsers[i].TurnId = i
tasks.Add(_masterHub.Clients.User(RoomUsers[i].UserId).SendAsync("StartRoom", i, dUsers));
}
await Task.WhenAll(tasks)
StartTurn(RoomUsers[0]);
}
</code></pre>
<p>SessionRepo is singleton holds all data from server boot up.</p>
<pre><code> public class SessionRepo : ISessionRepo
{
private ConcurrentDictionary<int, Room> Rooms;
private ConcurrentDictionary<string, RoomUser> RoomUsers;
private int LastRoomId;
private int LastRoomUserId;
private ConcurrentDictionary<(int, int), ConcurrentBag<Room>> PendingRooms;
private readonly int[] GenrePosses = {0, 1, 2, 3};
private readonly int[] UserCountPosses = {2, 3, 4};
public SessionRepo()
{
PendingRooms = new ConcurrentDictionary<(int, int), ConcurrentBag<Room>>();
for (int i = 0; i < GenrePosses.Length; i++)
{
for (int j = 0; j < UserCountPosses.Length; j++)
{
PendingRooms.TryAdd((i, j), new ConcurrentBag<Room>());
}
}
}
#region room
public Room DeleteRoom(int roomId)
{
Rooms.TryRemove(roomId, out Room room);
return room;
}
#endregion
#region pending room
public Room GetPendingRoom(int genre, int userCount)
{
PendingRooms[(genre, userCount)].TryTake(out Room room);
return room;
}
/// <summary>
/// if the room is still pending
/// </summary>
public void KeepRoom(Room room)
{
PendingRooms[(room.Genre, room.Capacity)].Add(room);
}
public RoomUser AddRoomUser(string id, string connId, Room room)
{
var rUser = new RoomUser {UserId = id, ConnectionId = connId, Room = room};
room.RoomUsers.Add(rUser);
RoomUsers.TryAdd(id, rUser);
return rUser;
}
public Room MakeRoom(int genre, int userCount)
{
var room = new Room {Genre = genre, Capacity = userCount};
Rooms.Append(ref LastRoomId, room);
return room;
}
#endregion
#region room user
public RoomUser GetRoomUserWithId(string id)
{
RoomUsers.TryGetValue(id, out RoomUser roomUser);
return roomUser;
}
#endregion
}
</code></pre>
<p>I was using function injection, then I found that server should be stataless, so I stored session data in DB, but I thought of this matter, session data is really small per user and it's frequenlty used bescause(it's actually inside gameplay only).
And if the server goes down, there's nothing to do to keep sessions working because there're timed actions(like turn timout) that won't happen when the server die for seconds, so the statless point in sessions doens't matter I think.</p>
<p>I learned/searched a lot but I can't decide, I can't find complex enougth SignalR Repository to learn from. I have no one to review my code, I am sorry if this is a lot, please give me you your thoughts.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T12:23:43.180",
"Id": "506436",
"Score": "0",
"body": "Welcome to the Code Review Community where we review code that is working as expected and provide suggestions on how to improve that code. While we sometimes provide design reviews as part of a code review that is not the main focus of the code review site. For a design review, which is what you seem to be asking about you might want to try [Software Engineering](https://softwareengineering.stackexchange.com/help/how-to-ask) but make sure you follow their guidelines when asking a question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T19:53:08.833",
"Id": "506456",
"Score": "0",
"body": "Thanks, I will look at it."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T19:10:16.023",
"Id": "256485",
"Score": "0",
"Tags": [
"database",
"dependency-injection",
"session",
"asp.net-core",
"signalr"
],
"Title": "Handling sessions in SignalR core"
}
|
256485
|
<p>I'm implementing a generic (ie. <code>void *</code>) queue in C. I believe I have a working version but I'm looking for two things:</p>
<ul>
<li>Do any subtle bugs pop out to the experienced reader?</li>
<li>Can I implement this in a better way (perhaps using <code>void **</code> pointers?</li>
</ul>
<p><strong>queue.h</strong></p>
<pre><code>#ifndef QUEUE_H
#define QUEUE_H
#include <stdbool.h>
#include <stdlib.h>
typedef struct Queue Queue;
void queue_free (Queue* queue);
Queue* queue_init (void);
void* queue_dequeue (Queue* queue);
void queue_enqueue (Queue* queue, void* item);
bool queue_is_empty (const Queue* queue);
void queue_iterate (const Queue* queue, void (*fn)(void*));
size_t queue_size (const Queue* queue);
#endif
</code></pre>
<p><strong>queue.c</strong></p>
<pre><code>#include "queue.h"
#include <assert.h>
#include <stddef.h>
#include <stdio.h>
struct Queue {
size_t capacity, size;
void** data;
size_t head, tail;
/*
The queue is constructed using a pointer to the data and two integers representing
the head and tail of the queue.
head, tail
|
v
[ ][ ][ ][ ]
When an item is enqueued, we place it at the tail of the list and increment the tail.
head
| tail
v v
[a][ ][ ][ ]
The tail is guaranteed to always point to an empty slot (if it can't point to an empty
slot, the underlying array is resized).
head head
| | tail
v v v
[a][b][c][d] => [a][b][c][d][ ][ ][ ][ ]
If the tail has reached the end of the underlying array (and there is still room), it
wraps around.
tail
| head
v v
[ ][b][c][d]
When an object is dequeued we return the item pointed to by head and increment head. If
the queue is empty, we do _not_ move head.
tail
| head
v v
[ ][ ][c][d]
If, when we resize the array, head is larger than tail, we move all of head's elements to
the end of the new array.
tail
| head
v v
[c][d][ ][ ][ ][ ][a][b]
*/
};
void queue_free(Queue* queue) {
assert(queue);
free(queue->data);
free(queue);
}
Queue* queue_init(void) {
Queue* queue = calloc(1, sizeof *queue);
assert(queue);
queue->capacity = 100;
queue->size = 0;
queue->data = calloc(queue->capacity, sizeof *queue->data);
assert(queue->data);
queue->head = 0;
queue->tail = 0;
return queue;
}
void* queue_dequeue(Queue* queue) {
assert(queue);
if (queue->size == 0) {
return NULL;
}
void* item = queue->data[queue->head];
queue->head = (queue->head + 1) % queue->capacity;
queue->size--;
assert(item);
return item;
}
void queue_enqueue(Queue* queue, void* item) {
assert(queue);
assert(item);
queue->data[queue->tail] = item;
queue->size++;
// Resize the underlying array if we've reached capacity.
if (queue->size == queue->capacity) {
size_t scale = 2;
void** tmp = realloc(queue->data, scale * queue->capacity * sizeof *tmp);
assert(tmp);
if (queue->head > queue->tail) {
for (size_t i = queue->head; i < queue->capacity; ++i) {
tmp[i + queue->capacity] = tmp[i];
tmp[i] = NULL;
}
queue->head += queue->capacity;
}
queue->capacity *= scale;
queue->data = tmp;
}
queue->tail = (queue->tail + 1) % queue->capacity;
}
bool queue_is_empty(const Queue* queue) {
assert(queue);
return queue->size == 0;
}
void queue_iterate(const Queue* queue, void (*fn)(void*)) {
assert(queue);
assert(fn);
if (queue->size == 0) {
return;
}
for (size_t i = 0; i < queue->size; ++i) {
void* x = queue->data[(i + queue->head) % queue->capacity];
fn(x);
}
}
size_t queue_size(const Queue* queue) {
assert(queue);
return queue->size;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T23:58:27.337",
"Id": "506417",
"Score": "1",
"body": "I made a few edits of bugs I've just seen after posting and added a bit of an explanation in the source file."
}
] |
[
{
"body": "<p>I like your diagrams in the comments - a picture really can express much more than words sometimes! It's a shame the text lines are so long - I recommend keeping line lengths less than a standard terminal width of 80 columns (even in these days of large monitors, most readers prefer to have more files visible side-by-side than to have longer lines in each).</p>\n<hr />\n<blockquote>\n<pre><code>struct Queue {\n size_t capacity, size;\n void** data;\n size_t head, tail;\n};\n</code></pre>\n</blockquote>\n<p>Good choice of type for <code>capacity</code> and <code>size</code>. I'd probably have <code>head</code> and <code>tail</code> be pointers to <code>void*</code> rather than indexes, but either is a valid design choice.</p>\n<p>Keeping a record of <code>head</code>, <code>tail</code> and <code>size</code> is somewhat redundant. Instead of maintaining <code>size</code> as a member, we could compute it when needed from <code>head</code> and <code>tail</code>, provided we don't ever completely fill the queue (i.e. expand it just before <code>head==tail</code>, rather than just after). Alternatively, we could dispense with either <code>head</code> or <code>tail</code>, and generate the value from the other one and <code>size</code>.</p>\n<hr />\n<blockquote>\n<pre><code> Queue* queue = calloc(1, sizeof *queue);\n assert(queue);\n</code></pre>\n</blockquote>\n<p>That's plain wrong. We know that <code>calloc()</code> can return zero, so claiming <code>queue</code> is non-zero is mistaken.</p>\n<p>It seems that you think <code>assert()</code> is a tool for run-time checks, but that is not the case. <strong><code>assert()</code> exists to document things we know to be true</strong> (and, in debug builds, let us know when our claims are wrong).</p>\n<p>The correct code is</p>\n<pre><code> Queue* queue = calloc(1, sizeof *queue);\n if (!queue) { return queue; }\n</code></pre>\n<p>Not only does this perform the check in non-debug builds, it reports the failure to the caller, who can handle it appropriately.</p>\n<p>Such misuse of <code>assert()</code> exists throughout the program.</p>\n<p>It's not clear why we're using <code>calloc()</code> here rather than <code>malloc()</code> - we write all the storage we allocate, so the zero-initialising done by <code>calloc()</code> is just a waste of cycles.</p>\n<hr />\n<blockquote>\n<pre><code>void queue_free(Queue* queue) {\n assert(queue); \n free(queue->data);\n</code></pre>\n</blockquote>\n<p>Why not just handle a null <code>queue</code>, to give an interface consistent with <code>free()</code>? I'd write</p>\n<pre><code>void queue_free(Queue* queue)\n{\n if (!queue) { return; }\n free(queue->data);\n free(queue);\n}\n</code></pre>\n<p>That makes life much easier for callers, who can now pass their <code>Queue*</code> to <code>queue_free()</code> without needing a separate path for null pointers.</p>\n<hr />\n<blockquote>\n<pre><code>if (queue->head > queue->tail) {\n for (size_t i = queue->head; i < queue->capacity; ++i) {\n tmp[i + queue->capacity] = tmp[i];\n tmp[i] = NULL;\n }\n queue->head += queue->capacity;\n}\n</code></pre>\n</blockquote>\n<p>I think the loop there can be replaced by a simple <code>memmove()</code>. There should be no need to assign <code>NULL</code> to the positions between <code>tail</code> and <code>head</code>, as we'll not access those entries before they are next written.</p>\n<hr />\n<p>There's a subtle connection between two parts of the code here:</p>\n<blockquote>\n<pre><code>size_t scale = 2;\nif (queue->head > queue->tail) {\n /* copy elements */\n queue->head += queue->capacity;\n}\nqueue->capacity *= scale;\n</code></pre>\n</blockquote>\n<p>That scale factor of 2 and the addition of <code>queue->capacity</code> are tightly bound, yet if we were to change the scale factor to 3, or (also changing its type) to 1.5, we wouldn't necessarily spot that we need to update the addition to match. We could write</p>\n<pre><code> queue->head += queue->capacity * (scale - 1);\n</code></pre>\n<p>Alternatively, we could introduce a new variable instead of <code>scale</code>:</p>\n<pre><code> new_capacity = queue->capacity * 2;\n</code></pre>\n\n<pre><code> queue->head += new_capacity - queue->capacity;\n</code></pre>\n<p>This version makes it easier to use rational scale factors using integer arithmetic (<code>queue->capacity * 3 / 2</code>, for example).</p>\n<hr />\n<p><code>queue_iterate</code> has:</p>\n<blockquote>\n<pre><code> if (queue->size == 0) {\n return;\n }\n</code></pre>\n</blockquote>\n<p>That's unnecessary, since the rest of the function is a <code>for</code> loop that will do nothing when size is zero. We can just omit this test.</p>\n<hr />\n<p>One thing missing that I would have liked to have seen is a comprehensive set of <strong>unit tests</strong>. It's much better to demonstrate correctness by testing than by inspection, and self-contained library code such as this is highly suited to unit testing.</p>\n<p>A good test suite also gives confidence to make improvements to the code with minimal risk of introducing regressions to previously-working functions.</p>\n<p>Whenever a bug is found, it's good to reproduce it by adding a new test. Then fix the bug to make the test pass.</p>\n<p>Occasionally, run the test suite using a profiler or checker such as Valgrind. Depending on the checker, that can reveal memory leaks or other allocation problems, cache performance, or many other run-time aspects of the code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T23:03:59.407",
"Id": "506531",
"Score": "2",
"body": "This is a great review. I think the decision to have `head` and `tail` be `size_t` over a pointer is very valid, and I would have done the same as OP; this avoids stale pointers when `realloc` is called in `queue_enqueue`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T08:22:45.813",
"Id": "506546",
"Score": "2",
"body": "Yes, index or pointer are both valid choices. Similarly, which two of `head`, `tail`, `size` we need to keep is also a design choice. I do really need to be clearer about different levels of recommendation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T19:06:52.837",
"Id": "506606",
"Score": "0",
"body": "Thanks very much @TobySpeight, this was (again) incredibly helpful. I think I have been using asserts to debug but it's a fair criticism that in some spots it's just as easy to write the actual error handling code the first time around. I've been missing unit testing while writing C code so that's another good suggestion that I need to incorporate."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T21:04:11.440",
"Id": "506615",
"Score": "1",
"body": "I quite often test my C code using a C++ unit-test framework. It's easy to call C functions from C++, and there are some good C++ test frameworks around."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T21:29:20.443",
"Id": "506715",
"Score": "0",
"body": "That's a good suggestion -- I've been trying out C++ for some niceties like function overloading so I'll include that in the pro section as well. I played with Unity yesterday and it seems to be simple enough as long as I remember to add tests to the suite."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T13:30:58.180",
"Id": "256505",
"ParentId": "256489",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "256505",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T22:03:56.020",
"Id": "256489",
"Score": "5",
"Tags": [
"c",
"generics",
"queue"
],
"Title": "Generic Queue in C"
}
|
256489
|
<p>I am trying to perform the basic operations <code>+</code> with CUDA for GPU computation. The function <code>vectorIncreaseOne</code> is the instance for the operation details and <code>gpuIncreaseOne</code> function is the structure for applying the operation to each element in the parameter <code>data_for_calculation</code>.</p>
<p><strong>The experimental implementation</strong></p>
<p>The experimental implementation of <code>gpuIncreaseOne</code> function is as below.</p>
<pre><code>#include <stdio.h>
#include <cuda_runtime.h>
#include <cuda.h>
#include <helper_cuda.h>
#include <math.h>
__global__ void CUDACalculation::vectorIncreaseOne(const long double* input, long double* output, int numElements)
{
int i = blockDim.x * blockIdx.x + threadIdx.x;
if (i < numElements)
{
if (input[i] < 255)
{
output[i] = input[i] + 1;
}
}
}
int CUDACalculation::gpuIncreaseOne(float* data_for_calculation, int size)
{
// Error code to check return values for CUDA calls
cudaError_t err = cudaSuccess;
// Print the vector length to be used, and compute its size
int numElements = size;
size_t DataSize = numElements * sizeof(float);
// Allocate the device input vector A
float *d_A = NULL;
err = cudaMalloc((void **)&d_A, DataSize);
if (err != cudaSuccess)
{
fprintf(stderr, "Failed to allocate device vector A (error code %s)!\n", cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
// Allocate the device input vector B
float *d_B = NULL;
err = cudaMalloc((void **)&d_B, DataSize);
if (err != cudaSuccess)
{
fprintf(stderr, "Failed to allocate device vector B (error code %s)!\n", cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
// Allocate the device output vector C
float *d_C = NULL;
err = cudaMalloc((void **)&d_C, DataSize);
if (err != cudaSuccess)
{
fprintf(stderr, "Failed to allocate device vector C (error code %s)!\n", cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
// Copy the host input vectors A and B in host memory to the device input vectors in
// device memory
err = cudaMemcpy(d_A, data_for_calculation, DataSize, cudaMemcpyHostToDevice);
if (err != cudaSuccess)
{
fprintf(stderr, "Failed to copy vector A from host to device (error code %s)!\n", cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
// Launch the Vector Add CUDA Kernel
int threadsPerBlock = 256;
int blocksPerGrid =(numElements + threadsPerBlock - 1) / threadsPerBlock;
printf("CUDA kernel launch with %d blocks of %d threads\n", blocksPerGrid, threadsPerBlock);
vectorIncreaseOne <<<blocksPerGrid, threadsPerBlock>>>(d_A, d_C, numElements);
err = cudaGetLastError();
if (err != cudaSuccess)
{
fprintf(stderr, "Failed to launch vectorAdd kernel (error code %s)!\n", cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
// Copy the device result vector in device memory to the host result vector
// in host memory.
err = cudaMemcpy(data_for_calculation, d_C, DataSize, cudaMemcpyDeviceToHost);
if (err != cudaSuccess)
{
fprintf(stderr, "Failed to copy vector C from device to host (error code %s)!\n", cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
// Free device global memory
err = cudaFree(d_A);
if (err != cudaSuccess)
{
fprintf(stderr, "Failed to free device vector A (error code %s)!\n", cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
err = cudaFree(d_B);
if (err != cudaSuccess)
{
fprintf(stderr, "Failed to free device vector B (error code %s)!\n", cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
err = cudaFree(d_C);
if (err != cudaSuccess)
{
fprintf(stderr, "Failed to free device vector C (error code %s)!\n", cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
return 0;
}
</code></pre>
<p><strong>Test cases</strong></p>
<p>The test case for <code>gpuIncreaseOne</code> function is as below.</p>
<pre><code>auto data_pointer = (float*)malloc(100 * sizeof(float));
for (int i = 0; i < 100; i++)
{
data_pointer[i] = static_cast<float>(1);
}
CUDACalculation::gpuIncreaseOne(data_pointer, 100);
free(data_pointer);
</code></pre>
<p>All suggestions are welcome.</p>
<p>If there is any possible improvement about:</p>
<ul>
<li>Potential drawback or unnecessary overhead</li>
<li>Error handling</li>
</ul>
<p>please let me know.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-26T23:58:40.917",
"Id": "256490",
"Score": "2",
"Tags": [
"beginner",
"c",
"reinventing-the-wheel",
"cuda"
],
"Title": "gpuIncreaseOne Function Implementation in CUDA"
}
|
256490
|
<p>First of all I must thank for the help given in the previous post:</p>
<p><a href="https://codereview.stackexchange.com/questions/256388/class-showing-a-format-similar-to-var-dump-rc5-version">Class showing a format similar to var_dump RC5 Version</a></p>
<p>I have it deployed in a early versio v1.0.5: <a href="https://github.com/arcanisgk/BOH-Basic-Output-Handler" rel="nofollow noreferrer">https://github.com/arcanisgk/BOH-Basic-Output-Handler</a></p>
<p>As they should imagine; Thanks to your help, the main code has had serious changes; both of logic and structure and I have also implemented a series of new ideas; including CLI support.</p>
<p>Even so I have some doubts since I am not an expert in php.</p>
<h3>Some methods of this library require some improvements (see this description):</h3>
<ol>
<li>I have implemented a number of methods to control and display specific layouts in the data output, mainly the color palette is manipulated, both for the Web and for the CLI. I have listened to different proposals which I have mixed and implemented up to the present point:</li>
</ol>
<blockquote>
<p>related properties: <code>TOKENSLIST</code> , <code>THEMESLIST</code>,<code>$colorcli</code>.</p>
</blockquote>
<blockquote>
<p>related method: <code>__construct</code>, <code>resetHighlight</code>, <code>getTheme</code>, <code>setHighlightTheme</code>, <code>setHighlightThemeCli</code>, <code>colorRGBforCLI</code>, <code>highlightCode</code>, <code>highlightCodeCli</code>, <code>adjusterSpaceLine</code> and <code>applyCss</code></p>
</blockquote>
<p><em><strong>fixed before someone replied to this post</strong></em></p>
<p><s>2. The <code>getIndent</code> method uses the parsing of the variable to determine the indentation of the output using the<code> array_walk_recursive</code> function. I don't have a lot of knowledge about handling arrays therefore I used this method because I found it simple. I don't know if it is the best to fulfill the purpose of the <code>getIndent</code> method. but I have already verified that in the case of magic methods stored in a class variable; the correct indentation number is not obtained or even if it is a class object that has properties, the name of this is not displayed as it should be:</p>
<pre class="lang-php prettyprint-override"><code>class FooBar
{
public string $pub_string = 'hello world!';
private array $priv_array = ['a' => 1, 'b' => 2];
const CONST_OBJECT = ['a' => 1, 'b' => 2];
function foofunction()
{
return "Hello World!";
}
}
$varclass = new FooBar;
$output = new Output\OutputHandler();
$output->getTheme('monokai');
$output->output([$varclass]);
</code></pre>
<p>if I take a look at it from <code>var_dump</code> it looks like this:</p>
<pre><code>object(FooBar)#3 (2) {
["pub_string"]=>
string(12) "hello world!"
["priv_array":"FooBar":private]=>
array(2) {
["a"]=>
int(1)
["b"]=>
int(2)
}
}
</code></pre>
<p>example output, I would like the name that tried to capture to be <code>'FooBar::priv_array'</code> but it comes out like this:</s></p>
<ol start="3">
<li><p>The "analyzeVariable" method uses the abstraction of the "pretty" function. It was the only example I found where it allowed me to have output similar to <code>var_dump</code> or<code> var_export</code>.Some other developers suggested to me to use reflection but I did not find an example related to the use / purpose I want to give it. I also have an analysis group to space out using ternary analysis. I would like someone with more experience to review it, looking for possible errors or improvements, to the ternary analysis that is executed. With the minimal tests that I have carried out I have not obtained any error.</p>
</li>
<li><p>The <code>evaluaVariable</code> method is my favorite; This method is responsible for analyzing the data of the passed variable to determine the type of data and return it, taking into account that the returned code / value is usable. But I have not been able to recreate the objects or resources to make them usable, let's see an example:</p>
<p>Example array we have a node as follows:</p>
<pre><code>'resource' => curl_init()
</code></pre>
<p>but in the output tube to put:</p>
<pre><code>'resource' => resource
</code></pre>
<p>This happens because the data type does not say that it comes from a <code>curl_init();</code> what I was hoping to do, which I have failed to do, is show the output:</p>
<pre><code>'resource' => curl_init()
</code></pre>
</li>
<li><p>Another thing that I also think can negatively impact the performance of the library is the analysis performed by the <code>evaluateVariable</code> method since it is a set of if checks, improvements have already been made but I think it can be improved even more, I hear opinions about.</p>
</li>
<li><p>Another important point for me is to evaluate if, in general, the Script / library complies with the active standards of PSR 1 and 12. I use phpStorm IDE but it does not detect an error of this type, several have already been corrected if you see any favor to tell me.</p>
</li>
<li><p>for version v1.1.0 I hope I have implemented unit tests; I have no knowledge on this topic currently.</p>
</li>
<li><p>for version v1.1.0 I hope to have implemented the skipping envelope for <code>highlight_file</code> files.</p>
</li>
</ol>
<p>for point 7 and 8 I am also waiting to hear any suggestions.</p>
<p>My goal is to improve this script.
I have listed the main points, and I await comments on them.
Although it is not the main objective, I am also open to hear opinions based on documented and exemplified improvements.</p>
<h2>Class/library Description:</h2>
<h3>[BOH] Basic Output Handler for PHP</h3>
<p><em>Acronym</em>: [BOH].<br />
<em>Name</em>: Basic Output Handler.<br />
<em>Dependencies</em>: Stand Alone / PHP v7.4.</p>
<h3>What does [BOH] do?</h3>
<p>[BOH] is a very simple PHP [output handler] implementation that show Human readable information instead of using the default PHP options:</p>
<ul>
<li><code>var_dump()</code> - Displays information about a variable.</li>
<li><code>print_r()</code> - Print human-readable information about a variable.</li>
<li><code>debug_zval_dump()</code> - Outputs a string representing an internal value of zend.</li>
<li><code>var_export()</code> - Print or return a string representation of a parseable variable.</li>
</ul>
<p>This means that all the data passed is presented to the developer according to the chosen parameters.
It also means that the displayed data can be directly reused as code.
Comments are also generated for each value that briefly explains the type of data</p>
<h3>Why use [BOH]?</h3>
<p>Developers need the ability to decide how their code behaves when data needs to be checked.
The native PHP Methods provide a range of information that is not reusable by the developer or may even require more work to get the correct output for data verification.</p>
<p>This library handles data output proven to be extremely effective. [BOH] is a standalone implementation that can be used for any project and does not require a third-party library or software.</p>
<h2>My code</h2>
<pre class="lang-php prettyprint-override"><code><?php
/**
* BOHBasicOutputHandler - Data output manager in PHP development environments.
* PHP Version 7.4.
*
* @see https://github.com/arcanisgk/BOH-Basic-Output-Handler
*
* @author Walter Nuñez (arcanisgk/original founder) <icarosnet@gmail.com>
* @copyright 2020 - 2021 Walter Nuñez.
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @note This program is distributed in the hope that it will be useful
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE.
*/
namespace IcarosNet\BOHBasicOutputHandler;
/**
* BOHBasicOutputHandler - Data output manager in PHP development environments.
*
* @author Walter Nuñez (arcanisgk/original founder) <icarosnet@gmail.com>
*/
/**
* Validation of php version.
* strictly equal to or greater than 7.4
* a minor version will kill any script.
*
*/
if (!version_compare(PHP_VERSION, '7.4', '>=')) {
die('IcarosNet\BOHBasicOutputHandler requires PHP ver. 7.4 or higher');
}
/**
* Validation of the environment of use.
* support for web and cli environments
*
*/
if (!defined('ENVIRONMENT_OUTPUT_HANDLER')) {
define('ENVIRONMENT_OUTPUT_HANDLER', (IsCommandLineInterface() ? 'cli' : 'web'));
}
class OutputHandler
{
/**
* theme selected by implementer.
* Options: null (default), __construct update to 'default' or theme selected.
* 'default','monokai','natural-flow','mauro-dark','x-space'
*
* @var string
*/
public string $themeused;
/**
* capture the environment for usage in the class.
* Options: empty (default), __construct update to 'ENVIRONMENT_OUTPUT_HANDLER'
* constant or implementor defined environment.
* 'cli','web'
*
* @var string
*/
public string $defenv = '';
/**
* List of TOKENS and Respective flags for Cli Themes.
*
* @var array
*/
const TOKENSLIST = [
T_AS => "as",
T_CLOSE_TAG => "tag",
T_COMMENT => "comment",
T_CONCAT_EQUAL => "",
T_CONSTANT_ENCAPSED_STRING => "string",
T_CONTINUE => "keyword",
T_DOUBLE_ARROW => "variable",
T_ECHO => "keyword",
T_ELSE => "keyword",
T_FILE => "magic",
T_FOREACH => "keyword",
T_FUNCTION => "keyword",
T_IF => "keyword",
T_IS_EQUAL => "",
T_ISSET => "keyword",
T_LIST => "keyword",
T_OPEN_TAG => "tag",
T_RETURN => "keyword",
T_STATIC => "keyword",
T_VARIABLE => "variable",
T_WHITESPACE => "",
T_LNUMBER => "function",
T_DNUMBER => "function",
T_OBJECT_CAST => "variable",
T_STRING => "function",
T_INLINE_HTML => "",
];
/**
* List of CURENCY and Respective flags for Cli Themes.
*
* @var array
*/
const CURRENCIESLIST = [
'¤', '$', '¢', '£', '¥', '₣', '₤', '₧', '€', '₹', '₩', '₴', '₯', '₮',
'₰', '₲', '₱', '₳', '₵', '₭', '₪', '₫', '₠', '₡', '₢', '₥', '₦', '₨',
'₶', '₷', '₸', '₺', '₻', '₼', '₽', '₾', '₿'
];
/**
* List of default themes colors.
*
* @var array
*/
const THEMESLIST = [
'x-space' => ['043,128,041', '099,099,099', '128,128,128', '072,094,187', '221,079,079', '000,000,000'],
'mauro-dark' => ['187,134,252', '250,250,250', '003,218,197', '255,204,255', '207,102,121', '018,018,018'],
'natural-flow' => ['145,155,152', '030,156,107', '003,218,197', '006,156,004', '139,156,051', '004,041,003'],
'monokai' => ['117,113,094', '255,255,255', '102,217,239', '249,038,114', '230,219,116', "039,040,034"],
'default' => ['255,095,000', '000,000,255', '000,000,000', '000,175,000', '255,000,000', '255,255,255'],
];
/**
* definition of colors for implementation in CLI.
*
* @var array
*/
public array $colorcli = [
"comment" => '',
"constant" => '',
"function" => '',
"keyword" => '',
"magic" => '',
"string" => '',
"tag" => '',
"variable" => '',
"html" => '',
"" => "%s",
"background" => '',
];
/**
* Constructor.
*
* @param string $theme
*/
public function __construct($theme = 'default')
{
$this->getTheme($theme);
$this->defenv = ENVIRONMENT_OUTPUT_HANDLER;
}
/**
* Destructor.
*/
public function __destruct()
{
$this->resetHighlight();
}
/**
* Call for reset of Theme colors in Web.
*/
public function resetHighlight(): void
{
ini_set("highlight.comment", "#FF9900");
ini_set("highlight.default", "#0000BB");
ini_set("highlight.html", "#000000");
ini_set("highlight.keyword", "#007700; font-weight: bold");
ini_set("highlight.string", "#DD0000");
}
/**
* Call theme() for theme select by implementer.
*
* @param string $theme
* Options: 'default' (default),'monokai','natural-flow','mauro-dark','x-space'
*/
public function getTheme(string $theme = 'default'): void
{
if (isset(self::THEMESLIST[$theme])) {
$color = self::THEMESLIST[$theme];
$this->themeused = $theme;
} else {
$color = self::THEMESLIST['default'];
$this->themeused = 'default';
}
$this->setHighlightTheme($color);
$this->setHighlightThemeCli($color);
}
/**
* Sets color of theme selected for web design.
*
* @param array $color
*/
private function setHighlightTheme(array $color): void
{
ini_set("highlight.comment", 'rgb(' . $color[0] . '); background-color: rgb(' . $color[5] . ');');
ini_set("highlight.default", 'rgb(' . $color[1] . '); background-color: rgb(' . $color[5] . ');');
ini_set("highlight.html", 'rgb(' . $color[2] . '); background-color: rgb(' . $color[5] . ');');
ini_set("highlight.keyword", 'rgb(' . $color[3] . "); font-weight: bold; background-color: rgb(" . $color[5] . ');');
ini_set("highlight.string", 'rgb(' . $color[4] . '); background-color: rgb(' . $color[5] . ');');
}
/**
* Sets color of theme selected for cli design.
*
* @param array $color
*/
private function setHighlightThemeCli(array $color): void
{
$this->colorcli['comment'] = "\033[38;2;" . $this->colorRGBforCLI($color[0]) . "m%s\033[0m";
$this->colorcli['constant'] = "\033[38;2;" . $this->colorRGBforCLI($color[4]) . "m%s\033[0m";
$this->colorcli['function'] = "\033[38;2;" . $this->colorRGBforCLI($color[1]) . "m%s\033[0m";
$this->colorcli['keyword'] = "\033[38;2;" . $this->colorRGBforCLI($color[3]) . "m%s\033[0m";
$this->colorcli['magic'] = "\033[38;2;" . $this->colorRGBforCLI($color[1]) . "m%s\033[0m";
$this->colorcli['string'] = "\033[38;2;" . $this->colorRGBforCLI($color[4]) . "m%s\033[0m";
$this->colorcli['tag'] = "\033[38;2;" . $this->colorRGBforCLI($color[1]) . "m%s\033[0m";
$this->colorcli['variable'] = "\033[38;2;" . $this->colorRGBforCLI($color[3]) . "m%s\033[0m";
$this->colorcli['html'] = "\033[38;2;" . $this->colorRGBforCLI($color[2]) . "m%s\033[0m";
$this->colorcli['background'] = "\033[48;2;" . $this->colorRGBforCLI($color[5]) . "m";
}
/**
* Convert RGB color String from web standard to ANSI color .
*
* @param string $color
*
* @return string
*/
private function colorRGBforCLI(string $color): string
{
return str_replace(',', ';', $color);
}
/**
* Convert normal string output of variable to
* String highlight like php code for web output
*
* @param string $string
*
* @return string
*/
private function highlightCode(string $string): string
{
return highlight_string("<?php \n#output of Variable:" . str_repeat(' ', 10)
. '*****| Theme Used: ' . $this->themeused . " |*****\n" . $string . "\n?>", true);
}
/**
* Convert normal string output of variable to
* String highlight like php code for cli output
*
* @param string $string
*
* @return string
*/
protected function highlightCodeCli(string $string): string
{
$bg = $this->colorcli['background'];
$string = '<?php' . PHP_EOL . $string . PHP_EOL . '?>';
$string = $this->adjusterSpaceLine($string);
$colors = $this->colorcli;
$output = "";
foreach (token_get_all($string) as $token) {
if (is_string($token)) {
$output .= $bg . $token . "\033[0m";
continue;
}
list($t, $str) = $token;
if ($t == T_STRING) {
if (function_exists($str)) {
$output .= $bg . sprintf($colors["function"], $str) . "\033[0m";
} else {
if (defined($str)) {
$output .= $bg . sprintf($colors["function"], $str) . "\033[0m";
} else {
$output .= $bg . sprintf($colors["function"], $str) . "\033[0m";
}
}
} else {
if (isset(self::TOKENSLIST[$t])) {
$output .= $bg . sprintf($colors[self::TOKENSLIST[$t]], $str) . "\033[0m";
} else {
$output .= $bg . sprintf("<%s '%s'>", token_name($t), $str) . "\033[0m";
}
}
}
return $output;
}
/**
* space adjuster at the end of the line for full background coverage in cli
*
* @param string $string
*
* @return string
*/
private function adjusterSpaceLine(string $string): string
{
$info = shell_exec('MODE 2> null') ?? shell_exec('tput cols');
$widthreal = 80;
if (strlen($info) > 5) {
preg_match('/CON.*:(\n[^|]+?){3}(?<cols>\d+)/', $info, $match);
$widthreal = $match['cols'] ?? 80;
}
$width = (int) $widthreal - 10;
$stringarr = preg_split('/\r\n|\r|\n/', rtrim($string));
$numline = count($stringarr);
$maxlen = max(array_map(function ($el) {
return mb_strlen($el);
}, $stringarr));
$longest = ($maxlen > $width ? $maxlen : $width);
if ($maxlen > $widthreal) {
echo 'Oops, your terminal window is not wide enough to display the information correctly.' . PHP_EOL .
'If you can increase the amount of characters per line (' . ($maxlen + 10) . ') it would work correctly.';
exit;
}
$string = '';
$count = 1;
foreach ($stringarr as $key => $line) {
$lenline = mb_strlen($line);
$string .= $line . str_repeat(' ', $longest - $lenline) . ($count < $numline ? PHP_EOL : '');
$count++;
}
return $string;
}
/**
* CSS applicator for web design.
*
* @param string $string
*
* @return string
*/
private function applyCss(string $string): string
{
$bg = 'rgb(' . self::THEMESLIST[$this->themeused][5] . ')';
$class = mt_rand();
return '<style>
.outputhandler-' . $class . '{
background-color: ' . $bg . '; padding: 8px;
border-radius: 8px;
margin: 5px;
}
.outputhandler-' . $class . ' > code {
padding: unset;
}
</style>
<div class="outputhandler-' . $class . '">' . $string . '</div>';
}
/**
* environment checker; if the implementer is wrong;
* the library will abort any execution immediately
* and display an error message stating that it has happened.
*
* @param null|string $env
*
* @return string
*/
private function checkEnv($env): string
{
$iscli = IsCommandLineInterface();
$env = $env ?? $this->defenv;
if ($iscli && $env == 'wb') {
echo 'error: you are trying to run output() method from CLI and it is not supported, use OutputCli() or AdvanceOutput() with CLI argument method instead.';
exit;
} elseif (!$iscli && $env == 'cli') {
echo 'error: you are trying to run OutputCli() method from web browser and it is not supported, use Output() or AdvanceOutput() with HTML argument method instead.';
exit;
}
return $env;
}
/**
* Check and Execute the request to show the formatted data.
*
* @param mixed $var
* @param null|string $env
* @param bool $retrieve
*
* @return void|string
*/
public function output($var, $env = null, $retrieve = false)
{
$env = $this->checkEnv($env);
if ($env == 'web') {
$string = $this->outputWb($var, $retrieve);
} elseif ($env == 'cli') {
$string = $this->outputCli($var, $retrieve);
} else {
$string = $this->outputWb($var, $retrieve);
}
if ($retrieve) {
return $string;
}
}
/**
* Check and Execute the request to show the formatted data for web environment.
*
* @param mixed $var
* @param bool $retrieve
*
* @return void|string
*/
public function outputWb($var, $retrieve = false)
{
$indents = $this->getIndent($var);
$string = $this->analyzeVariable($var, $indents);
$string = $this->highlightCode($string);
$string = $this->applyCss($string);
$this->resetHighlight();
return ($retrieve ? $string : $this->outView($string));
}
/**
* Check and Execute the request to show the formatted data for cli environment.
*
* @param mixed $var
* @param bool $retrieve
*
* @return void|string
*/
public function outputCli($var, $retrieve = false)
{
$indents = $this->getIndent($var);
$string = $this->analyzeVariable($var, $indents);
$string = $this->highlightCodeCli($string);
$this->resetHighlight();
return ($retrieve ? $string : $this->outView($string));
}
/**
* Evaluates the indentation that the values and
* comments should have in the construction of the output
*
* @param mixed $var
*
* @return array
*/
private function getIndent($var): array
{
$data = $var;
$indents = ['key' => 0, 'val' => 0];
if (is_array($data) || is_object($data)) {
$data = (array) $data;
array_walk_recursive($data, function (&$value) {
$value = is_object($value) ? (array) $value : $value;
});
$deep = ($this->calcDeepArray($data) + 1) * 4;
array_walk_recursive($data, function ($value, $key) use (&$indents) {
if (mb_strpos($key, chr(0)) !== false) {
$key = str_replace(chr(0), "'::'", $key);
$key = substr($key, 4);
}
$indents['key'] = ($indents['key'] >= mb_strlen($key)) ? $indents['key'] : mb_strlen($key);
if (!is_array($value) && !is_object($value) && !is_resource($value)) {
$indents['val'] = ($indents['val'] >= mb_strlen($value)) ? $indents['val'] : mb_strlen($value);
}
}, $indents);
$indents['key'] += $deep;
$indents['val'] += $deep / 2;
} else {
$indents = ['key' => mb_strlen('variable'), 'val' => mb_strlen($data)];
}
return $indents;
}
/**
* Calculates how many nodes deep the passed variable has if it is an array or object.
* note: it does not calculate the number of total nodes.
*
* @param array $array
*
* @return int
*/
private function calcDeepArray(array $array): int
{
$max_depth = 0;
foreach ($array as $key => $value) {
if (is_array($value) || is_object($value)) {
$depth = $this->calcDeepArray((array) $value) + 1;
if ($depth > $max_depth) {
$max_depth = $depth;
}
}
}
return $max_depth;
}
/**
* This should parse each variable passed and build the output string,
* similar to var_dump or var_export.
*
* @param mixed $var
* @param array $indents
*
* @return string
*/
protected function analyzeVariable($var, array $indents): string
{
$varname = 'variable';
$data = $var;
$pretty = function ($indents, $varlentitle, $v = '', $c = " ", $in = 0, $k = null) use (&$pretty) {
$r = '';
if (in_array(gettype($v), ['object', 'array'])) {
if (mb_strpos($k, chr(0)) !== false) {
$k = str_replace(chr(0), "'::'", $k);
$k = substr($k, 4);
}
$lenname = mb_strlen("'$k'");
$lenkeys = $indents['key'] - $in - $lenname;
if ($lenkeys < 0) {
$lenkeys = 0;
}
$eval = $this->evaluateVariable($v);
$v = (array) $v;
$lenkey = $indents['val'] - mb_strlen($eval['val']) + 1;
if (empty($v)) {
$r .= ($in != 0 ? str_repeat($c, $in) : '') . (is_null($k) ? '' : "'$k'"
. str_repeat($c, $lenkeys) . "=> " . $eval['val'] . "[],"
. str_repeat(" ", $lenkey - 6) . "// "
. $eval['desc']) . (empty($v) ? '' : PHP_EOL);
} else {
$r .= ($in != 0 ? str_repeat($c, $in) : '') . (is_null($k) ? '' : "'$k'"
. str_repeat($c, $lenkeys) . "=> " . $eval['val'] . "["
. str_repeat(" ", $lenkey - 4) . "// "
. $eval['desc']) . (empty($v) ? '' : PHP_EOL);
foreach ($v as $sk => $vl) {
$r .= $pretty($indents, $varlentitle, $vl, $c, $in + 4, $sk) . PHP_EOL;
}
$r .= (empty($v) ? '],' : ($in != 0 ? str_repeat($c, $in / 2) : '') .
(is_null($v) ? '' : str_repeat($c, $in / 2) . "],"));
}
} else {
if (mb_strpos($k, chr(0)) !== false) {
$k = str_replace(chr(0), "", $k);
}
$lenkey = $indents['key'] - mb_strlen("'$k'") - $in;
if ($lenkey < 0) {
$lenkey = 0;
}
$eval = $this->evaluateVariable($v);
$lenval = $indents['val'] - (mb_strlen("'" . $eval['val'] . "'"));
if ($lenval < 0) {
$lenval = 0;
}
$r .= ($in != -1 ? str_repeat($c, $in) : '') . (is_null($k) ? '' : "'$k'"
. str_repeat($c, $lenkey) . '=> ') . $eval['val']
. str_repeat(" ", $lenval) . '// ' . $eval['desc'];
}
return str_replace("\0", "", $r);
};
$varlentitle = mb_strlen('$' . $varname);
if (in_array(gettype($var), ['object', 'array'])) {
$string = '$' . $varname . str_repeat(" ", (($indents['key'] - $varlentitle) >= 0 ? $indents['key'] - $varlentitle : 1)) . '= ['
. str_repeat(" ", $indents['val'] - 2) . '// main array node.'
. rtrim($pretty($indents, $varlentitle, $data), ',') . ';';
} else {
$eval = $this->evaluateVariable($data);
$string = '$' . $varname . str_repeat(" ", $indents['key']) . '=' . $eval['val'] . ';'
. str_repeat(" ", $indents['val'] - 1) . '// ' . $eval['desc'];
}
return $string;
}
/**
* This should analyze each variable passed indicate the value and description of it.
* note: the description is a rich text.
*
* @param mixed $var
*
* @return array
*/
protected function evaluateVariable($var): array
{
if (null === $var || 'null' === $var || 'NULL' === $var) {
return is_string($var) ? ['val' => "'null'", 'desc' => 'null value string.'] :
['val' => 'null', 'desc' => 'null value.'];
}
if (is_array($var)) {
return ['val' => "", 'desc' => 'array node.'];
}
if (in_array($var, ["true", "false", true, false], true)) {
return is_string($var) ? ['val' => "'" . $var . "'", 'desc' => 'string value boolean ' . $var . '.'] :
['val' => ($var ? 'true' : 'false'), 'desc' => 'boolean value ' . ($var ? 'true' : 'false') . '.'];
}
if (is_object($var)) {
ob_start();
var_dump($var);
$string = explode('{', ob_get_clean());
return ['val' => '(object) ', 'desc' => rtrim(reset($string)) . '.'];
}
if ((int) $var == $var && is_numeric($var)) {
return is_string($var) ? ['val' => "'" . $var . "'", 'desc' => '(' . mb_strlen($var) . ') integer value string.'] :
['val' => $var, 'desc' => '(' . mb_strlen($var) . ') integer value.'];
}
if ((float) $var == $var && is_numeric($var)) {
return is_string($var) ? ['val' => "'" . $var . "'", 'desc' => '(' . mb_strlen($var) . ') float value string.'] :
['val' => $var, 'desc' => '(' . mb_strlen($var) . ') float value.'];
}
ob_start();
var_dump($var);
$string = ob_get_clean();
if (mb_strpos($string, 'resource') !== false) {
return ['val' => 'resource', 'desc' => rtrim($string) . '.'];
} elseif (mb_strpos($string, 'of type ') !== false) {
return ['val' => 'resource', 'desc' => rtrim($string) . '.'];
}
unset($string);
if (mb_strpos($var, ' ') !== false && mb_strpos($var, ':') !== false && mb_strpos($var, '-') !== false) {
$datetime = explode(" ", $var);
$validate = 0;
foreach ($datetime as $value) {
if ($this->validateDate($value)) {
$validate++;
}
}
if ($validate >= 2) {
return ['val' => "'" . $var . "'", 'desc' => '(' . mb_strlen($var) . ') string value datetime.'];
}
}
if ($this->validateDate($var) && mb_strpos($var, ':') !== false) {
return ['val' => "'" . $var . "'", 'desc' => '(' . mb_strlen($var) . ') string value time.'];
}
if ($this->validateDate($var) && mb_strlen($var) >= 8 && mb_strpos($var, '-') !== false) {
return ['val' => "'" . $var . "'", 'desc' => '(' . mb_strlen($var) . ') string value date.'];
}
if ($this->validateDate($var) && mb_strlen($var) >= 8 && mb_strpos($var, '-') !== false) {
return ['val' => "'" . $var . "'", 'desc' => '(' . mb_strlen($var) . ') string value date.'];
}
if (is_string($var)) {
$arr = $this->splitStrToUnicode($var);
$currencycheck = [];
foreach ($arr as $char) {
if (in_array($char, self::CURRENCIESLIST, true)) {
$currencycheck[] = $char;
}
}
if (!empty($currencycheck)) {
return [
'val' => "'" . $var . "'", 'desc' => 'string/amount value related to currency ('
. implode(',', $currencycheck) . ').'
];
}
}
if (is_string($var)) {
return ['val' => "'" . $var . "'", 'desc' => 'string value of ' . mb_strlen($var) . ' character.'];
}
return ['val' => 'unknown', 'desc' => 'unknown'];
}
/**
* This should validate Date String.
*
* @param string $date
*
* @return bool
*/
private function validateDate(string $date): bool
{
return (strtotime($date) !== false);
}
/**
* This should cut the strings in unicode format.
*
* @param string $str
* @param int $length default 1
*
* @return array
*/
private function splitStrToUnicode(string $str, $length = 1): array
{
$tmp = preg_split('~~u', $str, -1, PREG_SPLIT_NO_EMPTY);
if ($length > 1) {
$chunks = array_chunk($tmp, $length);
foreach ($chunks as $i => $chunk) {
$chunks[$i] = join('', (array) $chunk);
}
$tmp = $chunks;
}
return $tmp;
}
/**
* This should send the text on screen.
*
* @param string $string
*/
private function outView(string $string): void
{
echo $string;
}
}
/**
* check if runtime environment is CLI
*
* @return bool
*/
function IsCommandLineInterface(): bool
{
return (php_sapi_name() === 'cli');
}
</code></pre>
<h2>Example Usage</h2>
<pre class="lang-php prettyprint-override"><code><?php
/**
* This example shows how the BOHBasicOutputHandler class and its methods are declared.
*/
//Import the PHPMailer class into the global namespace
use \IcarosNet\BOHBasicOutputHandler as Output;
require __DIR__ . '\..\vendor\autoload.php';
/**
* FooBar is an example class.
*/
class FooBar
{
public string $pub_string = 'hello world!';
protected int $pro_int = 10;
private array $priv_array = ['a' => 1, 'b' => 2];
const CONST_OBJECT = ['a' => 1, 'b' => 2];
public function foofunction()
{
return "Hello World!";
}
protected function foofunction2()
{
return "Hello World!";
}
}
/**
* $varclass is a variable storage of instance class FooBar.
*/
$varclass = new FooBar;
/**
* $examplesingle is a short variable to use as an example.
*/
$examplesingle = 'Hello World';
/**
* $exampleshortarray is a short variable to use as an example.
*/
$exampleshortarray = ['a' => 1, 'b' => 2];
/**
* $examplearray is a large array variable to use as an example.
*/
$examplearray = [
'null' => null,
'null_text' => 'null',
'integer' => 10,
'integer_text' => '10',
'float' => 20.35,
'float_text' => '20.35',
'string' => 'Hello World',
'date_1' => '2021-01-17',
'date_2' => '2021-Jan-17',
'hour_1' => '6:31:00 AM',
'hour_2' => '17:31:00',
'datetime_1' => '2021-01-17 17:31:00',
'datetime_2' => '2021-Jan-17 6:31:00 AM',
'datetime_3' => '2021-01-17 6:31:00 AM',
'datetime_4' => '2021-Jan-17 17:31:00',
'currency_1' => '1.45$',
'currency_2' => 'db£ 1.45 ₹',
'array' => [
'boolean_true' => true,
'boolean_false' => false,
'boolean_true_text' => 'true',
'boolean_false_text' => 'false',
'object' => (object) [
'key_index_most' => 'Hello Wolrd',
'joder' => [
'prueba' => 'prueba',
]
],
'nested' => [
'other_obj' => (object) [
'apple',
'banana',
'coconut',
],
],
],
'objects_list' => [
'object_empty' => (object) [],
'class' => $varclass,
'resource' => curl_init(),
],
];
//Instance Class BOHBasicOutputHandler
$output = new Output\OutputHandler();
//Theme Selection
$output->getTheme('monokai');
//example 1:
$output->output($examplearray);
$output->getTheme('natural-flow');
//example 2:
$output->output($examplearray);
$output->getTheme('x-space');
//example 3:
$output->output($exampleshortarray);
</code></pre>
<h2>Example Output:</h2>
<p>Please keep in mind that this output was captured in the browser, although it has a code format, this is one of the functionalities of the class. the format is not possible to replicate in SE sites, so I add the images.</p>
<ul>
<li><p><strong>default theme</strong>
<a href="https://i.stack.imgur.com/d0fLi.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/d0fLi.jpg" alt="enter image description here" /></a></p>
</li>
<li><p><strong>monokai theme</strong>
<a href="https://i.stack.imgur.com/QyGEM.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QyGEM.jpg" alt="monokai theme" /></a></p>
</li>
<li><p><strong>natural-flow</strong>
<a href="https://i.stack.imgur.com/Z2ltD.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Z2ltD.jpg" alt="enter image description here" /></a></p>
</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T00:13:31.093",
"Id": "506631",
"Score": "0",
"body": "You should take another look at the way you have implemented \"themes\" - I feel they would be much better defined outside your class and tied together with a `Theme` interface..."
}
] |
[
{
"body": "<blockquote>\n<p>FYI - I'm a bit rusty with PHP and not a PHP expert in anyways.</p>\n</blockquote>\n<h1>TL;DR</h1>\n<ul>\n<li>Be strict on coding style and standard.</li>\n<li>Clean the class responsibility, implement (at least) Single Responsibility Principle.</li>\n<li>Make smaller functions.</li>\n<li>Write Unit test.</li>\n</ul>\n<hr />\n<h1>Retrospect</h1>\n<h3>Use Strict!</h3>\n<p>This generated a lot of errors that was not there before.</p>\n<pre><code><?php declare(strict_types=1);\n</code></pre>\n<h3>Access Specifiers</h3>\n<p>Private, Protected and Public are used, which is great to see but I think there has been put a lot of thought for doing it.</p>\n<h3>Class</h3>\n<p>In general, class OutputHandler is too large, more than 400 lines.The standard rule would be maximum lines of a Class is around 100.</p>\n<p>It has too many functionalities which could be separated out in another class of just utility functions which can be called directly.</p>\n<p>Like IsCommandLineInterface() we can move other common usage functions to a separate file so that our class could be cleaner. Or if are moving with a pure Object Oriented approach then probably make another class.</p>\n<p>I think the best way would be to make separate classes for CLI and Web version. We can have a OutputHandler Abstract base class with some similary functionalities which can be extended by class CliOutputHandler and WebOutputHandler child classes to implement needed features dependently.</p>\n<p>Furthermore,I can see the validation process could be move out to a separate class just with the validation functionality.</p>\n<p>And some more classes are possible for other small utility purposes which could be used just as a function but as I have mentioned let go complete OO.</p>\n<h3>Constructor</h3>\n<p>We might want to do pass example array kind of input variable here and do the validation in the constructor. It would be a good practice.</p>\n<pre><code>public function __construct($theme = 'default')\n{\n $this->getTheme($theme);\n // This is variable is not used so remove. \n // $this->defenv = ENVIRONMENT_OUTPUT_HANDLER;\n}\n</code></pre>\n<h3>Function getTheme()</h3>\n<pre><code>public function getTheme(string $theme = 'default'): void\n{\n if (isset(self::THEMESLIST[$theme])) {\n $color = self::THEMESLIST[$theme];\n $this->themeused = $theme;\n \n } else {\n $color = self::THEMESLIST['default'];\n $this->themeused = 'default';\n }\n\n IsCommandLineInterface() ? \n $this->setHighlightThemeCli($color)\n : $this->setHighlightTheme($color);\n \n} \n</code></pre>\n<h3>Function output()</h3>\n<p>I can see the goodness of strongly type being implemented in few functions. What I would love to see is that, that standard being maintained in this function signature as well.</p>\n<p>Minor modification is done in the implementation.</p>\n<pre><code>public function output($var, $env = null, $retrieve = false)\n{\n \n $indents = $this->getIndent($var);\n $string = $this->analyzeVariable($var, $indents);\n\n if (IsCommandLineInterface() ) {\n $string = $this->highlightCodeCli($string);\n\n } else {\n $string = $this->highlightCode($string);\n }\n\n $string = $this->applyCss($string);\n $this->resetHighlight();\n\n return ($retrieve ? $string : $this->outView($string));\n}\n</code></pre>\n<h3>Function getIndent()</h3>\n<p>One of function I am not happy seeing as I am not able to understand what's the purpose of the function and the way it has been implemented.</p>\n<p>We are returning indents array with [key => value] but we are doing trying to find the length of the array and objects, this is not done using mb_strlen.</p>\n<pre><code>private function getIndent($data): array\n{\n $indents = ['key' => 0, 'val' => 0];\n\n if ( is_array($data) || is_object($data) ) {\n \n $data = is_object($data) ? (array) $data : $data;\n \n // This literally does not make any sense.\n // Why are we looping and assigning value to \n // the same variable $value? And the $value is \n // used in the local scope.\n // array_walk_recursive($data, function (&$value) {\n // $value = is_object($value) ? (array) $value : $value;\n // });\n \n // THIS WILL GIVE ERROR!\n // var_dump($value);\n\n $deep = ($this->calcDeepArray($data) + 1) * 4;\n \n array_walk_recursive($data, function ($value, $key) use (&$indents) {\n\n if (mb_strpos(strval($key), chr(0)) !== false) {\n $key = str_replace(chr(0), "'::'", $key);\n $key = substr($key, 4);\n }\n \n // It does not make sense to use mb_strlen for\n // array and objects.\n if (!is_array($value) \n && !is_object($value) \n && !is_resource($value) \n && !is_null($value)) {\n $indents['val'] = ($indents['val'] >= mb_strlen(strval($value))) \n ? $indents['val'] : mb_strlen(strval($value));\n\n $indents['key'] = ( $indents['key'] >= mb_strlen(strval($key)) ) \n ? $indents['key'] : mb_strlen(strval($key));\n }\n \n\n }, $indents);\n\n $indents['key'] += $deep;\n $indents['val'] += $deep / 2;\n\n } else {\n $indents = ['key' => mb_strlen('variable'), 'val' => mb_strlen($data)];\n }\n\n return $indents;\n}\n</code></pre>\n<h3>function analyzeVariable</h3>\n<p>This is a bit messy. Let try to remove the recursion and check it other simple way. I believe the purpose of the function is to validate the variables in the input. A good way to design a API is to stick to some form of input standards. I think that usage of JSON format would be good as it helps to validate the schema easily. Here is an example of JSON Schema validator:</p>\n<p><a href=\"https://github.com/opis/json-schema\" rel=\"nofollow noreferrer\">https://github.com/opis/json-schema</a></p>\n<p>But it is not mandatory to do it.</p>\n<pre><code>protected function analyzeVariable($data, array $indents): string\n{\n $varname = 'variable';\n\n // We are using anonymous function to do some \n // analysis but I believe there is a better \n // way to do it, even without the use of recursion!\n // I am not sure what are the validation criteria\n // as the function is too hard to understand what's\n // going on.\n $pretty = function ($indents, $varlentitle, $v = '', $c = " ", $in = 0, $k = null) use (&$pretty) {\n $r = '';\n \n // Previously, checking of object and array was done\n // like this:\n // if ( is_array($data) || is_object($data) ) {\n // Why are we chaning the way we check?\n if (in_array(gettype($v), ['object', 'array'])) {\n \n if (!is_null($k)) {\n if (mb_strpos($k, chr(0)) !== false) {\n $k = str_replace(chr(0), "'::'", $k);\n $k = substr($k, 4);\n }\n }\n $lenname = mb_strlen("'$k'");\n $lenkeys = $indents['key'] - $in - $lenname;\n\n if ($lenkeys < 0) {\n $lenkeys = 0;\n }\n\n $eval = $this->evaluateVariable($v);\n\n $v = (array) $v;\n $lenkey = $indents['val'] - mb_strlen($eval['val']) + 1;\n \n if (empty($v)) {\n $r .= ($in != 0 ? str_repeat($c, $in) : '') . (is_null($k) ? '' : "'$k'"\n . str_repeat($c, $lenkeys) . "=> " . $eval['val'] . "[],"\n . str_repeat(" ", $lenkey - 6) . "// "\n . $eval['desc']) . (empty($v) ? '' : PHP_EOL);\n } else {\n $r .= ($in != 0 ? str_repeat($c, $in) : '') . (is_null($k) ? '' : "'$k'"\n . str_repeat($c, $lenkeys) . "=> " . $eval['val'] . "["\n . str_repeat(" ", $lenkey - 4) . "// "\n . $eval['desc']) . (empty($v) ? '' : PHP_EOL);\n \n foreach ($v as $sk => $vl) {\n $r .= $pretty($indents, $varlentitle, $vl, $c, $in + 4, $sk) . PHP_EOL;\n }\n $r .= (empty($v) ? '],' : ($in != 0 ? str_repeat($c, $in / 2) : '') .\n (is_null($v) ? '' : str_repeat($c, $in / 2) . "],"));\n }\n\n } else {\n\n if (mb_strpos($k, chr(0)) !== false) {\n $k = str_replace(chr(0), "", $k);\n }\n\n $lenkey = $indents['key'] - mb_strlen("'$k'") - $in;\n if ($lenkey < 0) {\n $lenkey = 0;\n }\n $eval = $this->evaluateVariable($v);\n $lenval = $indents['val'] - (mb_strlen("'" . $eval['val'] . "'"));\n\n if ($lenval < 0) {\n $lenval = 0;\n }\n $r .= ($in != -1 ? str_repeat($c, $in) : '') . (is_null($k) ? '' : "'$k'"\n . str_repeat($c, $lenkey) . '=> ') . $eval['val']\n . str_repeat(" ", $lenval) . '// ' . $eval['desc'];\n }\n\n return str_replace("\\0", "", $r);\n };\n\n // DO WE EVEN RECACH HERE?\n // There is a return in the recursive function \n // and I'm not sure if we even reach down low.\n\n $varlentitle = mb_strlen('$' . $varname);\n\n if (in_array(gettype($data), ['object', 'array'])) {\n $string = '$' . $varname . str_repeat(" ", (($indents['key'] - $varlentitle) >= 0 ? $indents['key'] - $varlentitle : 1)) . '= ['\n . str_repeat(" ", $indents['val'] - 2) . '// main array node.'\n . rtrim($pretty($indents, $varlentitle, $data), ',') . ';';\n } else {\n $eval = $this->evaluateVariable($data);\n $string = '$' . $varname . str_repeat(" ", $indents['key']) . '=' . $eval['val'] . ';'\n . str_repeat(" ", $indents['val'] - 1) . '// ' . $eval['desc'];\n }\n\n return $string;\n}\n</code></pre>\n<h3>Function evaluateVariable()</h3>\n<p>Well improvements can be here as well</p>\n<pre><code>if (is_object($var)) {\n // Is there any specific reason for it?\n // I am not able to figure out!\n ob_start();\n $string = explode('{', ob_get_clean());\n return ['val' => '(object) ', 'desc' => rtrim(reset($string)) . '.'];\n}\n\n// Im not sure why we need to do this?\n// What are we storing in buffer and \n// reusing? And we are returning so what\n// will be the purpose of doing this?\nob_start();\n$string = ob_get_clean();\nif (mb_strpos($string, 'resource') !== false) {\n return ['val' => 'resource', 'desc' => rtrim($string) . '.'];\n} elseif (mb_strpos($string, 'of type ') !== false) {\n return ['val' => 'resource', 'desc' => rtrim($string) . '.'];\n}\nunset($string);\n \n</code></pre>\n<hr />\n<h1>Conclusion</h1>\n<p>Well those were some things I could see but that is just my perception. There is a lot of room for improvement and I can see there are good signs that your are trying to do that, which is a promising sign :).</p>\n<p>The first thing I would recommend I go through Clean Code, SOLID Principles, and Write Unit Test. PSR has already been mentioned so it would be good to follow them as well.</p>\n<p>As I read from one of your replies that is in your future plan, I would say amend that plan immediately as writing test will help you become a good software engineer and a better programmer! And writing test is not that hard, at all!</p>\n<p>Here is a brief article on Unit Test : <a href=\"https://codeanit.medium.com/developers-guide-write-good-test-5e3e3cdec78e\" rel=\"nofollow noreferrer\">https://codeanit.medium.com/developers-guide-write-good-test-5e3e3cdec78e</a></p>\n<p>To further improve the quality of your code you can use Static Analysis Tools, an example: <a href=\"https://github.com/squizlabs/PHP_CodeSniffer\" rel=\"nofollow noreferrer\">https://github.com/squizlabs/PHP_CodeSniffer</a></p>\n<p>And one last thing I would like to add more is practice data structure and algorithm usage in PHP. Use tools like HackerRank, Codility, etc.. to practice problem solving and code challenges which will definitely make you better. As from the hard review of the code, I definitely can also see a well structural implemented system.</p>\n<p>I wish you all the very best!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T18:46:55.707",
"Id": "506602",
"Score": "0",
"body": "Access specifiers\nThey are used Private, Protected, and Public, which is great to see, but I think a lot of thought has gone into doing it.\n\n**You can be more specific?**"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T18:50:06.103",
"Id": "506604",
"Score": "0",
"body": "**Class:** you have some example of how to implement abstract classes"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T04:33:55.763",
"Id": "506640",
"Score": "0",
"body": "@FranciscoNúñez I am sure you will definitely good examples of OOP in PHP. You can put the examples you have found and put that implementation up for review. But for now I would leave it up to you as it took some time to review the code and I would love see what you can come up from this. \nFor reference: https://github.com/php-cheatsheet, you might find something there.\nAll the very best!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T18:27:46.413",
"Id": "256583",
"ParentId": "256491",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "256583",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T02:44:16.397",
"Id": "256491",
"Score": "1",
"Tags": [
"array",
"regex",
"console",
"reflection",
"phpunit"
],
"Title": "Class showing a format similar to var_dump v1.0.5"
}
|
256491
|
<p>I am working on a simple to do list and i was hoping if a experienced person could review my code in hope for feedback. I don't use any libraries as i haven't taken time to look about them. I decided to stick with plain js.</p>
<p>Thank you for your time.</p>
<p>Edit: Thank you for the reply, now i'm looking into the semantics in html and fixing my 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>let i = 1;
function myFunction(){
n = i.toString();
let theInput = document.getElementById('input').value;
if(theInput == ""){
return false;
}
else{
let input = `<li class = list id = div${n}>` + theInput +` <button onclick = myFunction2("div${n}")>Done</button>`;
newDiv = document.createElement(`div${n}`);
newDiv.innerHTML = input;
const currentDiv = document.getElementById("div0");
currentDiv.insertBefore(newDiv, currentDiv.nextSibling);
i++;
}
}
const myFunction2 = function(id){
let dou = document.getElementById(id)
dou.remove();
}
const myFunction3 = function(className){
let elements = document.getElementsByClassName(className);
while(elements.length > 0){
elements[0].parentNode.removeChild(elements[0]);
}
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>
h1{
font-family: Kufam;
font-size: 50px;
border-color: black;
border-style: solid;
border-width: 12px;
border-radius: 8px;
text-align: center;
}
.list{
font-family: Kufam;
font-size: 25px;
text-align: center;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<title>To do List</title>
<header>
<link href="https://fonts.googleapis.com/css?family=Kufam" rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="todoliststyle.css">
<script type="text/javascript" src="functionList.js"></script>
<h1>
<br>To do List <br>
<input id="input" type="text" placeholder="what to do" required maxlength="50">
<button onclick="myFunction()" >Add</button>
<button onclick="myFunction3(`list`)">Clear All</button> <br><br>
</h1>
<div id="div0">
</header>
</html></code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T15:55:24.793",
"Id": "506566",
"Score": "0",
"body": "Welcome to Code Review. I have rolled back your last edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] |
[
{
"body": "<p>Your app seems to be working :) Good job and keep going ! Take a look at the below notes. I will try to add more a bit later.</p>\n<ul>\n<li>Treat Your variable name as instructions for other developers (and yourself from future). They should be descriptive. Function with name such as <code>Function2</code> are not acceptable</li>\n<li>Your HTML inputs do not have associated labels</li>\n<li>You use <code>h1</code> in a wrong way. It's not a proper tag to place the input in. Use a <code>div</code> instead. H1 is used to define (only one) main heading on Your page. Read about HTML semantics and the meaning of each tag</li>\n<li>some of your <code>let</code> variables could be changed to <code>const</code>s. The rule is as follows - use <code>const</code> whenever it's possible and if it's not - use <code>let</code></li>\n<li>Do not style elements by their tag names like <code>h1{}</code> add the proper class to the element and style it with <code>.className</code> syntax in Your CSS</li>\n<li>Instead of an <code>onCLick</code> inline event listener in Your HTML You could add this handling in the js file using <code>element.addEventListener('typeOfEvent', callback)</code></li>\n<li>Add descriptive <code>ID's</code> to the elements - <code>div0</code> means absolutely nothing</li>\n<li>Your whole logic is in the <code>if/else</code> statement. Try to move it outside</li>\n<li>To DO title should not be in the <code>br</code> tag. Use a header or a <code>p</code> instead</li>\n<li>Your script logic could be also improved -> I will try to describe more a bit later</li>\n<li>You could also use a shortcut for border styles <code>border: 12px solid black</code></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T08:43:36.267",
"Id": "256496",
"ParentId": "256492",
"Score": "4"
}
},
{
"body": "<h2>Coding style</h2>\n<ul>\n<li>Format your code with correct indent. Format your HTML with correct closing tags.</li>\n<li>Name your variable / function / DOM elements with some meaningful names. Not <code>myFunction1</code> nor <code>div0</code>.</li>\n<li>You declared <code>myFunction</code> as global one, but use <code>const</code> for <code>myFunction2</code>. I would suggest use same style for every functions.</li>\n</ul>\n<h2>HTML</h2>\n<ul>\n<li>If you are posting a snippet, skip <code><!doctype html></code> and <code><html></code> would be acceptable. If you are posting whole HTML, make sure to include <code><head></code>, <code><body></code>, <code><meta charset="utf-8" /></code> tags.</li>\n<li>Add <code>lang</code> attribute to your HTML, maybe on <code><html></code> element.</li>\n<li><code><h1></code> is used for title of page. Not for input. Use proper tags.</li>\n<li><code><li></code> should only be placed under <code><ul></code> or <code><ol></code>. It should not be placed under <code><div></code>.</li>\n<li>Use common HTML tags if available. In case you need custom tags, use name with <code>-</code> in it. For example, <code><todo-list-item></code> is acceptable (but not preferred), but <code><div1></code> is not.</li>\n<li>When you need custom tags or using <code><div></code> try adding <code>role</code> on it to make it more meaningful.</li>\n</ul>\n<h2>JavaScript</h2>\n<ul>\n<li>Save a reference to DOM elements, so you do not to <code>getElementById</code> every time some event triggered.</li>\n<li>Never, never, never feed <code>innerHTML</code> with constructed string values. Especially something from user input. It may cause XSS issues.</li>\n<li>Add event listeners with <code>addEventListener</code> instead of <code>onclick</code> attribute is preferred.</li>\n<li>When button [Done] is clicked, you removed the <code><li></code> item but keeps its parent in DOM. It should be a mistake.</li>\n</ul>\n<h2>CSS</h2>\n<ul>\n<li>Use <code>margin</code> / <code>padding</code> to locate items. Do not use <code><br></code> and space character (U+0020).</li>\n</ul>\n<h2>Others</h2>\n<ul>\n<li>Wrap input in a <code><form></code> and listen to <code>submit</code> event instead of <code>click</code> event. So user may add the todo item with an Enter key. (Don't listen to keyup / keydown / keypress events, they may be confused with IME.)</li>\n<li>Clear the input when an todo item is added successfully. So user may add next item without clean the input manually.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T04:10:09.667",
"Id": "256557",
"ParentId": "256492",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T03:14:55.867",
"Id": "256492",
"Score": "4",
"Tags": [
"javascript",
"html",
"css"
],
"Title": "Simple To do List"
}
|
256492
|
<p>So this is a project I have been working on for the last few weeks. Just started learning Python. Started out with bash scripting and got the itch to learn more. Anyway code fetches covid-19 data from the internet, assembles data the way I need it to, plots it on graphs that are saved as .png files, writes all the data and graphs to a 'README.md' file and pushes it to github. As I am self taught I am posting this for feedback so I dont develop bad habits and can learn the best practices. Any advice or criticism would be appreciated. Thank you.</p>
<pre><code>#!/usr/bin/env python3
import requests
import pandas as pd
import io
import numpy as np
import matplotlib.pyplot as plt
import os
# **** Build data ****
# Fetch data
url = 'https://raw.githubusercontent.com/nytimes/covid-19-data/master/us.csv'
download = requests.get(url).content
df = pd.read_csv(io.StringIO(download.decode('utf-8')))
# Extract each column individually
date = df['date']
cases = df['cases']
deaths = df['deaths']
# Calculate new cases
total_cases = np.array(cases)
new_cases = np.diff(total_cases)
new_cases = np.insert(new_cases, 0, 1)
# Calculate new deaths
total_deaths = np.array(deaths)
new_deaths = np.diff(total_deaths)
new_deaths = np.insert(new_deaths, 0, 0)
# Create csv for total cases and deaths
df = pd.DataFrame({'date': date, 'total cases': total_cases,
'total deaths': total_deaths})
df.to_csv('data/us_covid-19_total.csv', index=False)
# Create csv for new cases and deaths
df = pd.DataFrame({'date': date, 'new cases': new_cases,
'new deaths': new_deaths})
df.to_csv('data/us_covid-19_new.csv', index=False)
# Create csv for all aggregated data
df = pd.DataFrame({'date': date, 'total cases': total_cases,
'total deaths': total_deaths, 'new cases': new_cases, 'new deaths': new_deaths})
df.to_csv('data/us_covid-19_data.csv', index=False)
# **** Plot data ****
# x axis for all plots
x = np.array(date, dtype='datetime64')
# Plot Total Cases
y = total_cases / 1000000
plt.figure('US Total COVID-19 Cases', figsize=(15, 8))
plt.title('US Total COVID-19 Cases')
plt.ylabel('Cases (in millions)')
plt.grid(True, ls='-.')
plt.yticks(np.arange(min(y), max(y) + 10))
plt.plot(x, y, color='b')
plt.savefig('plots/US_Total_COVID-19_Cases.png')
# Plot Total Deaths
y = total_deaths / 1000
plt.figure('US Total COVID-19 Deaths', figsize=(15, 8))
plt.title('US Total COVID-19 Deaths')
plt.ylabel('Deaths (in thousands)')
plt.grid(True, ls='-.')
plt.yticks(np.arange(min(y), max(y) + 100, 50))
plt.plot(x, y, color='b')
plt.savefig('plots/US_Total_COVID-19_Deaths.png')
# Plot New Cases
y = new_cases / 1000
plt.figure('US New COVID-19 Cases', figsize=(15, 8))
plt.title('US New COVID-19 Cases')
plt.ylabel('Cases (in thousands)')
plt.grid(True, ls='-.')
plt.yticks(np.arange(min(y), max(y) + 100, 50))
plt.plot(x, y, color='b')
plt.savefig('plots/US_New_COVID-19_Cases.png')
# Plot New Deaths
y = new_deaths
plt.figure('US New COVID-19 Deaths', figsize=(15, 8))
plt.title('US New COVID-19 Deaths')
plt.ylabel('Deaths')
plt.grid(True, ls='-.')
plt.yticks(np.arange(min(y), max(y) + 1000, 500))
plt.plot(x, y, color='b')
plt.savefig('plots/US_New_COVID-19_Deaths.png')
# **** Write to README.md ****
# New cases and deaths in the last 24 hours
cases = new_cases[-1]
deaths = new_deaths[-1]
# 7-day mean for new cases and deaths
cmean = np.mean(new_cases[-7:])
dmean = np.mean(new_deaths[-7:])
# Date
date = np.array(date, dtype='datetime64')
date = date[-1]
# DataFrame for new cases and deaths in the last 24 hours
df_24 = pd.DataFrame({'New cases': [f'{cases:,d}'], 'New deaths': [f'{deaths:,d}']})
df_24 = df_24.to_markdown(index=False, disable_numparse=True)
# DataFrame for 7-day average
df_avg = pd.DataFrame({'Cases': [f'{int(cmean):,d}'], 'Deaths': [f'{int(dmean):,d}']})
df_avg = df_avg.to_markdown(index=False, disable_numparse=True)
# Write to 'README.md'
f = open('README.md', 'w')
f.write(f'''# US COVID-19 [Data](https://github.com/drebrb/covid-19-data/blob/master/data/us_covid-19_data.csv)
###### Reported numbers for {str(date)}
{df_24}
###### 7-day average
{df_avg}
## [Total Cases and Deaths](https://github.com/drebrb/covid-19-data/blob/master/data/us_covid-19_total.csv)
### Cases

### Deaths

## [New Cases and Deaths](https://github.com/drebrb/covid-19-data/blob/master/data/us_covid-19_new.csv)
### Cases

### Deaths
''')
f.close()
# **** push to github ****
os.system('git add . && git commit -m "Updating data." && git push')
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T10:45:47.553",
"Id": "506433",
"Score": "0",
"body": "Please follow the guidelines: https://codereview.stackexchange.com/help/how-to-ask ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T13:58:19.740",
"Id": "506669",
"Score": "1",
"body": "Just a quick tip: Since version 3.6 of Python you can write `1_000_000` instead of `1000000`. The underscore in numbers is actually ignored by the Python interpreter, but it makes big numbers more readable for the human eye and can therefore prevent errors."
}
] |
[
{
"body": "<p>You should add a <code>requirements.txt</code> containing something like</p>\n<pre><code>tabulate\npandas\nrequests\nnumpy\nmatplotlib\n</code></pre>\n<p>The first requirement was hidden and bit me when I attempted to run your code.</p>\n<p>Introduce error checking to your <code>requests</code> call, and let it handle encoding for you:</p>\n<pre><code>url = 'https://raw.githubusercontent.com/nytimes/covid-19-data/master/us.csv'\nwith requests.get(url) as response:\n response.raise_for_status()\n with io.StringIO(response.text) as download:\n df = pd.read_csv(download)\n</code></pre>\n<p>You should be creating the data and plot directories if they don't exist, something like</p>\n<pre><code>data = Path('data')\nif data.exists():\n assert data.is_dir()\nelse:\n data.mkdir()\n# ...\ndf.to_csv(data / 'us_covid-19_total.csv', index=False)\n</code></pre>\n<p>Use a context manager for your readme writing:</p>\n<pre><code>with open('README.md', 'w') as f:\n f.write( # ...\n</code></pre>\n<p>Try to move your large heredoc-style README content to a template file and use the built-in <a href=\"https://docs.python.org/3/library/string.html#template-strings\" rel=\"nofollow noreferrer\">templating</a> facility.</p>\n<p>Don't call <code>os.system</code>, don't use shell statements, and don't concatenate them with <code>&&</code>. Instead, use <a href=\"https://docs.python.org/3.6/library/subprocess.html#subprocess.check_call\" rel=\"nofollow noreferrer\">check_call</a> and call directly into <code>/usr/bin/git</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T17:42:19.790",
"Id": "506447",
"Score": "1",
"body": "Wow thank you. That's a lot of great information. Definitely going to add the requirements.txt, sorry about that! As for the data and plots directory I was on the fence on whether I should warn the user if the directories are missing or if I should just create them. I'll need to research templating and check_call as I am not familiar with them, but I do understand your request call block, and context manager and will be implementing those. Thank you, still have lots to learn lol."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T19:12:19.827",
"Id": "506452",
"Score": "0",
"body": "Throwing if the directories don't already exist is a fine option too; whatever works for your use case."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T15:48:04.773",
"Id": "256509",
"ParentId": "256493",
"Score": "3"
}
},
{
"body": "<p>Your code is currently a linear sequence of steps. Even for fairly short\nprograms, that's an inflexible structure that is difficult to experiment with,\ndebug, test, and evolve. The solution is to break your code apart into separate\nfunctions, each having a narrow focus. Here's a rough sketch. The basic idea is\nto place all code (other than imports and constants) inside of functions.</p>\n<pre><code># Imports and constants.\n\nimport sys\n...\n\nDATA_URL = 'https://raw.githubusercontent.com/nytimes/covid-19-data/master/us.csv'\n\n# The program entry point\n\ndef main(args):\n ...\n\n# Functions to do various things.\n\ndef fetch_data():\n ...\n\ndef write_csv_file(():\n ...\n\n# Call main().\n\nif __name__ == '__main__':\n main(sys.arvg[1:])\n</code></pre>\n<p>Making that change will instantly open up other opportunities. For example, you\nmight want to add a new behavior in the future. That new behavior can be\neasily added without requiring you to revisit the entire program. Instead, you\ncould simply use a command-line argument (<code>args</code> in the sketch above) to\ntrigger the new behavior.</p>\n<p>Your code also has some repetitiveness -- for example, CSV file creation and\nplot creation. The solution again involves using functions: identify the parts\nthat are repetitive; store the parameters that vary in a data structure; and\nmove the repeated action into a function. For example, for CSV file creation\nyou might consider something along the lines sketched below. A similar set\nof tactics could be applied to plot creation as well.</p>\n<pre><code>def main(args):\n ...\n write_csv_files(...)\n\ndef write_csv_files(date, total_cases, total_deaths, new_cases, new_deaths):\n # Prepare the parameters that vary.\n csv_cols = {\n 'date': date,\n 'total cases': total_cases,\n 'total deaths': total_deaths,\n 'new cases': new_cases,\n 'new deaths': new_deaths,\n }\n # A data structure to drive the iteration.\n csv_file_params = {\n 'total': ['date', 'total cases', 'total deaths']\n 'new': ['date', 'new cases', 'new deaths'],\n 'data': ['date', 'total cases', 'total deaths', 'new cases', 'new deaths'],\n }\n # Iterate.\n for suffix, col_names in csv_file_params.items():\n file_path = f'data/us_covid-19_{suffix}.csv'\n d = {nm : csv_cols[nm] for nm in col_names}\n write_csv_file(file_path, d)\n\ndef write_csv_file(file_path, d, index=False):\n df = pd.DataFrame(d)\n df.to_csv(file_path, index=index)\n</code></pre>\n<p>Your code is starting to get a proliferation of variables. For example, in the\nsketch above, <code>write_csv_files()</code> requires 5 arguments. That's not terrible,\nbut it is a bit of an early-warning sign. If those variables need to move\naround together in your program, you could consider various ways to bundle them\ntogether. There are many options, such as a <code>dict</code>, a <code>namedtuple</code>, or a\n<code>dataclass</code>.</p>\n<p>Large multi-line strings are a hindrance to code readability and understanding.\nRather than cluttering up the <code>README</code> writing logic with a giant string,\nseparate the boring stuff (the bulk of the text than never changes)\nfrom the coding logic:</p>\n<pre><code>from textwrap import dedent\n\n# Define the template as a constant.\nREADME_TEMPLATE = dedent('''\n # US COVID-19 [Data](https://github.com/drebrb/covid-19-data/blob/master/data/us_covid-19_data.csv)\n ###### Reported numbers for {} \n {}\n ###### 7-day average \n {}\n ## [Total Cases and Deaths](https://github.com/drebrb/covid-19-data/blob/master/data/us_covid-19_total.csv)\n ### Cases\n \n ### Deaths\n \n ## [New Cases and Deaths](https://github.com/drebrb/covid-19-data/blob/master/data/us_covid-19_new.csv) \n ### Cases\n \n ### Deaths\n \n''')\n\ndef write_readme(date, df_24, df_avg):\n with open('README.md', 'w') as fh:\n fh.write(README_TEMPLATE.format(date, df_24, df_avg))\n</code></pre>\n<p>HTTP requests and <code>git</code> operations can fail. They should be wrapped in\n<code>try</code> blocks, with failures handled one way or another, as noted already in\nthe good review from Reinderien.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T00:54:52.100",
"Id": "506467",
"Score": "1",
"body": "Wow thank you so much. Some of what you explained I do not understand YET as I am still learning but you have provided me with enough information for me to now research and learn. Thank you."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T00:28:38.063",
"Id": "256522",
"ParentId": "256493",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "256522",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T05:22:51.917",
"Id": "256493",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"numpy",
"pandas",
"matplotlib"
],
"Title": "Downloading COVID data and uploading graphs"
}
|
256493
|
<p>I'm new to Rust and am learning by implementing my own version of <a href="https://pubs.opengroup.org/onlinepubs/9699919799/utilities/cut.html" rel="nofollow noreferrer"><code>cut</code></a>. This is a snippet that parses the <code><list></code> of ranges required for the <code>-f</code>, <code>-b</code>, or <code>-c</code> options. The relevant section of the spec states:</p>
<blockquote>
<p>The application shall ensure that the option-argument list (see options -b, -c, and -f below) is a -separated list or -separated list of positive numbers and ranges. Ranges can be in three forms. The first is two positive numbers separated by a (low- high), which represents all fields from the first number to the second number. The second is a positive number preceded by a (- high), which represents all fields from field number 1 to that number. The third is a positive number followed by a ( low-), which represents that number to the last field, inclusive. The elements in list can be repeated, can overlap, and can be specified in any order, but the bytes, characters, or fields selected shall be written in the order of the input data. If an element appears in the selection list more than once, it shall be written exactly once.</p>
</blockquote>
<p>I'm interested in tips for writing more idiomatic Rust (especially the error handling), and any other hints for a new Rust programmer. Thanks!</p>
<pre><code>use std::error::Error;
use std::fmt;
use std::fmt::{Display, Formatter};
use std::iter::FromIterator;
use std::num::ParseIntError;
pub type Result<T> = std::result::Result<T, RangeError>;
#[derive(Debug, Eq, PartialEq)]
pub enum RangeError {
MalformedRangSpec,
Parse(ParseIntError),
}
impl Display for RangeError {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
use RangeError::*;
let msg = match self {
MalformedRangSpec => format!("Invalid range spec"),
Parse(e) => e.to_string(),
};
write!(f, "Error: {}", msg)
}
}
impl From<ParseIntError> for RangeError {
fn from(e: ParseIntError) -> Self {
RangeError::Parse(e)
}
}
impl Error for RangeError {}
#[derive(Debug, Eq, PartialEq, Hash)]
pub enum Range {
From(usize),
To(usize),
Inclusive(usize, usize),
Singleton(usize),
}
#[derive(Debug, Eq, PartialEq)]
pub struct RangeSet {
ranges: Vec<Range>,
}
impl RangeSet {
pub fn from<I: IntoIterator<Item = Range>>(iter: I) -> RangeSet {
RangeSet {
ranges: Vec::from_iter(iter),
}
}
pub fn from_spec<T: AsRef<str>>(spec: T) -> Result<RangeSet> {
// "-5,10,14-17,20-"
let tuples = spec
.as_ref()
.split(|c| c == ',' || c == ' ') // e.g. ["-5", "10", "14-17", "20-"]
// [[None, Some(5)], [Some(10)], [Some(14), Some(17)], [Some(20), None]]
.map(|element| {
element
.split('-') // e.g. first iter: ["", 5]
.map(|bound| match bound {
// e.g. [None, Some("5")]
"" => Ok(None),
s => {
let n: usize = s.parse()?;
Ok(Some(n))
}
})
.collect::<Result<Vec<_>>>()
})
.collect::<Result<Vec<_>>>()?;
let ranges: Vec<Range> = tuples
.iter()
.map(|range| match range.as_slice() {
[Some(n)] => Ok(Range::Singleton(*n)),
[Some(s), Some(e)] => Ok(Range::Inclusive(*s, *e)),
[Some(s), None] => Ok(Range::From(*s)),
[None, Some(e)] => Ok(Range::To(*e)),
_ => Err(RangeError::MalformedRangSpec),
})
.collect::<Result<Vec<_>>>()?;
Ok(RangeSet::from(ranges))
}
pub fn contains(&self, n: usize) -> bool {
if n == 0 {
// range defined to start at 1
return false;
}
self.ranges.iter().any(|range| match range {
Range::From(from) => (*from..).contains(&n),
Range::To(to) => (1..=*to).contains(&n),
Range::Inclusive(from, to) => (*from..=*to).contains(&n),
Range::Singleton(s) => s == &n,
})
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn contains() {
let r = RangeSet::from(vec![
Range::From(100),
Range::Inclusive(50, 60),
Range::Singleton(40),
Range::To(10),
]);
for n in 0..1000 {
match n {
1..=10 | 40..=40 | 50..=60 | 100..=1000 => {
assert!(r.contains(n), "should contain {}", n)
}
_ => assert!(!r.contains(n), "shouldn't contain {}", n),
}
}
}
#[test]
fn from_spec() {
let r1 = RangeSet::from(vec![Range::Singleton(1)]);
let r2 = RangeSet::from_spec("1");
assert_eq!(Ok(r1), r2);
let r1 = RangeSet::from(vec![
Range::To(10),
Range::Singleton(40),
Range::Inclusive(50, 60),
Range::From(100),
]);
let r2 = RangeSet::from_spec("-10,40,50-60,100-");
assert_eq!(Ok(r1), r2);
}
#[test]
fn from_spec_bad() {
assert!(RangeSet::from_spec("b").is_err());
assert!(RangeSet::from_spec("4-5-6").is_err());
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Nice use of the custom types <code>RangeError</code>, <code>Range</code>, and <code>RangeSet</code>. Some feedback:</p>\n<ul>\n<li><p>The biggest problem with your code I see is that the <code>RangeSet::from_spec</code> function is quite gnarly. On inspection, my diagnosis of the problem is that you are implementing functionality in <code>RangeSet</code> that would be better implemented on <code>Range</code>.\nHere is a refactoring:</p>\n<pre><code>impl FromStr for Range {\n type Err = RangeError;\n\n fn from_str(s: &str) -> Result<Range> {\n let bounds = s\n .split('-')\n .map(|bound| match bound {\n "" => Ok(None),\n s => Ok(Some(s.parse()?))\n })\n .collect::<Result<Vec<_>>>()?;\n match bounds.as_slice() {\n [Some(n)] => Ok(Range::Singleton(*n)),\n [Some(s), Some(e)] => Ok(Range::Inclusive(*s, *e)),\n [Some(s), None] => Ok(Range::From(*s)),\n [None, Some(e)] => Ok(Range::To(*e)),\n _ => Err(RangeError::MalformedRangSpec),\n }\n }\n}\nimpl Range {\n pub fn contains(&self, n: usize) -> bool {\n if n == 0 {\n return false;\n }\n match self {\n Range::From(from) => (*from..).contains(&n),\n Range::To(to) => (1..=*to).contains(&n),\n Range::Inclusive(from, to) => (*from..=*to).contains(&n),\n Range::Singleton(s) => s == &n,\n }\n }\n}\n</code></pre>\n</li>\n<li><p>In <code>match</code> statements, you can also clean up all of those extraneous <code>*</code>s by pattern matching on <code>match *x</code> instead of <code>match x</code>, here's how that looks:</p>\n<pre><code>impl Range {\n pub fn contains(&self, n: usize) -> bool {\n if n == 0 {\n return false;\n }\n match *self {\n Range::From(from) => (from..).contains(&n),\n Range::To(to) => (1..=to).contains(&n),\n Range::Inclusive(from, to) => (from..=to).contains(&n),\n Range::Singleton(s) => s == n,\n }\n }\n}\n</code></pre>\n<p>and similarly in <code>fn from_str</code>: <code>match *bounds.as_slice()</code> and <code>[Some(n)] => Ok(Range::Singleton(n))</code> etc.</p>\n</li>\n<li><p>In the <code>&[Some(s), Some(e)] => Ok(Range::Inclusive(s, e))</code> case, maybe you want to check that the range is nontrivial:</p>\n<pre><code> [Some(s), Some(e)] => {\n if s < e {\n Ok(Range::Inclusive(s, e))\n } else {\n Err(RangeError::MalformedRangSpec)\n }\n },\n</code></pre>\n</li>\n<li><p>With these implementations on <code>Range</code>, <code>RangeSet</code> becomes much simpler:</p>\n<pre><code>impl RangeSet {\n pub fn from<I: IntoIterator<Item = Range>>(iter: I) -> RangeSet {\n RangeSet {\n ranges: Vec::from_iter(iter),\n }\n }\n\n pub fn from_spec<T: AsRef<str>>(spec: T) -> RangeResult<RangeSet> {\n // "-5,10,14-17,20-"\n let ranges = spec\n .as_ref()\n .split(|c| c == ',' || c == ' ')\n // e.g. ["-5", "10", "14-17", "20-"]\n .map(|element| element.parse())\n .collect::<RangeResult<Vec<_>>>()?;\n\n Ok(RangeSet::from(ranges))\n }\n\n pub fn contains(&self, n: usize) -> bool {\n self.ranges.iter().any(|range| range.contains(n))\n }\n}\n</code></pre>\n</li>\n<li><p>Your implementation currently lacks a CLI. For that, you will probably want to use the <a href=\"https://docs.rs/structopt/0.3.21/structopt/\" rel=\"nofollow noreferrer\">structopt</a> crate. It is worth considering that this may make some of your functionality, in particular <code>RangeSet::from_spec</code> unnecessary. In particular, if you define a command-line argument of type <code>Vec<Range></code> StructOpt would automatically determine a reasonable way to parse a string into a vector of ranges (this relies on <code>Range</code> implementing <code>FromStr</code> which we did above).</p>\n</li>\n<li><p>The <code>RangeError</code> implementation is an idiomatic way of handling errors and looks good.\nHowever, I personally would prefer not to redefine standard library types like <code>pub type Result<T> = std::result::Result<T, RangeError></code>, since it leads to non-standard function signatures that are not immediately readable. The error type is part of the behavior of a function, so better to explicitly return <code>Result<T, RangeError></code> in your functions. Alternatively you could just use a new name:</p>\n<pre><code>pub type RangeResult<T> = Result<Range, RangeError>\n</code></pre>\n<p>(FWIW, I also think <code>std::fmt::Result</code> and <code>std::io::Result<T></code> were mistakes.)</p>\n</li>\n</ul>\n<p>Final code:</p>\n<pre><code>use std::error::Error;\nuse std::fmt;\nuse std::fmt::{Display, Formatter};\nuse std::iter::FromIterator;\nuse std::num::ParseIntError;\nuse std::str::FromStr;\n\npub type RangeResult<T> = std::result::Result<T, RangeError>;\n\n#[derive(Debug, Eq, PartialEq)]\npub enum RangeError {\n MalformedRangSpec,\n Parse(ParseIntError),\n}\n\nimpl Display for RangeError {\n fn fmt(&self, f: &mut Formatter) -> fmt::Result {\n use RangeError::*;\n let msg = match self {\n MalformedRangSpec => "Invalid range spec".to_string(),\n Parse(e) => e.to_string(),\n };\n write!(f, "Error: {}", msg)\n }\n}\n\nimpl From<ParseIntError> for RangeError {\n fn from(e: ParseIntError) -> Self {\n RangeError::Parse(e)\n }\n}\n\nimpl Error for RangeError {}\n\n#[derive(Debug, Eq, PartialEq, Hash)]\npub enum Range {\n From(usize),\n To(usize),\n Inclusive(usize, usize),\n Singleton(usize),\n}\n\n// Added\nimpl FromStr for Range {\n type Err = RangeError;\n\n fn from_str(s: &str) -> RangeResult<Range> {\n let bounds = s\n .split('-')\n .map(|bound| match bound {\n "" => Ok(None),\n s => Ok(Some(s.parse()?))\n })\n .collect::<RangeResult<Vec<_>>>()?;\n match *bounds.as_slice() {\n [Some(n)] => Ok(Range::Singleton(n)),\n [Some(s), Some(e)] => {\n if s < e {\n Ok(Range::Inclusive(s, e))\n } else {\n Err(RangeError::MalformedRangSpec)\n }\n },\n [Some(s), None] => Ok(Range::From(s)),\n [None, Some(e)] => Ok(Range::To(e)),\n _ => Err(RangeError::MalformedRangSpec),\n }\n }\n}\nimpl Range {\n pub fn contains(&self, n: usize) -> bool {\n if n == 0 {\n return false;\n }\n match *self {\n Range::From(from) => (from..).contains(&n),\n Range::To(to) => (1..=to).contains(&n),\n Range::Inclusive(from, to) => (from..=to).contains(&n),\n Range::Singleton(s) => s == n,\n }\n }\n}\n\n#[derive(Debug, Eq, PartialEq)]\npub struct RangeSet {\n ranges: Vec<Range>,\n}\n\nimpl RangeSet {\n pub fn from<I: IntoIterator<Item = Range>>(iter: I) -> RangeSet {\n RangeSet {\n ranges: Vec::from_iter(iter),\n }\n }\n\n pub fn from_spec<T: AsRef<str>>(spec: T) -> RangeResult<RangeSet> {\n // "-5,10,14-17,20-"\n let ranges = spec\n .as_ref()\n .split(|c| c == ',' || c == ' ')\n // e.g. ["-5", "10", "14-17", "20-"]\n .map(|element| element.parse())\n .collect::<RangeResult<Vec<_>>>()?;\n\n Ok(RangeSet::from(ranges))\n }\n\n pub fn contains(&self, n: usize) -> bool {\n self.ranges.iter().any(|range| range.contains(n))\n }\n}\n\n#[cfg(test)]\nmod test {\n use super::*;\n\n #[test]\n fn contains() {\n let r = RangeSet::from(vec![\n Range::From(100),\n Range::Inclusive(50, 60),\n Range::Singleton(40),\n Range::To(10),\n ]);\n\n for n in 0..1000 {\n match n {\n 1..=10 | 40..=40 | 50..=60 | 100..=1000 => {\n assert!(r.contains(n), "should contain {}", n)\n }\n _ => assert!(!r.contains(n), "shouldn't contain {}", n),\n }\n }\n }\n\n #[test]\n fn from_spec() {\n let r1 = RangeSet::from(vec![Range::Singleton(1)]);\n let r2 = RangeSet::from_spec("1");\n assert_eq!(Ok(r1), r2);\n\n let r1 = RangeSet::from(vec![\n Range::To(10),\n Range::Singleton(40),\n Range::Inclusive(50, 60),\n Range::From(100),\n ]);\n\n let r2 = RangeSet::from_spec("-10,40,50-60,100-");\n\n assert_eq!(Ok(r1), r2);\n }\n\n #[test]\n fn from_spec_bad() {\n assert!(RangeSet::from_spec("b").is_err());\n assert!(RangeSet::from_spec("4-5-6").is_err());\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T00:11:18.310",
"Id": "506465",
"Score": "1",
"body": "Thanks for insight! \"(FWIW, I also think std::fmt::Result and std::io::Result<T> were mistakes.)\"\n\nI thought this was confusing too but it seemed to be the convention. I like your suggestion better."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T14:53:33.910",
"Id": "256507",
"ParentId": "256495",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "256507",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T07:53:40.090",
"Id": "256495",
"Score": "3",
"Tags": [
"rust"
],
"Title": "List parsing for 'cut'"
}
|
256495
|
<p>I have some classes with properties, wich could only have numeric values in a given range (e.g. 0 to 8). This should be validated and wrong values prevented with an exception. The given behavior may be implemented without duplicating the given code.</p>
<p>There are some <a href="https://docs.microsoft.com/en-us/dotnet/api/system.configuration.integervalidatorattribute?view=dotnet-plat-ext-5.0" rel="nofollow noreferrer">ValidatorAttributes</a> in C# but I can't get them to running. They don't seem to prevent the assignment with wrong values in a normal class.</p>
<p>My current solution is to copy paste this snippet for every attribute. But copy paste is not perfect:</p>
<pre><code>private short _index;
public short Index
{
get => this._index;
private set
{
const short min = 0;
const short max = 8;
if (value < min || max < value)
{
throw new ArgumentOutOfRangeException("The passed value is not between " + min + " and " + max + " (values included)");
}
this._index = value;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T10:28:08.770",
"Id": "506430",
"Score": "4",
"body": "The attribute itself does not execute any code. A certain engine must use the code described in this attribute. The attribute you mentioned is used by the configuration engine. And, for example, this [Range](https://docs.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.rangeattribute?view=net-5.0) attribute is used by the ASP.NET engine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T10:37:07.560",
"Id": "506431",
"Score": "0",
"body": "You can use AOP if you want to add elegant validation."
}
] |
[
{
"body": "<p>To reduce the lines of code to copy/paste, you could create a helper method:</p>\n<pre><code>public static class Helper\n{\n public static void EnsureIsInRange(short value, short min, short max)\n {\n if (value < min || max < value)\n {\n throw new ArgumentOutOfRangeException("The passed value is not between " + min + " and " + max + " (values included)");\n }\n }\n}\n</code></pre>\n<p>or more generic:</p>\n<pre><code>public static class Helper\n{\n public static void EnsureIsInRange<T>(T value, T min, T max) where T : IComparable<T>\n {\n if (value.CompareTo(min) != 1 || value.CompareTo(max) != -1)\n {\n throw new ArgumentOutOfRangeException("The passed value is not between " + min + " and " + max + " (values included)");\n }\n }\n}\n</code></pre>\n<p>// usage:</p>\n<pre><code>private short _index;\npublic short Index\n{\n get => this._index;\n private set\n {\n Helper.EnsureIsInRange(value, 0, 8);\n this._index = value;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T10:40:19.043",
"Id": "506432",
"Score": "0",
"body": "Thank you for your help. It thats what I need."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T10:31:42.277",
"Id": "256500",
"ParentId": "256498",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "256500",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T09:48:55.367",
"Id": "256498",
"Score": "0",
"Tags": [
"c#",
"object-oriented",
"validation",
"integer"
],
"Title": "optimize integer validation"
}
|
256498
|
<p>I'm writing a little library for some undocumented file formats. The original program uses a path string to find files in an archive and this function tries to do the same.</p>
<p>The archive contains a magic string, an offset into the file list, the data in the files and the file list itself. A entry in the filelist consists of a path (256 bytes long, 0-padded) and three numbers, the second one being the offset from the archive start to the entry file. The entries are sorted alphabetically respecting case; here are some mockup paths to demonstrate the ordering:</p>
<pre><code>Entry/Graphics/Sprite.cgf
Entry/Sound/Ding.wav
Quit/Graphics/exit.cgf
_RAW8123
</code></pre>
<p>Here are the relevant utility functions and defines. These are defined in <code>Utils.h</code> and <code>Utils.c</code>, I've put them here together for context.</p>
<pre><code>#define BYTESZE sizeof(char)
typedef unsigned int uint;
typedef unsigned char byte;
uint readU4L(FILE* file) {
byte buf[4];
fread(buf, BYTESZE, 4, file);
return buf[3] << 24 | buf[2] << 16 | buf[1] << 8 | buf[0];
}
</code></pre>
<p>Finally, here's the "library":</p>
<pre><code>// ====== BIGfile.h
#define BIG_MAGIC_LEN 7
#define BIG_SEEK_SUCC 1
#define BIG_SEEK_FAIL 0
typedef struct BIGFile {
char magic[BIG_MAGIC_LEN];
uint offset;
FILE* read;
} BIGFile;
BIGFile* load_BIGFile(char* fpath);
int seekToEntry(BIGFile* bigfile, char* path);
</code></pre>
<pre><code>// ====== BIGFile.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Utils.h"
#include "BIGFile.h"
BIGFile* load_BIGFile(char* fpath) {
BIGFile* bigfile = malloc(sizeof(BIGFile));
fopen_s(&(bigfile->read), fpath, "rb");
if (!bigfile->read) {
printf("Can't open file.\n");
return 0;
}
fread(bigfile->magic, BYTESZE, BIG_MAGIC_LEN, bigfile->read);
bigfile->offset = readU4L(bigfile->read);
return bigfile;
}
int seekToEntry(BIGFile* bigfile, char* path) {
fseek(bigfile->read, bigfile->offset, SEEK_SET);
byte buf[256];
int pos = 0;
// while not EOF, read string part
while (fread(buf, BYTESZE, 256, bigfile->read)) {
// seek over entry data
fseek(bigfile->read, 12, SEEK_CUR);
// loop until given path != read path
while (path[pos]==buf[pos]) {
pos++;
// path has ended, so buf == path
if (!path[pos]) {
// seek back into entry data
fseek(bigfile->read, -8, SEEK_CUR);
// read unsigned little endian 4-byte int
uint res = readU4L(bigfile->read);
// seek there and return success
fseek(bigfile->read, res, SEEK_SET);
//printf("found at %d\n", res);
return BIG_SEEK_SUCC;
}
}
// path char is smaller than buf char
// we seeked past where the entry could bem return failure
if (path[pos]<buf[pos]) {
return BIG_SEEK_FAIL;
}
}
// EOF, return failure
return BIG_SEEK_FAIL;
}
</code></pre>
<p>I'd like some feedback on general style, as well as on the <code>seekToEntry</code> function, perhaps this can be improved somehow? Thanks in advance!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T18:07:40.823",
"Id": "506700",
"Score": "0",
"body": "After implementing the suggested changes, how would I go about getting the new version reviewed? Do I post a new question or edit this one?"
}
] |
[
{
"body": "<p>There's no include guards in the header. You'll want to fix that immediately.</p>\n<blockquote>\n<pre><code>#define BYTESZE sizeof(char)\n</code></pre>\n</blockquote>\n<p>That's a pretty pointless definition, since <code>sizeof</code> yields the number of <code>char</code> needed for its argument, meaning <code>sizeof (char)</code> is 1 by definition.</p>\n<blockquote>\n<pre><code>uint readU4L(FILE* file) {\n</code></pre>\n</blockquote>\n<p><code>FILE</code> isn't defined - looks like you're missing an include of <code><stdio.h></code> from this header.</p>\n<blockquote>\n<pre><code> fread(buf, BYTESZE, 4, file);\n</code></pre>\n</blockquote>\n<p>Why are we ignoring the return value from <code>fread()</code>? If it's not successful, we'll have unitialised values in buf, meaning our program has undefined behaviour.</p>\n<blockquote>\n<pre><code> return buf[3] << 24 | buf[2] << 16 | buf[1] << 8 | buf[0];\n</code></pre>\n</blockquote>\n<p>There's a subtle type conversion problem here. The <code>unsigned char</code> values from <code>buf</code> get promoted to <code>int</code> for the arithmetic, but then converted to <code>unsigned int</code> for the return value. I think we actually want to treat them as unsigned values throughout, so we should convert them to <code>unsigned int</code> before the arithmetic.</p>\n<p>Note also that <code><< 24</code> may be outside the valid range of <code>int</code>. Perhaps consider using <code>uint32_t</code> for this value? (Include <code><stdint.h></code> to define it).</p>\n<blockquote>\n<pre><code>int seekToEntry(BIGFile* bigfile, char* path);\n</code></pre>\n</blockquote>\n<p>Do we need to be able to write to <code>*path</code>? Judging from the name, that should be an input, and passed as <code>const char*</code>.</p>\n<blockquote>\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include "Utils.h"\n#include "BIGFile.h"\n</code></pre>\n</blockquote>\n<p>It's best to make <code>"BIGFile.h"</code> the first thing that you include from <code>BIGFile.c</code> - that helps spot problems such as the missing include noted earlier.</p>\n<p><code><string.h></code> is included but not needed.</p>\n<blockquote>\n<pre><code> BIGFile* bigfile = malloc(sizeof(BIGFile));\n</code></pre>\n</blockquote>\n<p>What do we do if <code>bigfile</code> is a null pointer? It seems we go ahead and use it anyway (more Undefined Behaviour).</p>\n<p>A good habit is to apply <code>sizeof</code> to the destination rather than its type; this aids readers when the declaration is far away. For example, in the following case it's much more obviously a correct match:</p>\n<pre><code>bigfile = malloc(sizeof *bigfile);\n</code></pre>\n<blockquote>\n<pre><code>fopen_s(&(bigfile->read), fpath, "rb");\n</code></pre>\n</blockquote>\n<p>What's the point of using Annex K <code>fopen_s()</code> function if we just ignore the return value? Also, I don't see where we check that <code>__STDC_LIB_EXT1__</code> is defined nor where we set <code>__STDC_WANT_LIB_EXT1__</code> to ensure that the function is provided. It seems we'd be better off using plain old <code>fopen()</code> and checking for a null pointer in the normal way.</p>\n<blockquote>\n<pre><code>if (!bigfile->read) {\n printf("Can't open file.\\n");\n return 0;\n}\n</code></pre>\n</blockquote>\n<p>At last, we see some error checking. There's a couple of things wrong here:</p>\n<ol>\n<li>We're writing to <code>stdout</code> instead of <code>stderr</code>.</li>\n<li>We neglected to <code>free()</code> the memory we (possibly) allocated with <code>malloc()</code>, giving a memory leak.</li>\n</ol>\n<blockquote>\n<pre><code>fread(bigfile->magic, BYTESZE, BIG_MAGIC_LEN, bigfile->read);\n</code></pre>\n</blockquote>\n<p>Again, there's no check that we successfully read as much as we wanted here. And shouldn't we be checking that the file magic matches the expected value, so we don't attempt to parse files not in our expected format?</p>\n<blockquote>\n<pre><code>fseek(bigfile->read, bigfile->offset, SEEK_SET);\n</code></pre>\n</blockquote>\n<p><code>fseek()</code> can fail too, you know - there's nothing to say at this stage that we're not reading from a pipe, for example.</p>\n<blockquote>\n<pre><code>byte buf[256];\n\nwhile (fread(buf, BYTESZE, 256, bigfile->read)) {\n</code></pre>\n</blockquote>\n<p>Instead of writing that magic number twice (and risking missing one when modifying it), we can automatically use the available size: <code>fread(buf, 1, sizeof buf, bigfile->read)</code>. Again, we're ignoring the vitally-important return value.</p>\n<blockquote>\n<pre><code> while (path[pos]==buf[pos]) {\n pos++;\n</code></pre>\n</blockquote>\n<p>It looks like we're doing some kind of <code>strcmp()</code> here - why not use the standard function? It certainly looks wrong that we don't initialize <code>pos</code> to 0 before starting this comparison - if that's really intended, it warrants a comment to warn readers.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T18:06:41.663",
"Id": "506699",
"Score": "0",
"body": "Thanks! I changed `sizeof(char)` to `1` shortly after posting. \nHow would I do the conversion correctly? Is `(uint) buf[3] << 24 | (uint) buf[2] << 16 | (uint) buf[1] << 8 | (uint) buf[0];` better?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T19:59:47.253",
"Id": "506704",
"Score": "0",
"body": "That looks correct. There might be a more eloquent way to write it, but can't think immediately what that might be."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T12:51:30.373",
"Id": "256503",
"ParentId": "256499",
"Score": "2"
}
},
{
"body": "<p>Overall, your coding style is pretty clean, but here are some improvement suggestions to make the code more robust and portable, as well as safer:</p>\n<h2>Use fixed sized integers</h2>\n<p>In C, <code>sizeof(char)</code> is guaranteed to be 1 by the standard, but <code>sizeof(unsigned int)</code> is not guaranteed to be 4.</p>\n<p>Fortunately, C99 introduces <a href=\"https://en.cppreference.com/w/c/types/integer\" rel=\"nofollow noreferrer\">fixed size integers</a> such as <code>uint32_t</code> that is guaranteed to be 32 bit (4 bytes) defined in stdint.h.<br />\nSince you are using non standard <code>fopen_s</code> I assume you are not required to stick to ANSI C.</p>\n<h2>Add error checking</h2>\n<p>In the code you posted, you never check the return value of your file read operations or memory allocation operations.</p>\n<p>You also never check the sanity of the data you read.</p>\n<p>For a library, robust error handling is important, so you should always check if read operations success, and if data such as entry sizes or offsets are reasonable - match expected size / do not go past end of file.</p>\n<p>On error, you should return one of several error codes you define for you library and list in documentation.</p>\n<h2>Reduce disk operations</h2>\n<p>You will probably not feel this in your testing, both due to modern hardware, small file size, and multiple caches on different levels, but your <code>seekToEntry</code> function is inefficient due to many back and forward disk operations (both seek and read).</p>\n<p>There are two approaches here, which you can choose depending on how you want to trade memory for speed, and how would your library be used:</p>\n<ol>\n<li><p>Preload the entire "catalog" of file entries in to array of structures in memory and search that when you need to find entry position in file.<br />\nSince your entries are guaranteed to be sorted, you may want to implement a more efficient search, maybe arrange them in a tree by prefix.</p>\n</li>\n<li><p>Since every entry has fixed size, read at least the current entry completely in to a structure.<br />\nIf you don't want to load them all to memory in advance, at least load all data (name, size, offset) for each entry as you iterate, and save your self a bunch of <code>seek</code> operations.</p>\n</li>\n</ol>\n<p>Either approach will also give you the opportunity to create a documented structure for "entry" of this archive file, which will be good for you and your library users.</p>\n<h2>Create a name space</h2>\n<p>Since this is a library, it may be used in a big project with other libraries or many functions defined in the project it self.</p>\n<p>You want to avoid name collision for your functions, structures, and defines.</p>\n<p>Though C does not support special syntax for namespces, one convention for libraries is to use a fixed and consistent prefix to names followed by an underscore.</p>\n<p>If your library is for handling "Big File Archive" you could prefix all your names with BFA_ like so: <code>BFA_loadFile</code>, <code>BFA_seekToEntry</code>.</p>\n<h2>Avoid non-standard functions</h2>\n<p>While MS may claim <code>fopen_s</code> is more secure, it is also non-standard, so if you or one of your library users ever switches compiler or OS, your library will no longer work.</p>\n<p>You should use C standard <code>fopen</code> instead and just add proper error checking as specified above.</p>\n<p>Also, there is no reason to reimplement <code>strncmp</code> as you do with your loops.<br />\nUnlike <code>strcmp</code> which is not safe if the string is not guaranteed to be null terminated, <code>strncmp</code> is perfectly safe for your use case where maximum length is known in advance.</p>\n<h2>Use consistent interface</h2>\n<p>It is hard to tell with only two functions, but you seem to have some difference in how your library functions work:</p>\n<p>One returns an "object" (the <code>BIGFile</code> structure), another returns error / success codes instead.</p>\n<p>While this is technically valid approach, it would be more consistent and comfortable for the user to have a unified interface where all functions would return the same thing - error codes.\nIf a function must also return a value for the user, such as a pointer to a structure, it should return it using one of the parameters.</p>\n<p>Your open function could look like this:</p>\n<pre><code>/**\n * Opens an archive file and loads its header\n *\n * @param fpath path to the archive file\n * @param header place to return loaded header data if the file is successfully loaded (structure will be allocated by the function)\n * @return success / error status code\n */\nint BFA_loadFile(char *fpath, BFA_FileHeader **header) {\n ...\n}\n</code></pre>\n<p>Here, I also included one common method of documenting functions in libraries which can be used with automated tools such as <a href=\"https://www.doxygen.nl/index.html\" rel=\"nofollow noreferrer\">doxygen</a> to produce documentation files in HTML and other formats.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T17:55:53.347",
"Id": "506698",
"Score": "0",
"body": "Thanks for your time! I'm not sure what you mean with the fixed size ints, I did change the `sizeof(char)` to just `1` though. I'm also not sure how I would go about reducing disk operations. Keeping a >1000 entry catalogue in memory seems a bit suboptimal, but how would I get the data from the 256+12 byte long blob? About the interface, that's consistent with the rest of the library. Is it acceptable for `load_BIGFile` to set the `errno` or is it enough to just return `NULL` on failure? I could also add a `BIGFile*` arg and return a status code, but that seems a bit weird to me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T19:11:58.630",
"Id": "506701",
"Score": "0",
"body": "@mindoverflow 1. In C, `int` is not guaranteed to be 4 bytes, but `uint32_t` is guaranteed to be 32 bits which is 4 bytes. That is what I mean by \"fixed size\". 2. By modern standard 260K of memory (which is roughly what you need for 1000 entries) is nothing, and is much better than doing 2 - 3 seek operations for every entry. But, if it is still too much for you, at leas read the whole entry before checking, instead of reading the name than going back to read size / offset it it matches. Coding is always a trade off, and with today's hardware, trading RAM for speed can be good!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T19:16:52.690",
"Id": "506702",
"Score": "0",
"body": "@mindoverflow 3. It is up to you how detailed the error reporting of your library should be. You can just return NULL on error, or you can choose to help the user of the library and try to give them more info on why it failed via `errno`. To decide, ask your self one simple question: Would knowing why the function failed help the library user to fix the issue?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T20:01:45.123",
"Id": "506705",
"Score": "0",
"body": "Strictly speaking, `uint32_t` is only guaranteed to be 32 bits _if it is defined_. And it's certainly not guaranteed to be 4 bytes (= chars)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T20:42:01.847",
"Id": "506711",
"Score": "0",
"body": "@TobySpeight in the OP's case, he is using these vars to read binary values form a file, so we are talking bytes as general term not chars (or some `BYTE` style def). And as far as I know, byte today is always defined as 8 bits. For 'chars', it seems they may be larger, but not less then 8 bits, and that is super rare: https://stackoverflow.com/questions/5516044/system-where-1-byte-8-bit https://stackoverflow.com/questions/2098149/what-platforms-have-something-other-than-8-bit-char If I am missing something, I would be glad to read some reference on this (C and sizes can be problematic)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T21:06:46.533",
"Id": "506713",
"Score": "0",
"body": "No, the term \"byte\" is defined to be the same size as a `char` in section 3.6. So a byte is 8 bits if (and only if) `CHAR_BIT` is 8. It may be wider. (9-bit `char` is less common than it once was; 16-bit `char` has increased lately)."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T13:18:07.233",
"Id": "256504",
"ParentId": "256499",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T09:54:01.803",
"Id": "256499",
"Score": "0",
"Tags": [
"c",
"library"
],
"Title": "Simple library for an undocumented archive format"
}
|
256499
|
<p>This is one of my first attempts at querying the WordPress database for data, and some my first PHP code ever, so please bear that in mind when commenting.</p>
<p>It is supposed find data between two dates, and show it as HTML in a <code>for each</code> loop. How can this be made better? What is the correct way to query a WordPress database?</p>
<pre><code><?php
require_once('wp-load.php');
$sd = date('Y-m-d', strtotime(($startdate = filter_input(INPUT_GET, 'startdate'))));
$ed = date('Y-m-d', strtotime(($enddate = filter_input(INPUT_GET, 'enddate'))));
$query = $wpdb->prepare("SELECT FirstName, LastName, FROM WHEN HireDate BETWEEN '%s' and '%s'" $sd, $ed);
echo $query;
$results = $wpdb->get_results( $query );
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T12:13:50.653",
"Id": "506434",
"Score": "0",
"body": "Welcome to the Code Review Community. It isn't quite clear what you are trying to improve, security, performance. We also do better reviews when there is more code. How do you process the results once you get them?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T12:53:08.613",
"Id": "506437",
"Score": "0",
"body": "I'm still learning PHP, and well, I realize this is bad code. I am looking for feedback as to how one accesses the wordpress database in general? Do you use the WPDB functions? Something else?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T01:53:44.173",
"Id": "506468",
"Score": "0",
"body": "I don't WP but this seems topical: http://ottodestruct.com/blog/2010/dont-include-wp-load-please/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T09:34:18.707",
"Id": "506548",
"Score": "0",
"body": "Why do you think it's a bad code? I am not a WP pro, but this code looks good from performance and security points of view. If you don't need WP but only need to access a database then there is no such a separate entity as a \"wordpress database\" and so there are no special tools either - you can use *any* tool available, from mysqli to Doctrine."
}
] |
[
{
"body": "<p>If you're working with a custom table you have within your database, which you use for WP, then using <code>$wpdb</code> is the way to go. Just remember to use <code>prepare</code>, if there's any user submitted stuff included in the query.</p>\n<p>If on the other the data is stored as posts (with custom post type) with associated post meta, then <code>WP_Query</code> with <code>meta_query</code> argument is more appropriate way to find the data. (It uses <code>$wpdb</code> in the end, but is the more typical way to query posts).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T22:37:35.043",
"Id": "259965",
"ParentId": "256501",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T11:59:15.403",
"Id": "256501",
"Score": "3",
"Tags": [
"php",
"html",
"mysql",
"wordpress"
],
"Title": "Query WordPress database, returning an array of rows"
}
|
256501
|
<p>I've solved LC medium problem, set zeros. Below code is accepted and all test cases were passing. But my code came in the last 10% of accepted answers wrt performance. Can someone help me identify optimization opportunities? This is in C# and memory footprint is fine.</p>
<pre><code>public class Solution {
public void SetZeroes(int[][] matrix) {
bool zeroRow = false;
bool zeroCol = false;
for (int i = 0;i<matrix.Length;++i)
{
for (int j = 0; j < matrix[0].Length; ++j)
{
if (matrix[i][j] == 0)
{
if (i == 0)
zeroRow = true;
if (j == 0)
zeroCol = true;
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
for (int i = 1; i < matrix.Length; ++i)
{
for (int j = 1; j < matrix[0].Length; ++j)
{
if (matrix[i][0] == 0 || matrix[0][j] == 0)
{
matrix[i][j] = 0;
}
}
}
Console.Write('[');
for (int i = 0; i < matrix.Length; i++)
{
if (zeroCol) { matrix[i][0] = 0; }
Console.Write('[');
for (int j = 0; j < matrix[0].Length; j++)
{
if (zeroRow) { matrix[0][j] = 0; }
Console.Write(matrix[i][j]);
if(j!=matrix[0].Length-1)
Console.Write(',');
}
Console.Write("]");
if (i != matrix.Length-1)
Console.Write(',');
}
Console.Write(']');
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T17:44:51.520",
"Id": "506448",
"Score": "0",
"body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. I'm afraid \"set zeros\" means pretty much nothing as a program requirement - can you be more specific? Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T21:35:46.510",
"Id": "506459",
"Score": "2",
"body": "Are you talking about the following problem? https://leetcode.com/problems/set-matrix-zeroes/ if so, it looks like the matrix should be updated in memory so I am not sure why you need the Console.Write (that might affect performance)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T05:29:39.317",
"Id": "506470",
"Score": "0",
"body": "@YumeiDeArmas i think you might be right, let me try."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T06:53:24.177",
"Id": "506479",
"Score": "0",
"body": "@YumeiDeArmas That is the problem, thank you."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T15:30:56.930",
"Id": "256508",
"Score": "0",
"Tags": [
"c#",
"performance",
"algorithm"
],
"Title": "LC medium, matrix set zeros, accepted answer but not top"
}
|
256508
|
<p>I am working on a simple CRUD app as a personal project using Flask. I am currently working on the user blueprint and trying to use as less as libraries as I could and no ORM (for learning purposes). On my blueprints, I have multiple folders including a <code>user</code> folder. I wrote 2 classes in <code>blueprints/user/models.py</code>:</p>
<p><code>User</code>: represent a User entity</p>
<p><code>UserService</code> : register and login (login is not present yet)</p>
<ul>
<li><p>Does it make sense to have2 separate classes? I am actually thinking to move all of my User methods to the <code>UserService</code> class and just have a <code>UserService</code> class with setters and getters.</p>
</li>
<li><p>I am confused about is where and when to interact with the database. Should I do it directly on my <code>route.py</code> vs create a new class?</p>
</li>
</ul>
<p>For instance, to add a new <code>User</code> to the database, my SQL should look more or less like this:</p>
<pre><code>sql = "INSERT INTO users (email, password) VALUES (%s, %s)"
cursor = conn.cursor()
cursor.execute(sql, (email, password))
cursor.fetchall()
conn.commit()
</code></pre>
<p><strong>blueprints/user/models.py</strong></p>
<pre><code>class UserService():
def register_user(self,
email,
password,
registration_date,
active,
sign_in_count,
current_sign_in_on,
last_sign_in_on):
new_user = User(email, password, registration_date, active, sign_in_count, current_sign_in_on, last_sign_in_on)
return new_user.__str__()
class User():
def __init__(self, email, password, registration_date, active, sign_in_count, current_sign_in_on, last_sign_in_on ):
self.email = email
self.password = password
self.registration_date = registration_date
self.active = active
# Activity tracking
self.sign_in_count = sign_in_count
self.current_sign_in_on = current_sign_in_on
self.last_sign_in_on = last_sign_in_on
def desactivate_user(self):
if self.active == False:
print(f"User {self.email} is already inactive")
self.active = False
def reactive_user(self):
if self.active == True:
print(f"User {self.email} is already active")
self.active = True
def is_active(self):
return self.active
def update_activity_tracking(self, ip_address):
self.sign_in_count += 1
self.last_sign_in_on = self.current_sign_in_on
self.current_sign_in_on = datetime.datetime.now()
def update_password(self, new_password):
self.password = get_hashed_password(new_password)
def __str__(self):
user_attributes = vars(self)
return (', '.join("%s: %s" % item for item in user_attributes.items()))
</code></pre>
<p><strong>blueprints/user/views.py</strong></p>
<pre><code>from flask import Blueprint, render_template, request, jsonify
from prepsmarter.extensions import conn #database connection variable
user = Blueprint('user', __name__, template_folder='templates')
@user.route('/register')
def login():
return render_template('register.html')
@user.route('/new-user',methods = ['POST'])
def register_user():
# where I am going to register a new user
</code></pre>
<p><strong>extensions/Database.py</strong></p>
<pre><code>import pymysql
class Database:
instance = None
def __init__(self, host, user, password, db):
self.host = host
self.user = user
self. password = password
self.db = db
def connect(self):
try:
conn = pymysql.connect(
host = self.host,
user = self.user,
passwd = self.password,
db = self.db
)
return conn
except Exception as e:
print(e)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T14:53:15.420",
"Id": "506511",
"Score": "0",
"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)*. Please consider asking a new question instead. Feel free to add links in both questions towards another."
}
] |
[
{
"body": "<p>In general, your code seems to be in pretty good shape if you're hoping to move towards domain driven design, notably seen from your "entity-like" User object and the UserService.</p>\n<blockquote>\n<p>Does it make sense to have2 separate classes? I am actually thinking to move all of my User methods to the UserService class and just have a UserService class with setters and getters.</p>\n</blockquote>\n<p>First off, if you're anticipating your application to grow, a clear separation of concerns is what you'd want to achieve and to further achieve this, the two objects you have are fine. That is, one to represent a definition of what a <em>user</em> is and another to determine what you can do with a user object or related objects which in this case is the <code>UserService</code>. This naturally means that the methods on the <code>User</code> class should now be part of the <code>UserService</code>, considering them business logic of the application. I would use the words <strong>model</strong> to describe the <code>User</code> class and <strong>service</strong> to describe the <code>UserService</code> to define the <strong>types</strong> of components for the application.</p>\n<blockquote>\n<p>I am confused about is where and when to interact with the database. Should I do it directly on my route.py vs create a new class?</p>\n</blockquote>\n<p>One thing that you can also consider from domain driven design is also to include a <strong>repository</strong> object when your application becomes large enough. Repositories typically carry operations that might interact with a database, replacing what may be seen like an ORM that you have mentioned. Otherwise, if you're still small and nimble and don't have too many complex relationships in your database, you can keep it simple and keep the database queries in your model for simplicity for the time being. Both allows the user to be created from anywhere if needed and enables code re-use more than including them in the route. Designing from an interface perspective consider the following.</p>\n<pre class=\"lang-py prettyprint-override\"><code>user_repository = UserRepository(db_conn)\nuser_service = UserService()\nfoo_user = user_service.register_user(...)\n\n// using the repository\nrepository.save(foo_user)\n\n// using the model\nfoo_user.save()\n</code></pre>\n<p>I'll end this with, it depends how large your application is growing, the larger it is, the more you want to re-evaluate your design so to better organize groups of functionality to better extend from and if possible re-use code. That said, what you may have could be good in the long run if your application doesn't really grow beyond those needs.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T10:51:39.280",
"Id": "506491",
"Score": "0",
"body": "Thank you Will, this is a really great answer! I just moved all of my methods from the `User` to the `UserService` class. Since all of those methods require a `User` object, do I need to pass a `User` object in the `UserService` constructor or just have a `User` argument for each`UserService` methods?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T11:00:55.457",
"Id": "506493",
"Score": "0",
"body": "I just figured out that in the constructor won't be possible since I do have a `register_user`method in the `UserService`class now and the goal of this method is actually to create a user."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T11:09:45.877",
"Id": "506494",
"Score": "0",
"body": "I just updatd my post with the updated and new code :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T04:14:28.540",
"Id": "506542",
"Score": "0",
"body": "@Pierre-Alexandre Generally, the `UserService` is on the business logic layer which generally means, it won't take a single `user` object as the constructor of the `UserService`. Rather, all the methods on the `UserService` instance probably takes a user object or creates a user object, for cases like updating, reference to be used in conjunction for other business logic. Let me know if that helps."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T18:54:16.067",
"Id": "506936",
"Score": "0",
"body": "Yes, I did follow your suggestions and it's working"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T22:02:06.170",
"Id": "256518",
"ParentId": "256512",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "256518",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T16:44:48.270",
"Id": "256512",
"Score": "3",
"Tags": [
"python",
"object-oriented",
"flask"
],
"Title": "Python OOP - Web App (Flask) - User registration class?"
}
|
256512
|
<p>The comments in the code kind of explain it. Backspace characters only move cursor back and don't erase output so I need to overwrite them with <code>' '</code> to delete them.</p>
<pre><code>#include <iostream>
#include <string>
using namespace std;
const string PASSWORD = "PASSWORD";
int main(int argc, char** argv) {
string userkey = "";
char c;
int keystrokes = 0;
cout<<"Enter passkey: ";
while(true){
if(_kbhit()){
c=_getche();
if(c=='\r'){//check if user hit enter, _getche() records enter as \r
cout<<'\n';
break;
}
else if(c =='\b'){//check if user typed backslash, overwrite character there
cout<<' ';
if(keystrokes==1){ //makes sure userkey is cleared
userkey = "";
keystrokes--;
cout<<'\b';
}
else if(keystrokes!=0){
userkey = userkey.substr(0,userkey.length()-1);//cuts out last char of userkey
keystrokes--;
cout<<'\b';
}
}
else if (c!='\b'){
cout<<"\b*";//replaces enter char with'*'
keystrokes++;
userkey+=c;
}
}
}
//cout<<userkey;
if (userkey!=PASSWORD)
return 0;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T23:01:39.607",
"Id": "506463",
"Score": "0",
"body": "Do you understand that a hardcoded password gives very little security? Anyone can simply open the executable in Notepad and _see_ the password, as it will be a part of the binary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T16:19:40.533",
"Id": "506516",
"Score": "0",
"body": "I don't see where you defined those functions `_kbhit()` and `_getche()`, since you don't present them here, and don't have any includes for them. But note that identifiers beginning with `_` are *reserved for the implementation*, so you should be using more portable names."
}
] |
[
{
"body": "<p>Regarding your program's efficiency, remember that premature optimisation is the root of all evil. Looking at your program, I can tell that your program will be IO bound - meaning that the computer will spend longer waiting for the user to input the data than actually executing your program. Moreover, functions like <code>std::cout</code> which deal with output, include inevitable slow system calls, which will be far costly in time than your algorithm. So performance should not be a concern here ! :)</p>\n<p>The only thing I would say about your program efficiency is <code>const string PASSWORD = "PASSWORD";</code> which will use unnecessary copying and heap allocation. It is better to preserve the original type of the string like so:</p>\n<p><code>const auto PASSWORD = "PASSWORD";</code> (Here <code>auto</code> (assuming c++11) deduces the type for you, but the real type of the string is <code>const char*</code> if you want to know)</p>\n<p><strong>CODE REVIEW</strong></p>\n<p>These are the style/ readability points I would make on your code.</p>\n<ul>\n<li>Use proper indentation (this might due to copy pasting on codereview so I don't blame you for that)</li>\n<li>Do not use <code>using namespace std</code> - this will lead to naming collisions and all sort of horrible errors. Better to use the <code>std::</code> every-time instead.</li>\n<li>You might consider to put the variable <code>PASSWORD</code> inside <code>main</code> as a <code>static const</code> variable, this will limit the visibility of <code>PASSWORD</code>.</li>\n<li>Use a better variable name than <code>c</code>.</li>\n<li>If your program gets bigger, consider wrapping your algorithm inside a function, this might help to make the <code>main</code> function a bit neater.</li>\n</ul>\n<p>That's all! Well done, I would say generally this is very well written, readable c++ code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T18:41:51.337",
"Id": "506450",
"Score": "0",
"body": "Thank you! I'm new to C++ and this was very encouraging. Thanks for all of the suggestions, I'll change the variable name and definitely move this into a function, it's part of an encryption/decryption program. Would you say that using a break statement here is a good idea, or is there a better way to write the loop?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T19:07:36.447",
"Id": "506451",
"Score": "0",
"body": "I think the break is fine. An alternative would be to do something like do... while (c != '\\r') , but personally I prefer the break."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T18:28:28.297",
"Id": "256514",
"ParentId": "256513",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "256514",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T17:29:39.037",
"Id": "256513",
"Score": "3",
"Tags": [
"c++"
],
"Title": "How can I make this C++ code to obtain passwords more efficient?"
}
|
256513
|
<p>I have created this DI container class lib to be used to in any other external project as a learning exercise.</p>
<p>Please review, and suggest any improvements or comments you have.</p>
<pre><code>import { IContainer, ServiceDefDep } from './container.interface';
export class Container implements IContainer {
private _services: Map<string, ServiceDefDep>
constructor() {
this._services = new Map()
}
/**
* @usage it gets called by the decorator @inject
* to get a singleton instance of the dependency to be returned
*/
public get<T>(name: string): T {
return this._get(name);
}
/**
* @usage it gets called by the decorator @injectable
* to register any class annotated by the @injectable decorator.
*/
public register(
name: string,
definition: {},
dependencies: Array<string> = []
) {
try {
if (!this._isValidName(name))
throw new Error(`Invalid dependency name provided to register`)
if (!this._isValidDefinition(definition))
throw new Error(`Invalid dependency definition provided`)
if (!Array.isArray(dependencies))
throw new Error(`Dependencies need to be supplied as array`)
return this._services.set(name, {
definition: definition,
dependencies: dependencies,
})
} catch (e) {
throw new Error(`Unable to register dependency ${e}`)
}
}
private _get<T>(name: string): T {
try {
if (!this._isValidName(name))
throw new Error(`Invalid dependency name provided to fetch`)
let service: any = this._services.get(name)
if (this._isValidDefinition(service.definition)) {
console.log('heee ', typeof this._createSingleton(service), this._createSingleton(service));
return this._createSingleton(service)
}
} catch (e) {
throw new Error(`Unable to create dependency instance ${e}`)
}
}
private _fetchDependencies(dependencies: Array<string>) {
try {
return dependencies.map((name) => this._get(name))
} catch (e) {
throw new Error(`_resolvedDependencies ${e}`)
}
}
private _createSingleton(service: any) {
try {
return new service.definition(
...this._fetchDependencies(service.dependencies)
)
} catch (e) {
throw new Error(`_createSingleton ${e}`)
}
}
private _isValidName(name: string) {
if (typeof name !== 'string' || name.length === 0) return false
return true
}
private _isValidDefinition(definition: {}) {
return typeof definition !== 'object'
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T00:20:26.803",
"Id": "506466",
"Score": "0",
"body": "[Edit] the question to include an appropriate language tag. The title should state what your code does (see [ask]), and you shouldn't assume everybody knows what \"DI\" is."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-27T23:09:31.593",
"Id": "256520",
"Score": "0",
"Tags": [
"design-patterns",
"library"
],
"Title": "DI container class"
}
|
256520
|
<p>a rust exercise in initalizing a 12x12 array based on the algorithm for twelve tone matrix described here: <a href="https://www.instructables.com/Create-a-Twelve-Tone-melody-with-a-Twelve-Tone-Mat/" rel="nofollow noreferrer">https://www.instructables.com/Create-a-Twelve-Tone-melody-with-a-Twelve-Tone-Mat/</a></p>
<p>i copy pasted description from there into a comment but the post has pictures which may help you understand.</p>
<p>the code doesn't actually do anything beyond initializing the array so i'm left with looking for ideas on how this would be implemented in idiomatic rust. i was also hoping for something readable but still efficient and that creates a read only block of data. suggestions there would be welcome, i'm still new at this.</p>
<p>i saw multiple crates for initializing an array described here: <a href="https://www.joshmcguigan.com/blog/array-initialization-rust/" rel="nofollow noreferrer">https://www.joshmcguigan.com/blog/array-initialization-rust/</a>
but i had trouble figuring out how to use an algorithm to initialize the array rather than some examples of repeated data or random numbers.</p>
<p>also i didn't like how i needed to special case row 0 with an if statement, which needs to be seeded by the user. the rest of the matrix depends on the values in that seed row. i would've liked to have used prior data in the matrix itself to build up the rest of the matrix, like in a dynamic programming sort of way. so i would've liked to have set the first 12 values, then set the next rows based on that row and some other prior values initialized.</p>
<p>i filled in the data by column because that was easier for me to follow the algorithm in the post but i think the initialization could also be done via row if you believe that is necessary for a more idiomatic solution but we'd need to access 3 prior values: up and to the left, up, and to the left i think in the matrix (i didn't try that to check and was worried i might make a mistake that way).</p>
<p>i didn't put much thought into selecting the Array2D crate. i googled and the column wise initialization with a function seemed to fit the algorithm. maybe there is a better crate.</p>
<p>i think using this crate this way results in multiple assignments and clones in memory. i would've preferred just setting each element once in a read only matrix as it is calculated but in a column wise order. however, the readme of the crate suggested using a vector of vectors might be less efficient. i believe underneath the Array2D uses a single vector.</p>
<pre><code>use array2d::Array2D;
/*
This Instructable demonstrates the procedure for composing twelve-tone melodies using a twelve-tone matrix.
This technique was developed by Arnold Schoenberg in 1921, and its purpose is to compose music in which each of the twelve pitches are heard equally. This technique prevents the emphasis of any one note, thereby avoiding any sense of key or tonality.
After learning this technique, you will be able to quickly write melodies for your compositions without emphasizing any particular tonality. With practice, creating a Twelve-Tone matrix is a breeze, taking less than five minutes to complete.
To complete the matrix, you will need to be able to add and subtract numbers between 1 and 12. Writing melodies from this matrix will require a basic understanding of music notation.
Items needed for this task include a 12 by 12 grid (as shown below) and a pen or pencil. To write melodies from the matrix, you will need staff paper or software for writing music.
To hear what this type of music can sound like, follow this link for an example of Schoenberg's twelve-tone music. www.youtube.com/watch
Add TipAsk QuestionCommentDownload
Step 1: Write Numbers in the Top Row
Write each of the whole numbers from 1 through 12 across the top row of the grid such that each number appears exactly once.
The order of the numbers can be either completely arbitrary or carefully planned. The intervals between these numbers will become the number of half-steps between the pitches of your melody. With this knowledge, you can place the numbers in the first row of this matrix at predetermined intervals for musical effect. I have placed numbers in the top row, as shown.
Add TipAsk QuestionCommentDownload
Step 2: Populate the First Column
While the notes in the first row could have been written in any order you chose, the first column depends entirely upon the first row, so you should not select numbers for this column in the same manner as you selected numbers for the first row.
Begin by determining the difference between the first two elements of the top row. In the example below, the difference between the first two elements is -2, since 1 - 3 = -2.
The opposite of the difference between the first two elements of the top row should be the difference between the first two elements of the first column. For example, since the difference between the first two elements of the first row is -2, the difference between the first two elements of the first column should be +2. This is achieved by adding 2 to the first element. Since 3 + 2 = 5, the second element is 5.
Follow the same procedure for each subsequent set of adjacent elements. Continuing with the example below, observe that the difference between 9 and 1 is +8. Therefore, the difference between the second and third elements of the first column should be -8. Subtracting 8 from 5 yields - 3. Note that -3 is not between 1 and 12. Whenever you encounter a result that is not between 1 and 12, add or subtract 12 to that number as needed to make the result between 1 and 12. In this case, -3 + 12 = 9, so a 9 appears as the third element of the first column.
An image of the completed first row and first column of our example also appears below.
Check your work. One way to verify that you have not made any mistakes is to make sure that each whole number from 1 through 12 appears exactly one time in the first column.
Add TipAsk QuestionCommentDownload
Step 3: Fill in the Second Row
Once the first row and column are complete, the cells in the second row can be populated. Like the first column, the remaining cells are dependent upon the first row.
Determine the difference between the first elements of the first and second rows. Continuing with our example, we can see that the difference between the first two elements is 2, since 5 - 3 = 2. Fill in the remaining elements of the second row such that the difference between each second row element and the first row element immediately above it is the same as the difference you have just determined. In the example below, this means that the second element of the second row should be 3, because 1 + 2 = 3, and the third element should be 11, since 9 + 2 = 11.
As in the previous step, if you encounter a number less than 1 or greater than 12, add or subtract 12 as needed so that the number you write in the matrix is in the range from 1 through 12.
An image of the completed second row of our example is shown.
Check your work. Make sure that each number from 1 through 12 appears only once in the row. If this is not the case, then you have made a mistake.
Add TipAsk QuestionCommentDownload
Step 4: Fill in the Remaining Rows
The remaining rows should be completed in the same manner as the second row was populated.
Determine the difference between first element of the lowest row that is not completed and the first element of the row immediately above it. This difference should be replicated throughout the rest of the row. Returning to our example, we can observe that the difference between 9 and 5 is 4, so each element of the third row should be 4 greater than the element in the cell above it.
Each subsequent row of our example has been completed in this manner, and the resulting completed matrix appears below.
You can check your work once again by verifying that each number from 1 through 12 appears only once in each row and each column.
One final way to verify that the matrix is properly completed is to look along the diagonal that runs from the top left corner of the matrix to the bottom right corner. The number in each of these cells should be the same. In our example, this is the case; the number 3 appears in each cell of the diagonal.
Add TipAsk QuestionCommentDownload
Step 5: Translate the Numbers to Pitches
Translate the Numbers to Pitches
Now that the matrix is complete, you can select a few rows or colums and "translate" them into music. Each number corresponds to a specific pitch according to this list.
C 1
C# / Db 2
D 3
D# / Eb 4
E 5
F 6
F# / Gb 7
G 8
G# / Ab 9
A 10
A# / Bb 11
B 12
Select one or more rows or columns from the matrix and translate them to pitches. You can read the rows from left to right or from right to left, and the columns can be read from top to bottom or from bottom to top.
Returning to our example, the seventh row, read from left to right, was chosen for the first half of a melody. The tenth column, read from bottom to top, was chosen for the second half of the melody. The row and column are translated as follows.
Row 7:
10 8 4 12 11 1 3 2 7 5 6 9
A G D# B Bb C D Db Gb E F Ab
Column 10:
11 2 3 1 6 5 7 9 8 4 12 10
Bb C# D C F E Gb Ab G Eb B A
Add TipAsk QuestionCommentDownload
Step 6: Write Music!
Write Music!
Make a melody from the pitches. Make sure that you don't change the orders of the pitches, as changing the order of the pitches defeats the purpose creating the matrix.
Recall that the pitches generated in step 5 were as follows:
A G D# B Bb C D Db Gb E F Ab
Bb C# D C F E Gb Ab G Eb B A
I have completed our example by writing music from these pitches.
Pick your time signature, rhythms, and dynamics in any way you like. Note that using a key signature is not necessary because your melodies were not derived with any sense of key or tonality. 20th Century composers are known for writing specific dynamic, articulation, and tempo markings, so you can imitate this style by specifically spelling out these factors as well. I have done this in the example below.
Your finished melodies will be atonal and consistent with the methodologies employed by Arnold Schoenberg and other 20th Century composers.
*/
fn generate_matrix(seed_row: [i32; 12]) -> Array2D<i32> {
let mut counter = 0;
let mut last = 0;
let next = || {
let row = counter % 12;
let result = if row == 0 {
seed_row[counter / 12]
} else {
(last + seed_row[row - 1] - seed_row[row] + 12) % 12
};
last = result;
counter += 1;
if result == 0 {
12
}
else {
result
}
};
Array2D::filled_by_column_major(next, 12, 12)
}
fn main() {
const SEED_ROW: [i32; 12] = [3, 1, 9, 5, 4, 6, 8, 7, 12, 10, 11, 2];
let matrix: Array2D<i32> = generate_matrix(SEED_ROW);
// sample result [3, 1, 9, 5, 4, 6, 8, 7, 12, 10, 11, 2, 5, 3, 11, 7, 6, 8, 10, 9, 2, 12, 1, 4, 9, 7, 3, 11, 10, 12, 2, 1, 6, 4, 5, 8, 1, 11, 7, 3, 2, 4, 6, 5, 10, 8, 9, 12, 2, 12, 8, 4, 3, 5, 7, 6, 11, 9, 10, 1, 12, 10, 6, 2, 1, 3, 5, 4, 9, 7, 8, 11, 10, 8, 4, 12, 11, 1, 3, 2, 7, 5, 6, 9, 11, 9, 5, 1, 12, 2, 4, 3, 8, 6, 7, 10, 6, 4, 12, 8, 7, 9, 11, 10, 3, 1, 2, 5, 8, 6, 2, 10, 9, 11, 1, 12, 5, 3, 4, 7, 7, 5, 1, 9, 8, 10, 12, 11, 4, 2, 3, 6, 4, 2, 10, 6, 5, 7, 9, 8, 1, 11, 12, 3]
println!("{:?}", matrix)
}
</code></pre>
|
[] |
[
{
"body": "<p>First, I can't comment of the choice of <code>array2d</code> since I'm not familiar with the crate, it may be a good choice, but my recommendation is the <code>ndarray</code> crate.</p>\n<p>You made use of <em><strong>internal iteration</strong></em>. Rust has <em><strong>external iteration</strong></em>, which may be more appropriate for your use. Further information on iteration is available in the answer: <a href=\"https://stackoverflow.com/a/224675/14715117\">https://stackoverflow.com/a/224675/14715117</a></p>\n<p>Since you pass a <code>next</code> function to the constructor, which does internal iteration, your branches are a necessity. With external iteration, we still don't build up data on top of prior data in the matrix itself, "in a dynamic programming sort of way". Still, code after such a change in iteration seems more readable to me, and certainly more idiomatic, and I hope it looks as such to you too.</p>\n<p>Keep in mind that Rust forbids uninitialized data, or rather allows it only as an unsafe possibility. Still, we can initialize cells with <code>0</code>. You may be able to solve the task in two steps. First step initializes the first row with <code>seed_row</code> and all other cells with <code>0</code>. Second step fills these other cells:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>for row in 1 .. 12 {\n for col in 0 .. 12 {\n // initialize array[(col, row)] ...\n }\n}\n</code></pre>\n<hr />\n<p>Nitpick: there is <code>(x + 12) % 12</code> in the code, which may be replaced by <code>x.rem_euclid(12)</code> as a solution that does the same thing in one operation, not two.</p>\n<hr />\n<p>The following code is my take on the problem. It provides an external-iterator-based solution for both array crates.</p>\n<p>Hoping it helps.</p>\n<pre class=\"lang-rust prettyprint-override\"><code>use array2d::Array2D;\nuse ndarray::prelude::*;\nuse std::iter;\n\nfn generate_matrix(seed_row: [i32; 12]) -> Array2D<i32> {\n let mut counter = 0;\n let mut last = 0;\n\n let next = || {\n let row = counter % 12;\n\n let result = if row == 0 {\n seed_row[counter / 12]\n } else {\n (last + seed_row[row - 1] - seed_row[row] + 12) % 12\n };\n\n last = result;\n counter += 1;\n\n if result == 0 {\n 12\n }\n else {\n result\n }\n };\n\n Array2D::filled_by_column_major(next, 12, 12)\n}\n\nfn generate_matrix_from_iter_row_major(seed_row: [i32; 12]) -> Array2D<i32> {\n let iter = seed_row.iter().copied().flat_map(|seed| {\n let first_cell_in_col = iter::once(seed);\n let other_cells_in_col = (1 .. 12).scan(seed, |state, row| {\n *state = (*state + seed_row[row - 1] - seed_row[row]).rem_euclid(12);\n if *state == 0 {\n Some(12)\n } else {\n Some(*state)\n }\n });\n first_cell_in_col.chain(other_cells_in_col)\n });\n\n Array2D::from_iter_column_major(iter, 12, 12)\n}\n\nfn generate_ndarray_matrix(seed_row: [i32; 12]) -> Array2<i32> {\n let content: Vec<_> = seed_row.iter().copied().flat_map(|seed|\n iter::once(seed).chain((1 .. 12).scan(seed, |state, row| {\n *state = (*state + seed_row[row - 1] - seed_row[row]).rem_euclid(12);\n if *state == 0 {\n Some(12)\n } else {\n Some(*state)\n }\n }))\n ).collect();\n Array2::from_shape_vec(\n (12, 12).strides((1, 12)),\n content\n ).unwrap()\n}\n\nfn main() {\n const SEED_ROW: [i32; 12] = [3, 1, 9, 5, 4, 6, 8, 7, 12, 10, 11, 2];\n let matrix: Array2D<i32> = generate_matrix(SEED_ROW);\n let second_matrix: Array2<i32> = generate_ndarray_matrix(SEED_ROW);\n let third_matrix: Array2D<i32> = generate_matrix_from_iter_row_major(SEED_ROW);\n\n println!("{:?}", second_matrix);\n assert_eq!(matrix, third_matrix);\n assert_eq!(second_matrix.into_raw_vec(), third_matrix.as_column_major());\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T11:24:06.787",
"Id": "256566",
"ParentId": "256521",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "256566",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T00:26:42.183",
"Id": "256521",
"Score": "1",
"Tags": [
"beginner",
"reinventing-the-wheel",
"rust"
],
"Title": "initialize 2d array using 12 tone algorithm with Rust"
}
|
256521
|
<p>I found out the hard way, when utilizing pandas is better to use <code>pandas.Series</code> than <code>lists</code> data type to manipulate data.
Even if I understood how pandas stores different data types, I did not realize the ramification of using <code>lists</code> of <strong>strings</strong> instead of <code>pandas.Series</code> of <strong>objects</strong>.</p>
<p><a href="https://pbpython.com/pandas_dtypes.html" rel="nofollow noreferrer">Pandas dtype</a></p>
<p><a href="https://i.stack.imgur.com/TBCPa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TBCPa.png" alt="Pandas dtype" /></a></p>
<p>Like the pic above shows, pandas store <strong>strings</strong> as <strong>objects</strong>, it does not discriminate between <strong>strings, lists, dictionaries and etc</strong>, python <a href="https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Iterables.html" rel="nofollow noreferrer">iterable</a>.<br />
I made my own function that returns a <code>pandas.DataFrame</code> column names, columns' pandas dtypes and columns' python data types, see pic below.</p>
<p><a href="https://i.stack.imgur.com/VUEA9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VUEA9.png" alt="enter image description here" /></a></p>
<p>Most <code>pandas.DataFrame</code>s that I encountered have a <code>NaN</code> values representing any values that are undefined.<br />
A <code>pandas.DataFrame</code> column of <em>string objects</em>, first_names for example, can contain <code>NaN</code> values, <code>NaN</code> is a float data type.<br />
The main reason that the <code>NaN</code> value is commonly utilize, it is due to its usefulness, when combine with a function like <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dropna.html" rel="nofollow noreferrer"><code>DataFrame.dropna()</code></a>, it becomes a well recognize and powerful tool for data manipulation.</p>
<p>Most pandas teaching materials utilize <code>lists</code> and <code>pandas.DataFrames</code> to manipulate data, so I did the same, see code below:</p>
<pre><code> # Removes Html code and \n
for name in essay_names:
# Initializes essay text list
<b><i>essay_txts = []</i></b>
for essay in profiles[name]:
# Checks if the essay is empty, NaN
if type(essay) == type(.0):
# Adds NaN text to the essay texts Series, empty text
<b><i>essay_txts.append(np.NaN)</i></b>
else:
essay_clean = re.sub('', '', essay).replace('\n', ' ').replace(' ', ' ')
essay_txts.append(essay_clean)
# Stores cleaned essay text
profiles[f'{name}_text'] = essay_txts
</code></pre>
<p>The code lines <code>essay_txts = []</code> and <code>essay_txts.append(np.NaN)</code> create issues when trying to manipulating the DataFrames data with <code>DataFrame.dropna()</code>, the <code>essay_txts</code> is a <code>list</code> of <em>strings</em>, the <code>np.nan</code> value was not saved in the <code>list</code> as a <code>float</code> but as <em>string</em>, <code>'nan'</code>, and by consequence it was also saved in the <code>DataFrame</code> as a <em>string</em>.<br />
The <code>DataFrame.dropna()</code> function will not recognize the value as <code>NaN float</code> and it will not drop the <code>DataFrame</code> row where the values was inputted.</p>
<p>Replacing the code lines<br />
<code>essay_txts = []</code><br />
<code>essay_txts.append(np.NaN)</code><br />
with<br />
<code>essay_txts = pd.Series(dtype='object')</code><br />
<code>essay_txts = essay_txts.append(pd.Series(np.NaN), ignore_index=True)</code><br />
is my solution to the issues created by using <code>lists</code> and trying to utilize the <code>NaN</code> value to manipulate data with pandas.</p>
<p>See full code below</p>
<pre><code> # Removes Html code and \n
for name in essay_names:
# I use pandas Series, a Series will accept NaN float and object (string) values
<b><i>essay_txts = pd.Series(dtype='object')</i></b>
for essay in profiles[name]:
# Checks if the essay is empty, NaN
if type(essay) == type(.0):
# Adds NaN text to the essay texts Series, empty text
<b><i>essay_txts = essay_txts.append(pd.Series(np.NaN), ignore_index=True)</i></b>
else:
essay_clean = re.sub('', '', essay).replace('\n', ' ').replace(' ', ' ')
<b><i>essay_txts = essay_txts.append(pd.Series(essay_clean), ignore_index=True)</i></b>
# Stores cleaned essay text
profiles[f'{name}_text'] = essay_txts</code></pre>
<p>Thank you for feedback, or for sharing a better way to address the issues created by using <code>lists</code> and trying to utilize the <code>NaN</code> value to manipulate data with pandas.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T09:39:43.503",
"Id": "506484",
"Score": "0",
"body": "Welcome to Code Review, from your question it seems me you are proposing two distinct solutions to the same problem asking for comparison. If this is the scenario, you can add the `comparative-review` tag to your question."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T02:29:12.083",
"Id": "256524",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"comparative-review",
"pandas"
],
"Title": "Asking for feedback, when utilizing Pandas, why is it better to use pandas.Series than lists data type?"
}
|
256524
|
<p>Just wondering how my code looks, consider it a "professors input" since I'm not taking classes this semester. Also I'd like to note that this will soon be transitioning to a database approach where I use a MySQL database to get the <code>InventoryItems</code>.</p>
<p>Inventory.h</p>
<pre><code>#pragma once
#include <vector>
#include <iostream>
#include "InventoryItems.h"
class Inventory
{
public:
Inventory();
~Inventory();
void createNewInventoryItem(std::string itemName = "", unsigned int maxQuantity = 0, unsigned int orderThreshold = 0,
double price = 0.0, int quantityInInventory = 0);
void deleteInventoryItem(int posInVector);
InventoryItems* getItem(int posInVector);
private:
std::vector<InventoryItems*> m_inventory; //NOTE: does not use a smart pointer, instead the pointer is deleted from the heap in the deleteInventoryItem function
// if deleteInventoryItem is not called at the end of the inventory objects life cycle the inventory objects deconstructor will
// loop through all elements in m_inventory and call deleteInventoryItem for each item
};
</code></pre>
<p>Inventory.cpp</p>
<pre><code>#include "Inventory.h"
Inventory::Inventory()
{
std::cout << "Inventory created" << std::endl;
}
Inventory::~Inventory()
{
for (int i = 0; i < m_inventory.size(); i++) {
deleteInventoryItem(i);
}
std::cout << "Inventory destroyed" << std::endl;
}
void Inventory::createNewInventoryItem(std::string itemName, unsigned int maxQuantity, unsigned int orderThreshold,
double price, int quantityInInventory)
{
InventoryItems* newItem = new InventoryItems;
newItem->createInventoryItem(itemName, maxQuantity, orderThreshold, price, quantityInInventory);
m_inventory.emplace_back(newItem);
}
void Inventory::deleteInventoryItem(int posInVector)
{
delete m_inventory.at(posInVector);
m_inventory.erase(m_inventory.begin() + posInVector);
}
InventoryItems* Inventory::getItem(int posInVector)
{
return m_inventory.at(posInVector);
}
</code></pre>
<p>The inventory class will really come into it's own, this is just a proof of concept before I incorporate my database (I.E. <code>inventoryItems</code> is acting as a place holder for the DB and queries, hence me not including it here).</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T09:42:32.483",
"Id": "506486",
"Score": "1",
"body": "(Your lines are too wide. (The reason to set e.g. newspapers in multiple columns is a limit to the eyes successfully jumping to the beginning of the next line. Not much of a problem given automatic text wrapping. More so with code viewers/editor that typically don't, and have a hard time with comment (and code) layout if&where they do.) I dislike horizontal scrolling.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T09:44:29.323",
"Id": "506488",
"Score": "0",
"body": "This looks irritatingly close to *hypothetical code*, please (re-)visit [What topics can I ask about here?](https://codereview.stackexchange.com/help/on-topic)"
}
] |
[
{
"body": "<h2>Overview</h2>\n<p>It's a mistake to be using RAW pointers you should definitely be using some form of smart pointer here.</p>\n<p>It does two things for you:</p>\n<ul>\n<li>It will greatly simplify your code.</li>\n<li>It will remove the bugs !!!</li>\n</ul>\n<hr />\n<p>If you have owned RAW pointers in your class then you <strong>MUST</strong> implement the rule of three. You do (have owned RAW pointers) but your don't (implement the rule of three). As a result your code is broken.</p>\n<pre><code>{\n Inventory a;\n a.createNewInventoryItem("Wine");\n\n Inventory b(a); // You did not implement the copy constructor\n // nor did you disable it, so the default version\n // is generated. So this copy is allowed.\n //\n // Both a and b have a copy of the same RAW pointer\n // internally.\n}\n// b is destoryed (which destroys the pointer)\n// a is destroyed (which also destroys the pointer) but that is UB as\n// it has already been destroyed.\n</code></pre>\n<p>There are several other things that go wrong but you get the drift.</p>\n<p>If you had used <code>std::unique_ptr<></code> this would have prevented the <code>Inventory</code> object from being copied. If you had used <code>std::shared_ptr<></code> copying would have been allowed (not sure if the semantics would be correct).</p>\n<hr />\n<p>I would point out that you only need to store pointers and have dynamic allocation if you have polymorphic types. Otherwise you can simply store the object directly in the container:</p>\n<pre><code>// This will handle most situations.\nstd::vector<InventoryItems> m_items;\n /// ^^^ note: No pointer\n</code></pre>\n<p>You do need pointers for polymorphic types:</p>\n<pre><code>class Animal { /* Stuff */}\nclass Cat: public Animal { /* Stuff */}\nclass Dog: public Animal { /* Stuff */}\n\nstd::vector<Animal*> m_items;\n// Here we need pointers because we may store a Cat or a Dog\n// So the object stored is not an Animal and we don't know how\n// large it is at compiler time.\n</code></pre>\n<hr />\n<p>Interface Design:</p>\n<pre><code>class Inventory\n{\npublic:\n void createNewInventoryItem(/*Stuff*/);\n void deleteInventoryItem(int posInVector);\n InventoryItems* getItem(int posInVector);\n};\n</code></pre>\n<p>Sure you have a create/delete here and a get.</p>\n<p>But when you create an item you don't know where in the container it is. So you can not directly get it back. You could use something about the input parameters that you could reuse (like the item name) or I would expect the <code>create</code> to return some identifier that can be used by the delete and get.</p>\n<p>Alternatively your interface simply displays all the items and then you manipulate it from there. To do this you need to loop over all the items. But how many items do you have to loop over? In this case I would expect the class to provide some way to know the range of items available. It could be a <code>size()</code> method or alternatively you could provide <em>iterators</em> of the class so you know how to loop over the inventory.</p>\n<hr />\n<p>Representation of the Inventory:</p>\n<p>I can create two inventory items that have the same name:</p>\n<pre><code> Inventory a;\n a.createNewInventoryItem("Wine");\n a.createNewInventoryItem("Wine");\n</code></pre>\n<p>There are now two wine items in the inventory. This does not make sense to me. When you add a new item you should check to see if it already exists. If it does then you need to combine the data (or throw an error). You can do this with <code>std::vector</code> but there are other containers that will help you (maybe <code>std::map</code>).</p>\n<h2>Code Review</h2>\n<pre><code> void createNewInventoryItem(std::string itemName = "", unsigned int maxQuantity = 0, unsigned int orderThreshold = 0, double price = 0.0, int quantityInInventory = 0);\n</code></pre>\n<p>You can create an inventory item without specifying anything! If you pass no parameters it still works and you get an item with no name and no value.</p>\n<hr />\n<p>When you create an inventory item it does not return anything. So how do you know what item to delete?</p>\n<pre><code> void deleteInventoryItem(int posInVector);\n</code></pre>\n<p>You can randomly delete items (but there is no understanding of what item will be deleted (unless you get every item first and examine it).</p>\n<p>Personally I would index items by their <code>itemName</code>. I would then allow both <code>getItem()</code> and <code>deleteInventoryItem()</code> to work by passing the name.</p>\n<hr />\n<p>Don't return a pointer from a <code>get()</code>. I would return a reference to the object. Just because you store it as a pointer does not mean you need to expose that fact to the users of your class.</p>\n<pre><code> InventoryItems* getItem(int posInVector);\n</code></pre>\n<hr />\n<p>Don't use <code>std::endl</code> here; prefer to use <code>"\\n"</code> instead.</p>\n<pre><code> std::cout << "Inventory created" << std::endl;\n</code></pre>\n<p>The difference between these two is that <code>std::endl</code> in addition to outputting the newline character it forces the stream to flush. There is no need to flush the stream as this happens automatically when it needs to happen. The problem with forcing a manual flush is that it can be inefficient and cause the application to slow down if there is to many flushes.</p>\n<p>If you look at questions on SO asking why writing to standard output in C++ is so slow the actual solution is simply to stop using <code>std::endl</code> and allow the stream to flush itself (and the code magically speeds up).</p>\n<hr />\n<p>Sure you can loop like this:</p>\n<pre><code> for (int i = 0; i < m_inventory.size(); i++) {\n deleteInventoryItem(i);\n }\n</code></pre>\n<p>But I would note that this is broken because you call <code>deleteInventoryItem()</code> which not only deletes the item but removes it.</p>\n<p>Imagine you have a vector with 4 items.</p>\n<ul>\n<li>You call delete on item 0. This deletes the item and removes it. Thus moving everything in the vector down one item (new length is 3)</li>\n<li>You increment <code>i</code> (i is now 1)</li>\n<li>You call delete on item 1. This deletes the item and removes it. Thus moving everything in the vector down one item (new length is 2)</li>\n<li>you increment <code>i</code> (i is now 2)</li>\n<li>You exit the loop.</li>\n</ul>\n<p>You only deleted two items.</p>\n<p>But a vector is a range. So you can use the range based loop:</p>\n<pre><code> for (auto& item: m_inventory) {\n delete item;\n }\n\n m_inventory.clear();\n</code></pre>\n<hr />\n<p>Why do you have a two phase creation of a <code>InventoryItems</code>?</p>\n<pre><code> InventoryItems* newItem = new InventoryItems;\n newItem->createInventoryItem(itemName, maxQuantity, orderThreshold, price, quantityInInventory);\n</code></pre>\n<p>You should pass all those parameters to the constructor.</p>\n<hr />\n<p>One thing I would add is that you don't know the number of items in the inventory. So you just have to loop over them until you get an exception thrown. It may be worth adding a <code>size()</code> function so you can get the size so you know the limit of the number of items.</p>\n<hr />\n<p>You don't even need to use pointers here. There is no polymorphic objects involved. You should simply have used normal objects in the vector and it would have worked as expected.</p>\n<hr />\n<p>Don't use unsigned integer types. In most situations they will cause you a lot of headaches. If that extra bit is something you need then you are already at the boundary of your system and should upgrade the integer type to the next larger type to get a bunch more bits.</p>\n<p>Save the unsigned integer types for flags.</p>\n<hr />\n<p><strong>Don't</strong> use <code>double</code> for monetary units. Not all values can be represented exactly and you are going to run into rounding errors when you start adding things up.</p>\n<p>Rather use an integer type. If you are using dollars in a double then simply use an integer but store the number of cents.</p>\n<hr />\n<h2>Potential Solution</h2>\n<p>How I would do it:</p>\n<pre><code>#include <map>\n#include <iostream>\n\n#include "InventoryItems.h"\n\nclass Inventory\n{\n using Container = std::map<std::string, InventoryItems>;\npublic:\n Inventory();\n \n void createNewInventoryItem(std::string itemName,\n int maxQuantity = 0,\n int orderThreshold = 0,\n int price = 0,\n int quantityInInventory = 0);\n\n void deleteInventoryItem(std::string const& itemName);\n InventoryItems& getItem(std::string const& itemName);\n\n \n using iterator = typename Container::iterator;\n\n iterator begin() {return m_inventory.begin();}\n iterator end() {return m_inventory.end();}\n\n \n private:\n Container m_inventory;\n};\n\nInventory::Inventory()\n{\n std::cout << "Inventory created" << std::endl;\n}\n\nvoid Inventory::createNewInventoryItem(std::string itemName,\n int maxQuantity,\n int orderThreshold,\n int price,\n int quantityInInventory)\n{\n auto find = m_inventory.find(itemName);\n if (find == itemName.end()) {\n m_inventory.emplace_back(std::piecewise_construct,\n std::forward_as_tuple(itemName),\n std::forward_as_tuple(maxQuantity, orderThreshold, price, quantityInInventory));\n }\n else {\n // I don't know how your inventory works.\n // This is just s guess/suggestion.\n find->second.setMax(std::max(maxQuantity, find->second.getMax());\n find->second.setOrderThreshold(std::max(orderThreshold, find->second.getOrderThreshold());\n find->second.setPrice(price);\n find->second.increaseInventory(quantityInInventory);\n }\n}\n\nvoid Inventory::deleteInventoryItem(std::string const& itemName)\n{\n m_inventory.erase(itemName);\n}\n\nInventoryItems& Inventory::getItem(std::string const& itemName)\n{\n auto find = m_inventory.find(itemName);\n if (find == m_inventory.end()) {\n throw std::outofbound("Or something like that");\n }\n return find.second;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T20:33:57.997",
"Id": "506529",
"Score": "0",
"body": "Wow thank you for the very detailed response! I can see I still have quite a bit to learn and improve on in my programming ability. So the big thing I got from this is that classes should be entirely self contained and (for lack of a better word) self governing? I.e. the class can entirely take care of itself and should not piggy back off of other functions/classes?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T06:12:58.480",
"Id": "256526",
"ParentId": "256525",
"Score": "4"
}
},
{
"body": "<p>In addition to Martin's thorough answer, one small point:</p>\n<p>The header uses <code>std::string</code> but does not include <code><string></code>. Conversely, it includes <code><iostream></code> which it does not use (and which can be moved to the implementation file).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T06:33:10.230",
"Id": "507212",
"Score": "0",
"body": "<string> is included in <iostream>."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T07:36:46.620",
"Id": "507217",
"Score": "0",
"body": "On your platform, perhaps. For portable code, we can't assume that (unless you can point to a section of the standard that states otherwise). As far as I can tell `<iostream>`, is specified to include `<ios>`, `<streambuf>`, `<istream>`, `<ostream>` and no others."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T17:11:13.133",
"Id": "256545",
"ParentId": "256525",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "256526",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T04:36:49.167",
"Id": "256525",
"Score": "0",
"Tags": [
"c++",
"classes"
],
"Title": "Inventory system/management"
}
|
256525
|
<p>I've written an implementation of setjmp and longjmp in MMIX (assuming no name mangling).
I also hand-assembled it.<br />
Are there any mistakes anyone can spot?</p>
<pre><code> // Memory stack pointer is stored in $254.
// jmp_buf is rO, next address after setjmp call, memory stack pointer,
// frame pointer, then possibly other data (for sigsetjmp/siglongjmp).
// rG is preserved over a longjmp call
// (not that it should change over one, anyway)
setjmp IS @
GET $1,rO // FE01000A
STOU $1,$0,0 // AF010000
GET $1,rJ // FE010004
STOU $1,$0,8 // AF010008
STOU $254,$0,16 // AFFE0010
STOU $253,$0,24 // AFFE0018
POP 0,0 // F8000000
longjmp IS @
LDOU $254,$0,0 // 8FFE0000
SAVE $255,0 // FAFF0000
GET $1,rG // FE000013
// why 15? We save 13 special registers, two local registers,
// and the number 2, as well as any global registers.
// That's 256-rG + 16, and we add only 15 because $255 is the address
// of the saved rGA.
SETL $0,271 // E300010F
SUBU $1,$1,$0 // 26010100
SLU $1,$1,3 // 39000003
// now $255 is topmost saved register, $255+$1 is bottommost such,
// $254 is rO after.
SUBU $0,$254,$1 // 2600FE01
LDOU $2,$255,$1 // 8E02FF01
STOU $2,$0,$1 // AE020001
INCL $1,8 // E7010008
PBNZ $1,@-12 // 5B01FFFD
SET $255,$0 // C1FF0000
UNSAVE 0,$255 // FB0000FF
// now we have restored rO, but not other stuff
LDOU $253,$0,24 // 8FFD0018
LDOU $254,$0,16 // 8FFE0010
LDOU $0,$0,8 // 8F000008
PUT rJ,$0 // F6040000
POP 2,0 // F8020000
</code></pre>
<p>The register stack was the hard part here. Everything between the <code>SAVE</code> and the <code>UNSAVE</code> inclusive is essentially just “set register stack pointer properly”; after that it takes no time at all to fix up the other registers and return.</p>
<p>If you have any other questions, I'm happy to explain my reasons for each tetra of that code.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T12:03:06.430",
"Id": "506503",
"Score": "0",
"body": "Welcome to the Code Review Community. Does the code work as expected?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T13:22:24.543",
"Id": "506510",
"Score": "0",
"body": "@pacmaninbw Haven't checked, not having a MMIX interpreter at hand (currently rewriting Knuth's to be faster, using compiler intrinsics/inline assembly and uint64_t instead of structs). But it should. I'm asking if anyone else can see issues."
}
] |
[
{
"body": "<p>Looks like your <code>setjmp</code> takes the <code>jmp_buf</code> parameter as <code>$0</code> - but how is <code>jmp_buf</code> defined - how much space does it need for example?</p>\n<p>Also <code>longjmp</code> takes 2 parameters - the same <code>jmp_buf</code> and an <code>int</code> - I don't see <code>$1</code> being used for the second input parameter in your <code>longjmp</code></p>\n<p>You can find commandline tools to run MMIX programs at <a href=\"https://mmix.cs.hm.edu/exe\" rel=\"nofollow noreferrer\">https://mmix.cs.hm.edu/exe</a> to try out your implementation - there's a Windows GUI debugger too - could you show sample MMIX code that calls your <code>setjmp</code> and <code>longjmp</code>?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T23:43:05.653",
"Id": "513068",
"Score": "0",
"body": "jmp_buf would be octa[5], the last octa of which is used only for sig(set|long)jmp."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T23:46:23.030",
"Id": "513069",
"Score": "0",
"body": "What do you mean by \"I don't see `$1` being used for the second input parameter\"?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T23:50:40.940",
"Id": "513070",
"Score": "0",
"body": "calling `setjmp`: set `$(X+1)` to the address of a `jmp_buf`, then `PUSHJ $X,setjmp` (or arrange for `$Y` to be the address of `setjmp`, then `PUSHGO $X,$Y,0`). The return value appears in `$X`, and locals, `$253`, and `$254` will be unaltered. (As usual, locals `$(X+1)` and up disappear.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T23:55:11.697",
"Id": "513071",
"Score": "0",
"body": "calling `longjmp`: set `$X+1` to the address of a `jmp_buf`, `$X+2` to the return value for the `setjmp` that set it, and `PUSHJ $X,longjmp` (or, again, arrange for `$Y` to contain the address of `longjmp` then `PUSHGO $X,$Y,0`). There will be no return."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T00:31:57.837",
"Id": "513072",
"Score": "0",
"body": "longjmp gets its second parameter in $1 - caller $X+2 - where is $1 used for the return for setjmp?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T00:37:36.687",
"Id": "513074",
"Score": "0",
"body": "Right at the end of `longjmp`: `SET $0,$1; POP 1,0`. Which I will be changing to `POP 2,0` just to be cheap."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T17:47:34.350",
"Id": "513173",
"Score": "0",
"body": "But that assumes UNSAVE has restored $1 - after what looks like edits to the saved context - I don't think this can work or is allowed - SAVE and UNSAVE are mainly meant for the operating system to perform context switching - Knuth does say \"Coroutines might, of course, be sufficiently complicated that they each do require a register stack of their own. In such cases MMIX's SAVE and UNSAVE operations can be used, with care, to save and restore the context needed by each coroutine\" - but I believe the saved state is meant to remain opaque"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T17:53:02.923",
"Id": "513174",
"Score": "0",
"body": "Did you see exercise 16 in section 1.4.1' of Fascicle 1, MMIX? (Nonlocal goto statements.) Sometimes we want to jump out of a subroutine, to a location that is not in the calling routine. For example, suppose subroutine A calls subroutine B, which calls subroutine C, which calls itself recursively a number of times before deciding that it wants to exit directly to A. Explain how to handle such situations when using MMIX's register stack. (We can't simply JMP from C to A; the stack must be properly popped.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T17:57:03.230",
"Id": "513175",
"Score": "0",
"body": "It's pretty straightforward to run your code with MMIX tools - you'll be able to see SAVE and UNSAVE in action and check your implementation"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T00:37:13.277",
"Id": "513208",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/123481/discussion-between-nolongerbreathedin-and-zartaj-majeed)."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T17:50:00.777",
"Id": "259991",
"ParentId": "256527",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T06:52:46.620",
"Id": "256527",
"Score": "2",
"Tags": [
"assembly"
],
"Title": "setjmp and longjmp implementation in mmix"
}
|
256527
|
<p>I've written a script which creates a <code>new database</code>, a <code>table</code> within the database, <code>insert some values</code> into it and <code>fetch the values</code> in one go. The way I've created the script below to achieve what I just said seems not to be an ideal way as there are too many repetitions in there. To be specific this two functions <code>create_database()</code> and <code>connect()</code> are almost identical. Moreover, I had to use <code>mycursor = conn.cursor()</code> twice within main function.</p>
<pre><code>import mysql.connector
def create_database():
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd = "",
database=""
)
return mydb
def connect(databasename):
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd = "",
database=databasename
)
return mydb
def store_data(item_name,item_link):
mycursor.execute("INSERT INTO webdata (item_name,item_link) VALUES (%s,%s)", (item_name,item_link))
conn.commit()
if __name__ == '__main__':
db_name = "newdatabase"
conn = create_database()
mycursor = conn.cursor()
try:
mycursor.execute(f"CREATE DATABASE {db_name}")
except mysql.connector.errors.DatabaseError:
pass
conn = connect(db_name)
mycursor = conn.cursor()
mycursor.execute("DROP TABLE if exists webdata")
mycursor.execute("CREATE TABLE if not exists webdata (item_name VARCHAR(255), item_link VARCHAR(255))")
store_data("all questions","https://stackoverflow.com/questions/tagged/web-scraping")
mycursor.execute("SELECT * FROM webdata")
for item in mycursor.fetchall():
print(item)
</code></pre>
<p>What it prints (expected result):</p>
<pre><code>('all questions', 'https://stackoverflow.com/questions/tagged/web-scraping')
</code></pre>
|
[] |
[
{
"body": "<p>From the title alone, this sounds like something that should not be done, particularly since this is not a lightweight database such as SQLite. Creating the database, its tables, columns, constraints etc. is not, and should not, be the job of the application - but rather an external setup script with administrative permissions. The application, then, should not have such permissions and should only be able to insert/select/update/delete.</p>\n<p>For some reason I thought autocommit is enabled by default for the MySQL Python connector, but apparently it's not:</p>\n<p><a href=\"https://dev.mysql.com/doc/connector-python/en/connector-python-connectargs.html\" rel=\"nofollow noreferrer\">https://dev.mysql.com/doc/connector-python/en/connector-python-connectargs.html</a></p>\n<p>So your explicit call to <code>commit</code> is fine.</p>\n<p>I can't tell from the documentation whether the cursor and connection objects support context management. Try putting both of those in <code>with</code> statements, and if it complains that there's no <code>__enter__</code>, switch to a <code>try/finally</code> that guarantees cursor and connection closure.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T19:44:54.973",
"Id": "506526",
"Score": "1",
"body": "It seems [you concluded in 2020](https://codereview.stackexchange.com/a/240938/52915) that context management is not supported by default. According to the bugtracker, the functionality has been added since then. However, it might be a good idea to double-check that."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T15:55:20.203",
"Id": "256539",
"ParentId": "256528",
"Score": "4"
}
},
{
"body": "<p>Python functions can have optional arguments with default values. If you adjust\nthe signature of <code>connect()</code> to have a default, the <code>create_database()</code>\nfunction will be unnecessary.</p>\n<pre><code>def connect(database_name = ''):\n return mysql.connector.connect(\n host = 'localhost',\n user = 'root',\n passwd = '',\n database = database_name\n )\n</code></pre>\n<p>Contrary to your question text, you don't have a main function; you just have\ntop-level code nested under an if-conditional. Top-level code (other than\nconstants or imports) is generally a bad idea because it is inflexible and not\neasily tested or experimented with. Move that code into a proper\n<code>main()</code> function, and then just invoke it in the if-conditional. It's also not\na bad idea to prepare for the future of your script by including the\nability to handle simple command-line arguments -- often handy for debugging and\nexperimentation even if they are never part of an intended use case of the script.</p>\n<pre><code>import sys\n\ndef main(args):\n ...\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n</code></pre>\n<p>After you make that change, the <code>store_data()</code> function will be broken, because\nit depends on having access to the global <code>mycursor</code> variable. That's another\nillustration of the problems with top-level code: it can camouflage dependencies\nand, in some cases, create situations that are difficult to debug and disentangle if\nthe volume of such code grows large enough. Instead, the <code>store_data()</code> function\nshould take the DB connection as an explicit argument.</p>\n<p>A rigorous approach\nof putting all code inside of functions will seem like a small hassle at first;\nbut in my experience, it nearly always pays off in the form of fewer\nbugs, greater flexibility, improved code readability, and various other\nbenefits.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T17:33:35.073",
"Id": "256546",
"ParentId": "256528",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "256539",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T07:50:50.833",
"Id": "256528",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"mysql",
"database"
],
"Title": "Creating a database, a table within the database and inserting some values into it in one go"
}
|
256528
|
<p>Using GetEnumerator extensions added in C# 9 I was able to do the following:</p>
<pre><code> public static class Extensions
{
public static IEnumerator<int> GetEnumerator(this Range range)
{
var start = range.Start.Value;
var end = range.End.Value;
var current = start;
while (current <= end)
{
yield return current++;
}
}
}
</code></pre>
<p>Which enables me to do this neat thing:</p>
<pre><code>foreach (var i in 1..5)
{
Console.WriteLine(i);
}
</code></pre>
<p>What I want to know is what are potential problems or side effects. Apart from a little performance loss, what downsides can you see if I would write like this in the future instead of using a for loop?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T10:52:52.253",
"Id": "506492",
"Score": "0",
"body": "Since it doesnt support 1..5.Select(i => ) I say Enumerable.Range still wins"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T09:56:17.910",
"Id": "506549",
"Score": "0",
"body": "Which part of **your code** should be reviewed? Or are you looking for details about a new C# 9 feature?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T08:05:17.287",
"Id": "256529",
"Score": "0",
"Tags": [
"c#"
],
"Title": "Iterating over a C# range"
}
|
256529
|
<p>I made very simple interpreter in C and now, I want to make my code better.</p>
<p>Here is my code:</p>
<pre><code>#define size_t unsigned long long
int printf(const char *format, ...);
int scanf(const char *format, ...);
void *memmove(void *str1, const void *str2, size_t n);
size_t strlen(const char *str);
int main()
{
char ch[50];
do
{
printf(">>> ");
scanf("%s", ch);
if (ch[0] == '"' & ch[strlen(ch) - 1] == '"')
{
memmove(ch, ch + 1, strlen(ch));
ch[strlen(ch) - 1] = '\0';
printf("%s\n", ch);
}
}
while(1);
}
</code></pre>
<p><a href="https://github.com/ArianKG/PrintLang" rel="nofollow noreferrer">GitHub Link</a></p>
<p>(I don't want to include standard libraries)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T12:27:13.190",
"Id": "506508",
"Score": "0",
"body": "Welcome to the Code Review Community."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T15:37:37.407",
"Id": "506514",
"Score": "2",
"body": "Somehow this is not the first post I've seen this year that claims \"I don't like to include libraries, so I'll go through the trouble of redeclaring prototypes myself and then linking to the standard libraries\". Is there some kind of low-quality tutorial or course advocating for this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T15:43:06.330",
"Id": "506515",
"Score": "0",
"body": "@Reinderien No."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T16:23:21.600",
"Id": "506517",
"Score": "1",
"body": "Where did you get the idea then, that declaring the functions from the standard library might be a good idea?"
}
] |
[
{
"body": "<p>There are a number of issues in this very short program.\nUnless there are coding standards that require otherwise, it is better to use <code>typedef</code> to define types rather than <code>#define</code>.</p>\n<p>You are calling standard C libraries when you call <code>printf()</code>, <code>scanf()</code>, <code>memmove()</code> and <code>strlen()</code> unless you have written all of these functions on your own and linking in some sort of special manner.</p>\n<p>It is not a good idea to redefine <code>size_t</code> at any point since it is defined by the system header files and may be different on different platforms (the Windows version of <code>size_t</code> is different than the Fedora Linux version of <code>size_t</code> for example).</p>\n<p>The code contains a possible buffer overflow when performing the <code>scanf()</code>. The array <code>ch</code> is only 50 characters. This can lead to undefined behavior.</p>\n<p>You don't need a <code>long long</code> for an array that is a maximum of 50 characters.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T17:14:16.863",
"Id": "506523",
"Score": "3",
"body": "Actually, even if you write your own `printf()`, `scanf()`, etc, you may still be calling Standard C Library functions - the compiler is allowed to ignore such redefinitions."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T12:41:04.200",
"Id": "256534",
"ParentId": "256533",
"Score": "5"
}
},
{
"body": "<ul>\n<li>Your <code>main</code> function is missing a prototype. You should write <code>int main(void)</code> instead to explicitly say that this function does not take any arguments.</li>\n<li>What if I enter just a <code>"</code>?</li>\n<li>What if I enter <code> "hello"</code> with some leading spaces?</li>\n<li>What if I enter <code>"hello, world"</code>?</li>\n<li>By using <code>&</code> instead of <code>&&</code>, you force the condition on the right hand to be evaluated, which invokes undefined behavior if <code>ch</code> is an empty string.</li>\n<li>Since you are moving <code>strlen(ch)</code> bytes, there is no need to set <code>ch[strlen(ch) - 1] = '\\0'</code> anymore, the <code>memmove</code> does this already.</li>\n<li>In a <code>do { ... } while</code> loop, the <code>while</code> should not be written at the beginning of a line since it looks as if it were an endless loop there.</li>\n</ul>\n<p>From the introduction, it is not clear what exactly your code is supposed to interpret and what the expected results are. In its current state, the code does not feel to implement a good specification at all, so you should start with a specification, make it somewhat good (it doesn't need to be perfect), and then you should start to implement the first prototype.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T16:33:55.133",
"Id": "256540",
"ParentId": "256533",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "256534",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T12:06:41.933",
"Id": "256533",
"Score": "0",
"Tags": [
"c",
"interpreter"
],
"Title": "Very simple interpreter in C"
}
|
256533
|
<p>Anyone interested in reviewing and sharing comments on the following approach?</p>
<h1>Requirements:</h1>
<ul>
<li>Job - Code that executes and performs certain action</li>
<li>JobGroup - One or more Jobs grouped to perform some work in a coordinated fashion. Jobs within a JobGroup are organized in a sequence</li>
<li>CronSchedule - A crontab schedule - that determines the time at which the JobGroup needs to be executed on a recurring basis</li>
<li>The JobGroup and Jobs configuration, including the Cron Schedules should be stored/retrieved from a database</li>
<li>Implement a Job executor that dynamically retrieves the Cron Schedules from the database and executes the configured Job Groups based on corresponding crontab schedules</li>
<li>Use Azure Durable Functions that dynamically polls until certain conditions are met</li>
</ul>
<h2>Following is the implementation (for review)</h2>
<ul>
<li>Reference:
<ul>
<li><a href="https://docs.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-monitor" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-monitor</a>?</li>
<li><a href="https://docs.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-monitor?tabs=csharp" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-monitor?tabs=csharp</a></li>
</ul>
</li>
<li>Implements a Timer Trigger Function that reads the JobGroup configuration and kicks-off a Durable JobGroupSchedulingOrchestrator for individual JobGroup.
<ul>
<li>To keep unique instances of the orchestrator - the instance ID for the JobGroupSchedulingOrchestrator is set to be same as the name of the JobGroup</li>
</ul>
</li>
<li>The JobGroupSchedulingOrchestrator retrieves the crontab schedule for the specific JobGroup and uses a durableOrchestrationContext.CreateTimer() and monitors the 'timer'</li>
<li>On waking up from the timer, JobGroupSchedulingOrchestrator kicks-off a Durable JobExecutionOrchestrator sub-orchestration for the actual execution of the jobs.
<ul>
<li>To keep unique instances of the orchestrator - the instance ID for the JobExecutionOrchestrator is set to be same as the name of the JobGroup with a suffix "_Execution_Orchestrator"</li>
</ul>
</li>
</ul>
<pre><code> using System;
public class AzureDynamicTimerMonitoringOrchestrationFunctionApp
{
public class OrchestratedJobGroup
{
public string Name { get; set; }
public string CronSchedule { get; set; }
public int Iterations { get; set; }
}
public class Job
{
public decimal Id { get; set; }
public string JobGroupName { get; set; }
public string JobName { get; set; }
public decimal SequenceNumber { get; set; }
public bool Enabled { get; set; }
}
public class JobGroup
{
public decimal Id { get; set; }
public string JobGroupName { get; set; }
public string CronSchedule { get; set; } // e.g., "0 1 * * *" - every day at 1AM
public bool Enabled { get; set; }
}
public class JobGroupSchedule
{
public string CronSchedule { get; set; }
public List<Job> JobsToRun { get; set; }
/// <summary>
/// Time to wait until the next run
/// -1 : No more runs - done with the JobGroup runs
/// 0 : No wait - execute the jobs in the jobgroup
/// Value greater than 0 : Wait time in seconds until the next jobgroup run attempt
/// </summary>
public double WaitTime { get; set; }
public string NextOccurences { get; set; }
}
public class JobResult
{
public Job Job { get; set; }
public bool Success { get; set; }
}
private List<JobGroup> GetJobGroups()
{
// Returns a list of all Jobs for all jobs groups
// Individual jobgroups
return new List<JobGroup>(); // mocking an empty for code review
}
[FunctionName(nameof(JobExecutor))]
public Task<bool> JobExecutor([ActivityTrigger] Job job, ILogger logger)
{
//
// The actual work of the job is performed here
//
return Task.FromResult(true);
}
[FunctionName(nameof(GetJobGroupSchedule))]
public Task<JobGroupSchedule> GetJobGroupSchedule([ActivityTrigger] OrchestratedJobGroup orchestratedJob, ILogger logger)
{
return Task.FromResult(new JobGroupSchedule
{
WaitTime = -1 // mocking an empty for code review
});
}
[FunctionName(nameof(TimerOrchestrationLauncher))]
public async Task TimerOrchestrationLauncher(
[TimerTrigger("%TimerOrchestrationLauncherInterval%")] TimerInfo timer,
[DurableClient] IDurableOrchestrationClient starter, ILogger log)
{
List<JobGroup> jobGroups;
try
{
//
// Get all enabled jobgroups' info
//
jobGroups = await GetJobGroups();
}
catch (Exception ex)
{
throw new Exception("Error retrieving JobGroup information", ex);
}
var success = true;
foreach (var jobGroup in jobGroups)
{
try
{
if (configuration.GetValue<bool>($"Disable{jobGroup.JobGroupName}") == true)
{
log.LogInformation("JobGroup has been disabled via the app settings. Skipping JobGroup orchestrator {JobGroup}", jobGroup.JobGroupName);
continue;
}
//
// Is the jobgroup orchestration already active?
//
var durableOrchestrationStatus = await starter.GetStatusAsync(jobGroup.JobGroupName);
log.LogInformation("JobGroup Orchestration Job Group: {JobGroup} Current status: {OrchestrationStatus}",
jobGroup, durableOrchestrationStatus.RuntimeStatus);
if (durableOrchestrationStatus.RuntimeStatus == OrchestrationRuntimeStatus.Canceled
|| durableOrchestrationStatus.RuntimeStatus == OrchestrationRuntimeStatus.Completed
|| durableOrchestrationStatus.RuntimeStatus == OrchestrationRuntimeStatus.Failed
|| durableOrchestrationStatus.RuntimeStatus == OrchestrationRuntimeStatus.Terminated)
{
log.LogInformation("JobGroup not active. Kicking-off JobGroup Orchestration. Job Group: {JobGroup}", jobGroup);
//
// Launch orchestrator - pass in the cron-schedule and job-group name
// Use the name of the JobGroup as the instanceid for the orchestrator. This ensures
// that no two instances of the same jobgroup are running at the same time
// with the RuntimeStatus check in place
//
string instanceId = await starter.StartNewAsync(nameof(JobGroupSchedulingOrchestrator),
jobGroup.JobGroupName,
new OrchestratedJobGroup
{
Name = jobGroup.JobGroupName,
CronSchedule = jobGroup.CronSchedule
});
log.LogInformation("Started orchestration Job Group: {JobGroup} with ID {JobInstanceId}", jobGroup, instanceId);
}
else
{
log.LogInformation("JobGroup Orchestration already active, running or in an unknown status. Doing nothing. Job Group: {JobGroup}", jobGroup);
}
}
catch (Exception ex)
{
log.LogError(ex, "Error kicking-off JobGroup Orchestration. Job Group: {JobGroup}", jobGroup);
success = false;
}
}
log.LogInformation("Started orchestration of {JobGroupCount}", jobGroups.Count());
if (success == false)
{
throw new Exception("Errors found during JobGroup Orchestration orchestration");
}
}
[FunctionName(nameof(JobSchedulingOrchestrator))]
public async Task<bool> JobGroupSchedulingOrchestrator(
[OrchestrationTrigger] IDurableOrchestrationContext context, ILogger logger)
{
//
// Reference: https://docs.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-monitor?tabs=csharp
//
var orchestratedJobGroup = context.GetInput<OrchestratedJobGroup>();
//
// Initialize the schedule run info
//
var jobGroupSchedule = await context.CallActivityAsync<JobGroupSchedule>(nameof(GetJobGroupSchedule), orchestratedJobGroup);
if (jobGroupSchedule.WaitTime < 0)
{
// Schedule info indicates to not run this jobgroup anymore - exit
logger.LogError("Error getting next scheduled run info. Exiting JobGroup orchestrator {JobGroup}", orchestratedJobGroup.Name);
return await Task.FromResult(true);
}
while (true)
{
// Register any updates to wait time or cron schedule
orchestratedJobGroup.CronSchedule = jobGroupSchedule.CronSchedule;
DateTime nextCheckpoint = context.CurrentUtcDateTime;
if (jobGroupSchedule.WaitTime > 0)
{
// Schedule info indicates for us to wait for the next checkpoint
nextCheckpoint = context.CurrentUtcDateTime.AddSeconds(jobGroupSchedule.WaitTime);
logger.LogInformation("Next check for JobGroup {JobGroup} at {nextCheckpoint}", orchestratedJobGroup.Name, nextCheckpoint);
// Wait until the next check-point
await context.CreateTimer(nextCheckpoint, CancellationToken.None);
if (configuration.GetValue<bool>($"Disable{orchestratedJobGroup.Name}") == true)
{
logger.LogInformation("Function app has been disabled via the app settings. Exiting JobGroup orchestrator {JobGroup}", orchestratedJobGroup.Name);
break;
}
//
// Get the latest schedule run info
//
orchestratedJobGroup.Iterations++;
jobGroupSchedule = await context.CallActivityAsync<JobGroupSchedule>(nameof(GetJobGroupSchedule), orchestratedJobGroup);
if (jobGroupSchedule.WaitTime < 0)
{
// Schedule info indicates to not run this jobgroup anymore - exit
logger.LogError("Exiting JobGroup orchestrator {JobGroup}", orchestratedJobGroup.Name);
break;
}
}
logger.LogInformation("Executing JobGroup {JobGroup} at {nextCheckpoint}", orchestratedJobGroup.Name, nextCheckpoint);
try
{
await context.CallSubOrchestratorAsync(
nameof(JobExecutionOrchestrator),
$"{orchestratedJobGroup.Name}_Execution_Orchestrator",
jobGroupSchedule.JobsToRun);
}
catch (Exception ex)
{
logger.LogError(ex, "Error Executing JobGroup {JobGroup} at {nextCheckpoint}", orchestratedJobGroup.Name, nextCheckpoint);
}
}
return await Task.FromResult(true);
}
[FunctionName(nameof(JobExecutionOrchestrator))]
public async Task<bool> JobExecutionOrchestrator(
[OrchestrationTrigger] IDurableOrchestrationContext context, ILogger logger)
{
var jobs = context.GetInput<List<Job>>();
// Get all jobs
jobs = jobs.OrderBy(i => i.SequenceNumber).ToList();
var tasks = new List<Task<JobResult>>();
foreach (var job in jobs)
{
// Add task function to task list
var task = context.CallActivityAsync<JobResult>(nameof(JobExecutor), job);
tasks.Add(task);
}
//
// Wait until all jobs are done
//
try
{
await Task.WhenAll(tasks);
foreach (var task in tasks)
{
var result = await task;
if (result.Success == false)
{
logger.LogError($"Remaining jobs - Failed running job {result.Job?.JobName} in job group {context.InstanceId}");
if (result.Job.ContinueOnFailure == false)
{
return false;
}
}
}
}
catch (Exception ex)
{
logger.LogError(ex, $"Failed running remaining jobs in group {context.InstanceId}");
return false;
}
return true;
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T13:42:09.463",
"Id": "256535",
"Score": "0",
"Tags": [
"c#",
"azure"
],
"Title": "Azure - Dynamically polling until certain conditions are met - using Azure Durable Functions"
}
|
256535
|
<p>I'm new to coding and have been directed here from Stack Overflow. As I'm new to coding, I'm not entirely sure if my program works completely, but I think it does. I'm looking for suggestions on how to improve my code, particularly the format, as well as the code itself please.</p>
<p>Rather than output FizzBuzz for the first 100 numbers, i.e., 1 - 100, I wanted to write a program that could output FizzBuzz for any positive whole number range.</p>
<pre><code>const fizzBuzz = (num) => {
let fizzBuzzNumbers = [];
const populateArray = num => {
for (let i = 1; i < num + 1; i++) {
fizzBuzzNumbers.push(i);
}
};
populateArray(num)
for (let i = 0; i < fizzBuzzNumbers.length; i++) {
if (fizzBuzzNumbers[i] % 3 === 0 && fizzBuzzNumbers[i] % 5 === 0) {
console.log('FizzBuzz');
} else if (fizzBuzzNumbers[i] % 3 === 0 && fizzBuzzNumbers[i] % 5 !== 0) {
console.log('Fizz');
} else if (fizzBuzzNumbers[i] % 3 !== 0 && fizzBuzzNumbers[i] % 5 === 0) {
console.log('Buzz');
} else {
console.log(fizzBuzzNumbers[i]);
}
}
};
</code></pre>
<p>Any feedback or suggestions will be greatly appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T15:22:01.267",
"Id": "506513",
"Score": "6",
"body": "You can start with `i = 1` and then drop the array completely."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T16:57:21.300",
"Id": "506518",
"Score": "0",
"body": "@konijn thank you very much for the suggestion. As I'm very new to coding, I'm unsure of how to implement the change. Is it possible to show me where in the code I can start with i = 1 and drop the array please?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T00:24:05.757",
"Id": "506537",
"Score": "16",
"body": "`I'm not entirely sure if my program works completely, but I think it does.` How do you come to be unsure? Have you run the program? Did it work? Have you run it for some other ranges? Have you considered what ranges might cause weird behaviours? Welcome to Software development. More than half of the work is testing and debugging the code you wrote :D"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T18:14:23.883",
"Id": "506818",
"Score": "0",
"body": "@Brondahl - I think it's just a confidence thing because I've only been learning for a few months. I've tested programs I've written as part of a supported learning pathway before, but this was the first time I have tried to write a program from scratch off of a brief that was just 'Write a program that...' As for debugging, that's something I'm yet to become familiar with, so your comment has got me investigating that now. Really appreciate your comment. Thanks."
}
] |
[
{
"body": "<p>A short review;</p>\n<ul>\n<li>You don't need the array, you could just use <code>i</code></li>\n<li>Part of the challenge is to realize that you only have to check for <code>3</code> and <code>5</code></li>\n<li><code>i</code> is a good short variable, I would go for <code>num</code> -> <code>n</code> or even <code>count</code></li>\n<li>I only use fat arrow syntax <code>=></code> for inline functions</li>\n<li>Function names ideally follow <code><verb>Thing</code> syntax so <code>fizzBuzz</code> -> <code>logFizzBuzz</code></li>\n</ul>\n<p>This is my counter proposal;</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function logFizzBuzz(count){\n\n for (let i = 1; i <= count; i++) {\n let out = '';\n if (i % 3 === 0){\n out += 'Fizz';\n }\n if (i % 5 === 0){\n out += 'Buzz';\n }\n console.log(out || i);\n }\n}; \n\n\nlogFizzBuzz(45);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T17:10:27.220",
"Id": "506522",
"Score": "3",
"body": "Fantastic! Your solution is so much more elegant and has given me real motivation to revise my own. I knew mine looked clunky, but being so early in my learning, I couldn't work out how to refine it. Thank you for taking the time to review. It's greatly appreciated @konijn."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T16:00:10.427",
"Id": "506569",
"Score": "0",
"body": "While the array isn't necessary for the usual sequential FizzBuzz, it could be useful in a more general version. E.g. you could populate the array with random numbers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T17:00:52.210",
"Id": "506581",
"Score": "3",
"body": "One of the tricks of FizzBuzz is that there are lots of ways to do the \"otherwise, print the number\", and none of them are obviously better than the others. There is no reason a new programmer should be expected to write `console.log(out || i);` instead of something like `console.log(out == \"\" ? i : out);` or even `if(out==\"\") console.log(i); else console.log(out);`"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T16:58:22.213",
"Id": "256542",
"ParentId": "256536",
"Score": "15"
}
},
{
"body": "<p>There are a couple of things that are worrisome in this code. The one that caught me first was the shadowing of the <code>num</code> variable... You have 2 different variables called <code>num</code>.</p>\n<p>In the <code>populateArray</code> function you should have a different name for it, not <code>num</code>.</p>\n<p>This got me thinking, and the name <code>num</code> is a poor name choice. It should be <code>count</code> or similar, because it's not an actual number you are computing FizzBuzz on, but rather the count of values....</p>\n<p>In addition, your loop for populating the array is</p>\n<blockquote>\n<pre><code>for (let i = 1; i < num + 1; i++) {\n fizzBuzzNumbers.push(i);\n}\n</code></pre>\n</blockquote>\n<p>Loops typically are 0-based in computing, and when you need a 1-based loop like you do now, instead of having <code>let i = 1; i < num + 1; i++</code> it is more common to have <code>let i = 1; i <= num; i++</code> - it is probably inconsequential on performance, but having the additional <code>+ 1</code> in each check of the loop is messy. Note that <code><= x</code> is the same as <code>< x + 1</code></p>\n<p>Finally, your if-else-if-else-if ... chain has too many comparisons. Your first comparison compares for both <code>%5</code> and <code>%3</code> so for your subsequent checks you don't need to check for the negative match on things.</p>\n<p>You have:</p>\n<blockquote>\n<pre><code>if (fizzBuzzNumbers[i] % 3 === 0 && fizzBuzzNumbers[i] % 5 === 0) {\n console.log('FizzBuzz');\n} else if (fizzBuzzNumbers[i] % 3 === 0 && fizzBuzzNumbers[i] % 5 !== 0) {\n console.log('Fizz');\n} else if (fizzBuzzNumbers[i] % 3 !== 0 && fizzBuzzNumbers[i] % 5 === 0) {\n console.log('Buzz');\n} else {\n console.log(fizzBuzzNumbers[i]);\n}\n</code></pre>\n</blockquote>\n<p>But that could be just:</p>\n<pre><code>if (fizzBuzzNumbers[i] % 3 === 0 && fizzBuzzNumbers[i] % 5 === 0) {\n console.log('FizzBuzz');\n} else if (fizzBuzzNumbers[i] % 3 === 0) {\n console.log('Fizz');\n} else if (fizzBuzzNumbers[i] % 5 === 0) {\n console.log('Buzz');\n} else {\n console.log(fizzBuzzNumbers[i]);\n}\n</code></pre>\n<p>Technically, your code would read simpler if it was also in a <code>forEach</code> loop, instead of a <code>for(...)</code> loop. Consider the outer loop:</p>\n<pre><code>fizzBuzzNumbers.forEach((value) => {\n if (value % 3 === 0 && value % 5 === 0) {\n console.log('FizzBuzz');\n } else if (value % 3 === 0) {\n console.log('Fizz');\n } else if (value % 5 === 0) {\n console.log('Buzz');\n } else {\n console.log(value);\n }\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T17:08:03.407",
"Id": "506521",
"Score": "1",
"body": "This is excellent feedback @rolfl. Thank you very much! It'll take me a while to understand and digest it all completely, as I'm still a struggling fledgling, but I can see how clunky my code was. I really appreciate you taking the time to review. Thanks again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T15:57:36.510",
"Id": "506567",
"Score": "0",
"body": "Checking for multiples of both 3 and 5 can be simplified to multiplies of 15."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T16:24:14.320",
"Id": "506572",
"Score": "0",
"body": "@Barmar- my answer is not intended to give the best fizzbuzz solution, rather it's to provide some progressive improvements for the OP. I chose a few improvements to point out that will make the OP a better programmer in general, not specifically to solve fizzbuzz ;-) Your point about the %15 is valid though for a highly-performant answer, and if the OP was more advanced in his learning, I would have maybe considered it"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T16:58:40.150",
"Id": "256543",
"ParentId": "256536",
"Score": "10"
}
},
{
"body": "<p>Aside from <code>fizzBuzzNumbers[i]</code> always being identical to <code>i</code> (as others pointed out), I think this is a fantastic first attempt. I.e. if <code>num</code> was 3, <code>fizzBuzzNumbers</code> would be <code>[1,2,3]</code> and <code>i</code> would go from 1-to-2-to 3 without even needing to reference the array at all beyond <code>length</code>, which is just your input <code>num</code>. Your array could actually be <code>['big', 'bad', 'wolf']</code> and the output would be the same for an input of 3.</p>\n<p>One resource that I think is worth a watch after trying this problem is Tom Scott's <a href=\"https://www.youtube.com/watch?v=QPZ0pIK_wsc\" rel=\"nofollow noreferrer\">FizzBuzz: One Simple Interview Question</a> on YouTube. He breaks down some common ways that people approach the problem, as well as why some approaches are better than others.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T20:02:35.023",
"Id": "506828",
"Score": "0",
"body": "thank you for your comment! It had me grinning because that video was where I got the idea from. Tom says 'pause the video and go and attempt to write a program' and I did. It was the first time I sat down and planned out how to write \na program from scratch without assistance. I'm incredibly thankful for your encouragement, especially in this beginning phase of my learning. Thank you."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T09:11:55.403",
"Id": "256610",
"ParentId": "256536",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T13:51:09.867",
"Id": "256536",
"Score": "11",
"Tags": [
"javascript",
"fizzbuzz"
],
"Title": "Logs 'Fizz' for multiples of three, 'Buzz', for multiples of 5, and 'Fizz Buzz' for multiples of 3 & 5"
}
|
256536
|
<p>I have a TCP Listener with <code>NetworkStream</code> that reads 530 bytes from the Client once a second.<br />
Within the TCP Listener <code>BackgroundWorker</code>, I write those bytes into a <code>MemoryStream</code>, and invoke a method that breaks down the <code>MemoryStream</code> into smaller arrays.<br />
Then, I have another <code>BackgroundWorker</code> that constantly compares those smaller arrays to a set of predefined byte arrays- based on the outcome it performs different tasks<br></p>
<p>While this works fine for what I'm doing, I wonder if there's a better, more efficient way of doing it.</p>
<p>Here's my code:</p>
<pre><code>namespace TcpServerTest
{
public partial class Form1 : Form
{
public TcpListener server = null;
public TcpClient client;
public Int32 port = 6100;
public IPAddress localAddr = IPAddress.Parse("127.0.0.1");
public MemoryStream memStream = new MemoryStream(2000);
Byte[] bytesFromTCP = new Byte[530];
byte[] SendtoPlcZeroCalPASS = { 0x0A, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x32, 0x2B };
byte[] SendtoPlcZeroCalFAIL = { 0x0A, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x58 };
byte[] SendtoPlcSmokeCalPASS = { 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x03, 0x4C };
byte[] SendtoPlcSmokeCalFAIL = { 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x46, 0xC9 };
public byte[] arrInt1 = new byte[2];
public byte[] _arrInt1 = { 0x10, 0x02 };
public byte[] arrBool1 = new byte[2];
public byte[] _arrBool1 = { 0x01, 0x00 };
public byte[] arrBool2 = new byte[2];
public byte[] _arrBool2 = { 0x01, 0x00 };
public byte[] arrBool3 = new byte[2];
public byte[] _arrBool3 = { 0x01, 0x00 };
public byte[] arrBool4 = new byte[2];
public byte[] _arrBool4 = { 0x01, 0x00 };
public byte[] arrString1 = new byte[256];
public byte[] _arrString1 = new byte[256];
public byte[] arrString2 = new byte[256];
public byte[] arrBool5 = new byte[2];
public byte[] _arrBool5 = { 0x01, 0x00 };
public byte[] arrBool6 = new byte[2];
public byte[] _arrBool6 = { 0x01, 0x00 };
public byte[] arrBool7 = new byte[2];
public byte[] _arrBool7 = { 0x01, 0x00 };
public byte[] arrCrc = new byte[2];
public Form1()
{
InitializeComponent();
bgWorkerSocketListener.DoWork += bgWorkerSocketListener_DoWork;
bgWorkerSocketListener.WorkerSupportsCancellation = true; //Allow for the background worker process to be cancelled
bgWorkerSocketListener.WorkerReportsProgress = true;
bgWorkerSocketListener.RunWorkerAsync();
bgWorkerTcpProcessor.DoWork += bgWorkerTcpProcessor_DoWork;
bgWorkerTcpProcessor.WorkerSupportsCancellation = true; //Allow for the background worker process to be cancelled
bgWorkerTcpProcessor.WorkerReportsProgress = true;
bgWorkerTcpProcessor.RunWorkerAsync();
}
public void bgWorkerSocketListener_DoWork(object sender, DoWorkEventArgs e) //Start the TCP Listener
{
try
{
AppendTBoxTcpBytes("Waiting for a connection... " + Environment.NewLine);
//Create a listener
server = new TcpListener(localAddr, port);
//Start listening for client requests.
server.Start();
String data = null;
//Enter the listening loop.
while (true)
{
//Perform a blocking call to accept requests.
client = server.AcceptTcpClient();
AppendTBoxTcpBytes("Connected!" + Environment.NewLine);
data = null;
//Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
int i;
while (client.Connected == true)
{
try
{
//Loop to receive all the data sent by the client.
while ((i = stream.Read(bytesFromTCP, 0, bytesFromTCP.Length)) != 0)
{
//Translate data
data = BitConverter.ToString(bytesFromTCP);
AppendTBoxTcpBytes(" Data: " + Environment.NewLine + data + Environment.NewLine + "Length: " + data.Length
+ Environment.NewLine + DateTime.Now.ToString("dd MMMM yyyy HH:mm:ss"));
memStream.Write(bytesFromTCP, 0, bytesFromTCP.Length);
this.Invoke(new EventHandler(processMessageMemStr)); //Process incoming message
memStream.Position = 0;
}
}
catch (Exception ex){}
}
}
}
catch (SocketException ex)
{
MessageBox.Show("SocketException: " + ex);
}
}
private void processMessageMemStr(object sender, EventArgs e) //Process received messages from Memory Stream
{
try
{
memStream.Position = 0;
memStream.Read(arrInt1, 0, 2);
memStream.Read(arrBool1, 0, 2);
memStream.Read(arrBool2, 0, 2);
memStream.Read(arrBool3, 0, 2);
memStream.Read(arrBool4, 0, 2);
memStream.Read(arrString1, 0, 256);
memStream.Read(arrString2, 0, 256);
memStream.Read(arrBool5, 0, 2);
memStream.Read(arrBool6, 0, 2);
memStream.Read(arrBool7, 0, 2);
memStream.Read(arrCrc, 0, 2);
}
catch (Exception err)
{ MessageBox.Show(err.ToString()); }
}
public void bgWorkerTcpProcessor_DoWork(object sender, DoWorkEventArgs e) //Start the TCP Listener
{
ASCIIEncoding ascii = new ASCIIEncoding();
while (true)
{
try
{
if (string.Join(",", arrBool1) == string.Join(",", _arrBool1))
pictureBox2.Image = Resources.green_on;
else
pictureBox2.Image = Resources.led_off;
if (string.Join(",", arrBool2) == string.Join(",", _arrBool2))
pictureBox1.Image = Resources.green_on;
else
pictureBox1.Image = Resources.led_off;
if (string.Join(",", arrBool3) == string.Join(",", _arrBool3))
pictureBox3.Image = Resources.red_on;
else
pictureBox3.Image = Resources.led_off;
if (string.Join(",", arrBool4) == string.Join(",", _arrBool4))
pictureBox4.Image = Resources.red_on;
else
pictureBox4.Image = Resources.led_off;
if (string.Join(",", arrBool5) == string.Join(",", _arrBool5))
pictureBox5.Image = Resources.green_on;
else
pictureBox5.Image = Resources.red_on;
if (string.Join(",", arrBool6) == string.Join(",", _arrBool6))
pictureBox6.Image = Resources.green_on;
else
pictureBox6.Image = Resources.led_off;
if (string.Join(",", arrBool7) == string.Join(",", _arrBool7))
{
pictureBox7.Image = Resources.green_on;
pictureBox8.Image = Resources.led_off;
}
else
{
pictureBox7.Image = Resources.led_off;
pictureBox8.Image = Resources.green_on;
}
AppendTBoxAlarm(ascii.GetString(arrString1, 0, 256));
AppendTBoxStep(ascii.GetString(arrString2, 0, 256));
}
catch { }
}
}
private void btnSendToClient_Click_1(object sender, EventArgs e)
{
try
{
server = new TcpListener(localAddr, port);
NetworkStream stream = client.GetStream();
if (cBoxSendToPLC.SelectedItem == "Test1 PASS")
stream.Write(SendtoPlcZeroCalPASS, 0, SendtoPlcZeroCalPASS.Length);
if (cBoxSendToPLC.SelectedItem == "Test2 PASS")
stream.Write(SendtoPlcSmokeCalPASS, 0, SendtoPlcZeroCalPASS.Length);
if (cBoxSendToPLC.SelectedItem == "Test1 FAIL")
stream.Write(SendtoPlcZeroCalFAIL, 0, SendtoPlcZeroCalPASS.Length);
if (cBoxSendToPLC.SelectedItem == "Test2 FAIL")
stream.Write(SendtoPlcSmokeCalFAIL, 0, SendtoPlcZeroCalPASS.Length);
else{}
}
catch (Exception err)
{
MessageBox.Show("No client is yet connected to the server.\n" + "Exception: " + err.Message, "Client not connected", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
public void AppendTBoxTcpBytes(string value) //Appends text, prevents UI from freezing
{
if (InvokeRequired)
{
this.Invoke(new Action<string>(AppendTBoxTcpBytes), new object[] { value });
return;
}
tBoxTcpBytes.Clear();
tBoxTcpBytes.Text += value;
}
public void AppendTBoxAlarm(string value) //Appends text, prevents UI from freezing
{
if (InvokeRequired)
{
this.Invoke(new Action<string>(AppendTBoxAlarm), new object[] { value });
return;
}
tBoxAlarm.Clear();
tBoxAlarm.Text += value;
}
public void AppendTBoxStep(string value) //Appends text, prevents UI from freezing
{
if (InvokeRequired)
{
this.Invoke(new Action<string>(AppendTBoxStep), new object[] { value });
return;
}
tBoxStep.Clear();
tBoxStep.Text += value;
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>There's a lot of issues in the code. If i'll try to review all of them, the post would be too long.</p>\n<p>Common tips:</p>\n<ul>\n<li>Give variable understandeable names. What is <code>arrBool1</code> means? Write code to avoid such questions.</li>\n<li>When you're in multithreading or asynchronous environment, avoid using global variables. This is strongly recommended. Unless ones is thread-safe or you're using it in a thread-safe manner. Pass data to methods as arguments, use Producer/Consumer collections from <code>System.Collections.Concurrent</code>, etc.</li>\n<li>A monster <code>string.Join(",", arrBool1) == string.Join(",", _arrBool1)</code> can be replaced with simple <code>arrBool1.SequenceEqual(_arrBool1)</code>.</li>\n</ul>\n<p>I'll focus on data receiving avoiding the war with arrays.</p>\n<p>Here's a data structure</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public struct Packet\n{\n public bool bool1;\n public bool bool2;\n public bool bool3;\n public bool bool4;\n public string text1;\n public string text2;\n public bool bool5;\n public bool bool6;\n public bool bool7;\n public short crc;\n\n public static Packet FromStream(Stream stream)\n {\n using BinaryReader br = new BinaryReader(stream, Encoding.ASCII, leaveOpen: true);\n Packet p = new Packet();\n p.header = br.ReadInt16();\n p.bool1 = br.ReadBoolean();\n br.ReadByte();\n p.bool2 = br.ReadBoolean();\n br.ReadByte();\n p.bool3 = br.ReadBoolean();\n br.ReadByte();\n p.bool4 = br.ReadBoolean();\n br.ReadByte();\n p.text1 = FromStringZ(br.ReadChars(256));\n p.text2 = FromStringZ(br.ReadChars(256));\n p.bool5 = br.ReadBoolean();\n br.ReadByte();\n p.bool6 = br.ReadBoolean();\n br.ReadByte();\n p.bool7 = br.ReadBoolean();\n br.ReadByte();\n p.crc = br.ReadInt16();\n return p;\n }\n\n private static string FromStringZ(ReadOnlySpan<char> buffer)\n {\n int i = 0;\n while (i < buffer.Length && buffer[i] != '\\0')\n i++;\n return new string(buffer[0..i]);\n }\n}\n</code></pre>\n<p>You can use <code>BinaryWriter</code> in the same way to write data to some <code>Stream</code>.</p>\n<p>You can receive data in the following way then.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>byte[] headerBuffer = new byte[2];\n\nint bytesReceived;\nwhile (client.Connected == true)\n{\n try\n {\n while ((bytesReceived = stream.Read(headerBuffer, 0, headerBuffer.Length)) > 0) // reads 2 bytes if available\n {\n if (headerBuffer.SequenceEqual(Packet.Id))\n {\n Packet packet = Packet.FromStream(stream); // reads 528 bytes\n this.Invoke((Action)(() => Display(packet)));\n }\n else\n {\n // received another packet type but as this loop doesn't contain\n // any other type packets handler, it goes to abnormal state\n stream.Close();\n }\n }\n }\n catch (Exception ex) { }\n}\n</code></pre>\n<p>The <code>Display</code> method is simple then</p>\n<pre class=\"lang-cs prettyprint-override\"><code>private void Display(Packet packet)\n{\n pictureBox2.Image = packet.bool1 ? Resources.green_on : Resources.led_off;\n pictureBox1.Image = packet.bool2 ? Resources.green_on : Resources.led_off;\n pictureBox3.Image = packet.bool3 ? Resources.red_on : Resources.led_off;\n pictureBox4.Image = packet.bool4 ? Resources.red_on : Resources.led_off;\n pictureBox5.Image = packet.bool5 ? Resources.green_on : Resources.red_on;\n pictureBox6.Image = packet.bool6 ? Resources.green_on : Resources.led_off;\n pictureBox7.Image = packet.bool7 ? Resources.green_on : Resources.led_off;\n pictureBox8.Image = packet.bool7 ? Resources.led_off : Resources.green_on;\n\n AppendTBoxAlarm(packet.text1);\n AppendTBoxStep(packet.text2);\n}\n</code></pre>\n<p>You don't need a <code>BackgroudWorker</code> for displaying the data anymore.</p>\n<p>I tell more, <code>BackgroudWorker</code> is obsolete and let it rest in peace. To run the Server you may spawn a simple <code>Thread</code>.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public Form1()\n{\n InitializeComponent();\n\n // but it's better to move this code to 'Form.Load' event handler\n Thread thread = new Thread(RunServer) { IsBackground = true };\n thread.Start();\n}\n\nprivate RunServer()\n{\n // former bgWorkerSocketListener_DoWork method's body\n}\n</code></pre>\n<hr />\n<p>Another short thing: <code>+=</code> is too slow operation for <code>TextBox</code> because it rewrites the entire string concatenating old and appended values which cause redraw all the content.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>tBoxStep.Clear();\ntBoxStep.Text += value;\n</code></pre>\n<p>Can be replaced with</p>\n<pre class=\"lang-cs prettyprint-override\"><code>tBoxStep.Text = value;\n</code></pre>\n<p>Or if you want to append the text, you have 2 options</p>\n<pre class=\"lang-cs prettyprint-override\"><code>tBoxStep.AppendText(value);\ntBoxStep.AppendLine(value); // appends Environment.NewLine automatically\n</code></pre>\n<p>These two are enough fast regardless of text amount that <code>TextBox</code> contains already.</p>\n<p>And finally, your Server can serve only one client at once. Consider to change the logic if you want to serve multiple clients at once. That's not so hard e.g. spawn new <code>Thread</code> for each <code>TcpClient</code>.</p>\n<p><strong>Further steps:</strong> learn about <code>async/await</code>: <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/async\" rel=\"nofollow noreferrer\">Asynchronous Programming</a>. Network or database interacting code is 100x times easier with it (with no Threads spawning).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T10:36:54.853",
"Id": "506767",
"Score": "1",
"body": "Thank you so much for taking your time to write this up, I'll take all of your suggestions on board. This is just a part of a bigger application (8k lines of code), so I can only imagine how many more monsters are hiding in there :D Thanks again, it's much appreciated.\n\nOn passing data to methods as arguments, can you think of any page/blog that would help me understand it better?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T10:46:42.573",
"Id": "506769",
"Score": "0",
"body": "@W.Donald if the answer was helpful, you may mark it as accepted. `On passing data to methods as arguments` - that's easy, look how I call `Display` method with passing the data structure as argument."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T20:16:42.930",
"Id": "256635",
"ParentId": "256537",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "256635",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T14:33:16.573",
"Id": "256537",
"Score": "1",
"Tags": [
"c#",
"performance",
"array",
".net",
"byte"
],
"Title": "Byte array comparison - efficiency"
}
|
256537
|
<p>While studying <a href="https://deno.land/" rel="nofollow noreferrer">Deno</a> which is a kind of Node with everything normalized to modern JS and TS, I quickly met the;</p>
<pre><code>import { serve } from "https://deno.land/std@0.87.0/http/server.ts";
const server = serve({ hostname: "0.0.0.0", port: 8080 });
for await (const request of server) {
request.respond({ status: 200, body: "Whatever" });
}
</code></pre>
<p>Here the <code>server</code> object is an <a href="https://2ality.com/2016/10/asynchronous-iteration.html" rel="nofollow noreferrer">asynchronous iterator</a>. Whenever a request is received it turns the <code>for await of</code> loop once. I believe <code>server</code> must be instantiated from an Asynchronously Iterable Queue type.</p>
<p>So i tried to implement a similar asynchronous Queue over the <a href="https://codereview.stackexchange.com/a/255817/105433">best synchronous Queue type in JS that i am aware of</a>.</p>
<p>Obviously, in an <code>AsyncQueue</code> we can not have <code>.dequeue()</code> or <code>.peek()</code> functions since in this case dequeueing happens automatically by the resolution of the first promise and there is no point to peek at the first promise in a Queue of promises. Instead here we have a <code>.next()</code> function for dequeueing alongside with an <code>.enqueue()</code> function to insert new promises.</p>
<p>An important aspect of this <code>AsyncQueue</code> is that it must be able to accept new promises both sychronously and asynchronously which means it will run forever.</p>
<p>So the code is below and i would like to know if it can be simplified any further or perhaps there are things to enhance the performance or whatnot. Please bear with my indentation style since i will not change it. Also i like to use the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields" rel="nofollow noreferrer">Private Class Fields</a> very much.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class AsyncQueue {
#HEAD;
#LAST;
static #LINK = class {
#RESOLVER;
constructor(promise,resolver){
this.promise = new Promise(resolve => ( this.#RESOLVER = resolve
, promise.then(value => resolver({value, done: false}))
));
this.next = void 0;
}
get resolver(){
return this.#RESOLVER;
}
}
constructor(){
new Promise(resolve => this.#HEAD = new AsyncQueue.#LINK(Promise.resolve(null),resolve));
};
enqueue(promise){
this.#LAST = this.#LAST ? this.#LAST.next = new AsyncQueue.#LINK(promise,this.#LAST.resolver)
: this.#HEAD = new AsyncQueue.#LINK(promise,this.#HEAD.resolver)
}
next(){
var promise = this.#HEAD.promise.then(value => ({value, done: false}));
this.#HEAD.next ? this.#HEAD = this.#HEAD.next
: this.#LAST = void 0;
return promise;
};
[Symbol.asyncIterator]() {
return this;
};
};
var aq = new AsyncQueue();
async function getAsyncValues(){
for await (let item of aq){
console.log(`The Promise resolved with a value of ${item.value}`);
};
};
getAsyncValues();
// synchronous insertion of promises
for (var i=1; i <= 5; i++) aq.enqueue(new Promise(resolve => setTimeout(resolve, 1000*i, `done at ${1000*i}ms`)));
// asynchronous insertion od a promise
setTimeout(aq.enqueue.bind(aq),7500,Promise.resolve("this is an asynchronnous insertion"));</code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T01:46:56.513",
"Id": "506632",
"Score": "0",
"body": "I believe `async function* serve({ hostname, port }) { while (true) yield { respond({ status, body }) { console.log(status, body); } }; }` may also work."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T17:10:31.377",
"Id": "256544",
"Score": "0",
"Tags": [
"javascript",
"asynchronous",
"queue"
],
"Title": "Asynchronously Iterable Queue Implementation for JavaScript"
}
|
256544
|
<p>I am trying to implement a tiny image tagger with customized tag options in C#. The main window is as follows.</p>
<p><img src="https://user-images.githubusercontent.com/5549662/109428015-ff49a480-7a2f-11eb-8719-555c9c46fde0.png" alt="MainUIFigure" /></p>
<p>The left block is a picture box <code>MainPictureBox</code> and there are two buttons, <code>PreviousButton</code> and <code>NextButton</code>. Furthermore, there are some tags in a group box <code>AttributeGroupBox</code>. A save button <code>SaveButton</code> is used for saving tagged information.</p>
<p>The implemented functions:</p>
<ul>
<li><p>Load images automatically in the folder which the program located.</p>
</li>
<li><p>Each image could be tagged.</p>
</li>
<li><p>The tag information of each image could be saved as a text file <code>LabelResult.txt</code>.</p>
</li>
</ul>
<p><strong>The experimental implementation</strong></p>
<ul>
<li><code>Attribute</code> Class</li>
</ul>
<pre><code>class Attribute
{
public enum AttributeEnum
{
Mountain,
Cat
}
public AttributeEnum attributeEnum;
public override string ToString()
{
if (this.attributeEnum.Equals(AttributeEnum.Cat))
{
return "Cat";
}
if (this.attributeEnum.Equals(AttributeEnum.Mountain))
{
return "Mountain";
}
return "";
}
}
</code></pre>
<ul>
<li>Main Winform</li>
</ul>
<pre><code>public partial class Form1 : Form
{
List<string> ImagePaths;
List<Attribute> AttributeList;
int index = 0;
string targetDirectory = "./";
public Form1()
{
InitializeComponent();
System.IO.FileSystemWatcher watcher = new FileSystemWatcher()
{
Path = targetDirectory,
Filter = "*.jpg | *.jpeg| *.bmp | *.png"
};
// Add event handlers for all events you want to handle
watcher.Created += new FileSystemEventHandler(OnChanged);
// Activate the watcher
watcher.EnableRaisingEvents = true;
ImagePaths = new List<string>();
string[] fileEntries = System.IO.Directory.GetFiles(targetDirectory);
foreach (string fileName in fileEntries)
{
string filenameExt = System.IO.Path.GetExtension(fileName);
if (filenameExt.Equals(".jpg") ||
filenameExt.Equals(".jpeg") ||
filenameExt.Equals(".bmp") ||
filenameExt.Equals(".png")
)
{
ImagePaths.Add(fileName);
}
}
MainPictureBox.SizeMode = PictureBoxSizeMode.Zoom;
MainPictureBox.Image = Image.FromFile(ImagePaths[0]);
AttributeList = new List<Attribute>();
}
private void OnChanged(object source, FileSystemEventArgs e)
{
ImagePaths.Clear();
string[] fileEntries = System.IO.Directory.GetFiles(targetDirectory);
foreach (string fileName in fileEntries)
{
string filenameExt = System.IO.Path.GetExtension(fileName);
if (filenameExt.Equals(".jpg") ||
filenameExt.Equals(".jpeg") ||
filenameExt.Equals(".bmp") ||
filenameExt.Equals(".png")
)
{
ImagePaths.Add(fileName);
}
}
}
private void PreviousButton_Click(object sender, EventArgs e)
{
index--;
if (index <= 0)
{
index = 0;
}
MainPictureBox.Image = Image.FromFile(ImagePaths[index]);
GC.Collect();
}
private void NextButton_Click(object sender, EventArgs e)
{
NextAction();
}
private void NextAction()
{
index++;
if (index >= ImagePaths.Count)
{
index = ImagePaths.Count - 1;
}
MainPictureBox.Image = Image.FromFile(ImagePaths[index]);
GC.Collect();
}
private void SaveButton_Click(object sender, EventArgs e)
{
Attribute attribute = new Attribute();
if (radioButton1.Checked)
{
attribute.attributeEnum = Attribute.AttributeEnum.Mountain;
}
if (radioButton2.Checked)
{
attribute.attributeEnum = Attribute.AttributeEnum.Cat;
}
MessageBox.Show(attribute.ToString());
AttributeList.Add(attribute);
AttributeListToTxt();
NextAction();
}
private void AttributeListToTxt()
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < this.AttributeList.Count; i++)
{
sb.Append(this.ImagePaths[i] + "\t" + this.AttributeList[i].ToString() + Environment.NewLine);
}
File.WriteAllText("LabelResult.txt", sb.ToString());
}
}
</code></pre>
<p>All suggestions are welcome.</p>
<p>If there is any possible improvement about:</p>
<ul>
<li>Potential drawback or unnecessary overhead</li>
<li>The design of implemented methods</li>
</ul>
<p>please let me know.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T13:47:14.760",
"Id": "506557",
"Score": "1",
"body": "Is this WinForms? WPF? Please use better tags than something generic like \"object oriented\"."
}
] |
[
{
"body": "<p>There is plenty room for improvement</p>\n<h3>Attribute</h3>\n<ul>\n<li>There is a <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.attribute\" rel=\"nofollow noreferrer\">built-in class in the BCL</a> with same name which help you define decorators.\n<ul>\n<li>That's why I would not recommend to call your class like this.</li>\n</ul>\n</li>\n<li><code>AttributeEnum</code>: I personally don't like to include enums inside a class definition.\n<ul>\n<li>The usage is also really weird (stuttery): <code>Attribute.AttributeEnum.Cat</code></li>\n</ul>\n</li>\n<li>You don't need perform branching like this: <code>this.attributeEnum.Equals(AttributeEnum.Cat)</code>\n<ul>\n<li><code>this.attributeEnum.ToString("G")</code> would be enough. <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/base-types/enumeration-format-strings\" rel=\"nofollow noreferrer\">Reference</a></li>\n</ul>\n</li>\n</ul>\n<h3>Form1</h3>\n<ul>\n<li><code>FileSystemWatcher</code> is disposable, so please be sure to dispose it</li>\n<li>File extensions: they are repeated at least 3times.\n<ul>\n<li>Please prefer class-wide constants</li>\n</ul>\n</li>\n<li><code>watcher.Created += OnChanged</code>: This is really misleading, because <code>watcher</code> does have event for <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.io.filesystemwatcher.changed\" rel=\"nofollow noreferrer\">Changed</a> as well.</li>\n<li><code>System.IO.Directory.GetFiles(targetDirectory)</code>: Performing I/O operation inside the ctor is not really a good practice.\n<ul>\n<li>Please move every non-essential logic into an <code>Init</code> method.</li>\n</ul>\n</li>\n<li><code>GC.Collect();</code>: Please do not ever call <code>GC.Collect</code> directly. <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/fundamentals#conditions-for-a-garbage-collection\" rel=\"nofollow noreferrer\">Reference</a>:</li>\n</ul>\n<blockquote>\n<p>The GC.Collect method is called. In almost all cases, you don't have to call this method, because the garbage collector runs continuously. This method is primarily used for unique situations and testing.</p>\n</blockquote>\n<ul>\n<li><code>NextAction</code>: This naming does not provide any value.\n<ul>\n<li>Please try to use meaningful names.</li>\n</ul>\n</li>\n<li><code>radioButton1.Checked</code>: Yet again please use meaningful naming.\n<ul>\n<li>For example <code>rb_Montain</code> would be a much better option.</li>\n</ul>\n</li>\n<li><code>AttributeListToTxt</code>: Please try to name your methods in the way that they start with a verb, like: <code>PersistAttributeListIntoTxt</code> or <code>SaveAttributeList</code>, etc.\n<ul>\n<li>Why don't you simply write line-by-line instead of composing the\nwhole content then write it once.</li>\n</ul>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T09:53:50.370",
"Id": "256562",
"ParentId": "256547",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "256562",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T18:37:23.970",
"Id": "256547",
"Score": "1",
"Tags": [
"c#",
"object-oriented",
"reinventing-the-wheel",
"image",
"winforms"
],
"Title": "A Tiny Image Tagger Implementation in C#"
}
|
256547
|
<p>I am working on a simple CRUD app as a personal project using Flask. I am currently working on the <strong>user service</strong> and I just finished the registration process. I am also trying to use as less as libraries as I could, this is why you won't see any ORM or Flask-wtf (for learning purposes).</p>
<ul>
<li><p><strong>models.py</strong>: contains 1 class - <code>User</code>. The <code>User</code> class is just a representation of a <code>User</code> object, there is no method present in this class expect a <code>__str__</code> method.</p>
</li>
<li><p><strong>services.p</strong>y: contains 1 class - <code>UserService</code>. No constructor or class variables. The <code>UserService</code> is use to interact with the <code>User</code> such as create a new user, update a user parameter or delete a user. Most of the <code>UserService</code> methods takes a <code>User</code> as a parameter expect the method to create a new <code>User</code>, <code>add_user()</code></p>
</li>
<li><p><strong>repo.py</strong>: contains 1 class - <code>UserRepository</code>. As I am not using any ORM, I needed a way to interact with the database to add, delete or update rows in the <code>User</code> table. I could have directly make the queries on the <code>User</code> service, but I think I will actually broke the separation of concerns;</p>
</li>
<li><p><strong>Route.py</strong>: Once the user fill the <code>register.html</code> registration form, the form is sent to the <code>/new-user</code> route.</p>
</li>
</ul>
<p>I am wondering about multiple things:</p>
<ul>
<li><p>I read that commit to the repository using sqlite take a decent amount of resources. I do have a save method on my UserRepository class that just do a conn.commit(). But do I have to call this method each time I am creating a new user or like it should be call like after creating x new <code>Users</code> or x new db-operations?</p>
</li>
<li><p>I am converting my <code>active</code> variable from <code>Boolean</code> to <code>Integer</code> (1 or 0) because this is how it is set in my <code>User</code> table on mySQL db as <code>tinyint(1) DEFAULT '1'</code>. Should I also use 1/0 on my code or keep it as True/False and convert from <code>Boolean</code> to <code>Integer</code> in my <code>UserRepository</code> class?</p>
</li>
<li><p>If you have any other red flag or design issues that I should not do, let me know :)</p>
</li>
</ul>
<p>Code bellow:</p>
<p><strong>user/routes.py</strong></p>
<pre><code>user = Blueprint('user', __name__, template_folder='templates')
@user.route('/register')
def login():
return render_template('register.html')
# register new user
@user.route('/new-user',methods = ['POST'])
def register_user():
# gather form data
form_email = request.form.get('email')
form_password = request.form.get('psw')
# register_user() will return a User object
new_user = UserService().register_user(form_email, form_password)
user_repository = UserRepository(conn, 'users')
user_repository.add_user(new_user)
user_repository.save()
# will probably change the return and add try-catch?
return "ok"
</code></pre>
<p><strong>models.py (User class)</strong></p>
<pre><code>class User():
def __init__(self, email, password, registration_date,
active, sign_in_count, current_sign_in_on, last_sign_in_on):
self.email = email
self.password = password
self.registration_date = registration_date
self.active = active
# Activity tracking
self.sign_in_count = sign_in_count
self.current_sign_in_on = current_sign_in_on
self.last_sign_in_on = last_sign_in_on
def __str__(self):
user_attributes = vars(self)
return (', '.join("%s: %s" % item for item in user_attributes.items()))
</code></pre>
<p><strong>services.py (UserService class)</strong></p>
<pre><code>class UserService():
def register_user(self,
email,
password):
# sign-in count is 1 since it is a new user
sign_in_count = 1
# today dates for registration date, current sign-in date and last sign-in date since it's a new user
today_date = datetime.today().strftime('%Y-%m-%d')
active = True
new_user = User(email, password, today_date, active,
sign_in_count, today_date, today_date)
return new_user
def desactivate_user(self, User):
if User.active == False:
print(f"User {User.email} is already inactive")
User.active = False
def reactive_user(self, User):
if User.active == True:
print(f"User {User.email} is already active")
User.active = True
def is_active(self, User):
return User.is_active
def update_activity_tracking(self, User, ip_address):
User.sign_in_count += 1
User.last_sign_in_on = User.current_sign_in_on
User.current_sign_in_on = datetime.datetime.now()
def update_password(self, User, new_password):
User.password = get_hashed_password(new_password)
</code></pre>
<p><strong>repo.py (UserRepository class)</strong></p>
<pre><code>class UserRepository():
def __init__(self, conn, table):
self.conn = conn
self.table = table
def add_user(self, User):
sql = "INSERT INTO users (email, password, is_active, sign_in_count, current_sign_in_on, last_sign_in_on) VALUES (%s, %s, %s, %s, %s, %s)"
cursor = self.conn.cursor()
# the is_active column in the DB is a tinyint(1). True = 1 and False = 0
if User.active == True:
is_active = 1
is_active = 0
cursor.execute(sql, ( User.email, User.password, is_active, User.sign_in_count, User.current_sign_in_on, User.last_sign_in_on))
resp = cursor.fetchall()
return resp
def delete_user(self):
return ""
def get_user(self):
return ""
def save(self):
self.conn.commit()
</code></pre>
|
[] |
[
{
"body": "<p>Opinions always differ on matters like this, but your <code>UserService</code> class seems\nlike a severe case of over-engineering.</p>\n<p>First, three of the methods seem to offer nothing very substantive:\n<code>desactivate_user()</code> and <code>reactive_user()</code> just set boolean attributes on a\n<code>User</code> instance; and <code>is_active()</code> just returns an attribute. I would encourage\nyou to simplify things: just operate on the user instance directly.</p>\n<p>Second, the <code>update_activity_tracking()</code> does more stuff to the user instance,\nbut there's no obvious reason not to move the method into the <code>User</code> class as well.</p>\n<p>Third, the <code>update_password()</code> is a good example of a situation where you could\nuse a property, because you need to perform some calculations before storing\nthe attribute. Here's the basic pattern:</p>\n<pre><code>class User:\n\n def __init__(self, password):\n # Initialize an under-the-hood attribute.\n self._password = None\n\n # Call the setter.\n self.password = password\n\n @property\n def password(self):\n # The getter just returns it.\n return self._password\n\n @property.setter\n def password(self, new_password):\n # The setter does the needed calculation.\n self._password = get_hashed_password(new_password)\n</code></pre>\n<p>Fourth, the <code>register_user()</code> method is a natural fit for a <code>classmethod</code> in\nthe <code>User</code> class:</p>\n<pre><code>class User:\n\n @classmethod\n def register_user(cls, email, password):\n # Python allows you to call functions in keyword style even if the\n # function defines arguments as required positionals. You can use\n # this feature to simplify the code (eliminate some temporary\n # variables in this case) while still preserving code readability.\n today = datetime.today().strftime('%Y-%m-%d')\n return cls(\n email,\n password,\n registration_date = today,\n active = 1,\n sign_in_count = 2,\n current_sign_in_on = today,\n last_sign_in_on = today,\n )\n</code></pre>\n<p>The <code>User.__init__()</code> method has a large number of required parameters. Perhaps\nyour use case demands that, but you might give some thought to which of the\nattributes are truly required in all usages. For example, the method\ncould default to using <code>registration_date</code> if the two sign-on dates\nare not provided (as we do above in <code>register_user()</code>).\nRegardless of that decision, if\ntesting and debugging make direct interaction with <code>__init__()</code> tedious, you\ncan add more conveniences to the class, again using the <code>@classmethod</code>\nmechanism.</p>\n<p>Managing user passwords is tricky business, at least in the real world. It's\ngood that you store a hashed password rather than the plaintext, but I would\nnot include even the hashed password attribute in any kind of printing,\nlogging, etc. Adjust your <code>User.__str__()</code> method accordingly.</p>\n<p>In <code>UserRepository.add_user()</code> you can simplify things. If you are testing for\ntruth, just do it directly (<code>if user.active</code>) rather than indirectly (<code>if user.active == True</code>). Also, <code>bool</code> values in Python are a subclass of <code>int</code>\n(for example, <code>199 + True == 200</code>), so you can delete the conditional logic entirely and\njust do something like this:</p>\n<pre><code>def add_user(self, user):\n # Long lines can be made more readable by formatting\n # them in the style of pretty-printed JSON. Notice how\n # easy this style is to read, scan visually, and edit flexibly.\n sql = '''\n INSERT INTO users (\n email,\n password,\n is_active,\n sign_in_count,\n current_sign_in_on,\n last_sign_in_on\n )\n VALUES (%s, %s, %s, %s, %s, %s)\n '''.strip()\n cursor = self.conn.cursor()\n cursor.execute(\n sql,\n (\n user.email,\n user.password,\n int(user.active),\n user.sign_in_count,\n user.current_sign_in_on,\n user.last_sign_in_on,\n )\n )\n return cursor.fetchall()\n</code></pre>\n<p>Your capitalization of the <code>User</code> variable within various methods is\ninconsistent both with your own usages and with the norms in the wider\nPython community: <code>FooBar</code> for class names and <code>foo_bar</code> for instance\nvariables is the most common approach.</p>\n<p>DB operations can fail. If this is just an early learning exercise, you\ncan safely ignore the problem, but if your goal is to make the application\nmore robust, the operations should be wrapped in <code>try-except</code> structures,\nas hinted at in your code comments.</p>\n<p>In my experience, web applications like this will have various classes\nrepresenting the entities of interest (User, Book, Author, whatever). And\nseveral of those classes will need DB operations: create, read, update, delete,\netc. And those DB operations will be fairly general, in the sense that if you\nwrite a good method to update one kind of instance (eg, User), it can often be\nmade to do the same thing for other kinds of instances, provided that the\nsubstantive classes (User, Book, etc) have attributes, properties, or methods\nto deliver the information (things like table name and a list of <code>(COL_NAME, ATTRIBUTE_VALUE)</code> tuples) that a general-purpose DB method needs in order to\nperform its operation. All of which is to say that <code>UserRepository</code> might\nbe too narrow of a focus. Instead, think about whether and how you might\nconvert that class into just <code>Repository</code>.</p>\n<p>If this web application is intended to be a long-running application, you'll\nwant to wire it up to use the <code>logging</code> framework at some point (rather than\njust printing stuff), but that can come whenever you are ready to learn about\nit.</p>\n<p>Regarding your question about frequency of saving DB changes, don't worry about\nit or overthink it. Build your application with reasonable Python code -- you\nare off to a good start -- and if your application ever needs to achieve higher\nscale, solve the problem when it is clearly visible on the horizon. It's often\neasier to change DBs, scale outward (more running instances of your application\nin different processes or on different servers), or alter the data schema than\nit is to write tricky "save every N operations" code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T00:13:43.913",
"Id": "256552",
"ParentId": "256549",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "256552",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T21:46:46.853",
"Id": "256549",
"Score": "2",
"Tags": [
"python",
"object-oriented",
"design-patterns",
"flask"
],
"Title": "Python (Flask) - User registration system"
}
|
256549
|
<p>I am using Autofac to maximise the sharing of code between Android and iOS via a shared PCL assembly in a Xamarin (native) environment. The shared service layer consists of four interfaces to classes containing methods or data that don't change throughout the lifetime of the application.</p>
<p>Instead of resolving the service classes from the Autofac singleton container at every point of use, I've thought of creating a class of static references to the services.</p>
<p>I would like to know whether there is something intrinsically wrong with this approach (e.g. memory leaks), or if there are any better suggestions someone could make.</p>
<p>This is the gist:</p>
<p>Android (& equivalent iOS):</p>
<pre><code>public class BootStrap
{
private static IContainer container = null;
public static IContainer Container()
{
if (container == null)
{
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterType<CacheFactory>().SingleInstance().As<ICacheFactory>(); ;
builder.RegisterType<ClientFactory>().SingleInstance().As<IClientFactory>();
builder.RegisterType<CoreHelpers>().SingleInstance().As<ICoreHelpers>();
builder.RegisterType<PrefsSerializer>().SingleInstance().As<IPrefsSerializer>();
builder.RegisterType<Services>().SingleInstance();
container = builder.Build();
}
return container;
}
}
public class MainApp
{
private ILifetimeScope RootScope;
public MainApp
{
RootScope = BootStrap.Container().BeginLifetimeScope(); // register types, return container
RootScope.Resolve<Services>(); // set static Services members
}
~MainApp()
{
RootScope.Dispose();
}
}
</code></pre>
<p>Shared Assembly:</p>
<pre><code>public class Services
{
public static ICacheFactory CacheFactory; // data and methods
public static IClientFactory ClientFactory; // data and methods
public static ICoreHelpers CoreHelpers; // methods only
public static IPrefsSerializer PrefsHelper; // methods only
public Services(ICacheFactory _cacheFactory, IClientFactory _clientFactory, ICoreHelpers _coreHelpers, IPrefsSerializer _prefsHelper)
{
CacheFactory = _cacheFactory;
ClientFactory = _clientFactory;
CoreHelpers = _coreHelpers;
PrefsHelper = _prefsHelper;
}
}
</code></pre>
<p>Usage:</p>
<pre><code>Services.CacheFactory.GetCache().DoSomething();
UserClient user = Services.ClientFactory.GetUserClient();
...
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T22:19:38.457",
"Id": "256550",
"Score": "0",
"Tags": [
"android",
"dependency-injection",
"xamarin",
"autofac"
],
"Title": "Using Autofac with static services class"
}
|
256550
|
<p>I have made most of the review changes based on feedback I have got from <a href="https://codereview.stackexchange.com/questions/256360/embedded-iot-local-data-storage-when-no-network-coverage">here</a>. Now I am back here for a second review to further better my code. Before posting the changes, somethings I haven't changed are the following.</p>
<ol>
<li><p>I have left the print statements as-is for now. The reason for this is, at times if something goes wrong at the client site, we usually ask them to grab logs and share them with us. I still haven't given enough thought to the mechanism to control what needs to be printed and what not.</p>
</li>
<li><p>I am still in the midst of figuring out ways to further simplify the whole code from logic and structure. Especially when it comes to handling the wrap-around while reading the timestamps for data writes and reads.</p>
</li>
<li><p>I still need to figure out how to make the tests work for humans. It will take some time to come up with test cases and codes. But I am going to keep that aside for now considering the amount of time I have left to complete this task.</p>
</li>
<li><p>I have managed to get rid of most of the warnings. However, I still have a few warnings as shown below.
<a href="https://i.stack.imgur.com/LEriY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LEriY.png" alt="enter image description here" /></a>
I am a bit reluctant to fix these warnings as they end up breaking the code. For instance, doing the below will get rid of the warning.</p>
<pre><code> *timestamp |= *(uint32_t*)cBucketBufHeadTmp << (8 * I);
</code></pre>
</li>
</ol>
<p>But it breaks the code since now the pointer typecasted to read uint32_t and not uint8_t which is not what I intend to do. The same goes for the others.</p>
<p>Now coming to the code, below is the header file.</p>
<pre><code>/*
* Bucket.h
*
* Created: 17/12/2020 12:57:45 PM
* Author: Vinay Divakar
*/
#ifndef BUCKET_H_
#define BUCKET_H_
#define BUCKET_SIZE 32 // Range 10-32000 Memory in bytes allocated to bucket for edge storage
#define BUCKET_MAX_FEEDS 32 // Range 2-64 Number of unique feeds the bucket can hold
//#define BUCKET_TIME() GetUnixTime(); // Need to define link to function that will provide unix time to this macro
#define BUCKET_MAX_VALUE_SIZE 64 // Maximum value string length
typedef enum {
UINT16,
STRING
} cvalue_t;
// Used to register feeds to the bucket and for passing sensor data to the bucket
typedef struct {
const char* key; // MUST BE CONST, since the feeds reference key will never change.
cvalue_t type; // Data type
void* value; // Value
uint32_t unixTime; // Timestamp
} cbucket_t;
bool BucketRegisterFeed(cbucket_t *feed);
int8_t BucketPut(const cbucket_t *data);
int8_t BucketGet( char *keyOut, char *dataOut, uint32_t *timestampOut);
uint8_t BucketNumbOfRegisteredFeeds(void);
void BucketZeroize(void);
//Debug functions
void DebugPrintRegistrationData(void);
void DebugPrintBucket(void);
void DebugPrintBucketTailToHead(void);
#endif /* BUCKET_H_ */
</code></pre>
<p>Below is the source file.</p>
<pre><code>/*
* Bucket.c
*
* Created: 17/12/2020 12:57:31 PM
* Author: Vinay Divakar
* Description: This module is used to accumulate data when
the network is down or unable to transmit data due to poor
signal quality. It currently supports uint16_t and string
data types. The bucket is designed to maximize the amount
of data that can be stored in a given amount of memory for
typical use. The feeds must be registered before it can be
written to or read from the bucket.
The BucketPut API writes the feed to the bucket.
E.g. 1: If the BucketPut sees that consecutive feeds written
have the same timestamp, then it writes the data as shown below.
This is done to save memory.
[Slot] [Data] [Slot] [Data] [Slot] [Data]...[Timestamp]
E.g. 2: If the BucketPut sees that consecutive feeds written have
different timestamps, then it writes the data as shown below.
[Slot] [Data] [Timestamp] [Slot] [Data] [Timestamp]
[Slot] [Data] [Timestamp]
E.g. 3: If the BucketPut sees a mixture of above, then it writes
the data as shown below.
[Slot] [Data] [Slot] [Data] [Slot] [Data] [Timestamp] [Slot] [Data]
[Timestamp] [Slot] [Data] [Slot] [Data] [Timestamp]
The BucketGet API reads the feed in the following format.
[Key] [Value] [Timestamp]
* Notes:
1. Module hasn't been tested for STRING data type.
*/
/*
*====================
* Includes
*====================
*/
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <stdbool.h>
#include "atmel_start.h"
#include "Bucket.h"
//#include "INIconfig.h"
/* For debug purposes */
const char* cvaluetypes[] = {"UINT16", "STRING"};
/*
*====================
* static/global vars
*====================
*/
// Stores the registered feed
static cbucket_t *registeredFeed[BUCKET_MAX_FEEDS];
static const uint8_t unixTimeSlot = 0xFF; //virtual time slot
// Bucket memory for edge storage and pointers to keep track or reads and writes
static uint8_t cbucketBuf[BUCKET_SIZE];
static uint8_t *cBucketBufHead = &cbucketBuf[0];
static uint8_t *cBucketBufTail = &cbucketBuf[0];
/*
*====================
* Fxns
*====================
*/
static uint8_t RegisteredFeedFreeSlot(void);
/****************************************************************
* Function Name : BucketZeroize
* Description : Zeroize the bucket
* Returns : None.
* Params :None.
****************************************************************/
void BucketZeroize(void){
memset(cbucketBuf, 0, sizeof(cbucketBuf));
}
/****************************************************************
* Function Name : BucketGetRegisteredFeedSlot
* Description : Gets slot index of the registered feed
* Returns : slot index on OK, 0xFF on error
* Params @data: points to the feed struct
****************************************************************/
static uint8_t BucketGetRegisteredFeedSlot(const cbucket_t *data){
uint8_t slotIdx;
/* Check if the feed had been previously registered */
for(slotIdx = 0 ; slotIdx < BUCKET_MAX_FEEDS ; slotIdx++) {
//found it?
if(data == registeredFeed[slotIdx]){
//Get the slot index
return(slotIdx);
}
}
return(0xFF);
}
/****************************************************************
* Function Name : BucketCheckDataAvailable
* Description : Checks for data in the bucket
* Returns : false on empty else true.
* Params None.
****************************************************************/
static bool BucketCheckDataAvailable(void){
return (cBucketBufTail != cBucketBufHead);
}
/****************************************************************
* Function Name : BucketHeadWrapAroundToStart
* Description : Wraps the head to start of the bucket
* Returns None.
* Params None.
****************************************************************/
static void BucketHeadWrapAroundToStart(void){
if(cBucketBufHead >= &cbucketBuf[BUCKET_SIZE]){
cBucketBufHead = &cbucketBuf[0];
}
}
/****************************************************************
* Function Name : BucketTailWrapAroundToStart
* Description : Wraps the tail to start of the bucket
* Returns None.
* Params None.
****************************************************************/
static void BucketTailWrapAroundToStart(void){
if(cBucketBufTail >= &cbucketBuf[BUCKET_SIZE]){
cBucketBufTail = &cbucketBuf[0];
}
}
/****************************************************************
* Function Name : BucketGetTimeStamp
* Description : Gets the timestamp for the specific key
* Returns : true on OK, false on empty
* Params @timestamp: Gets the timestamp while write
****************************************************************/
static bool BucketPutGetTimeStamp(uint32_t *timestamp){
bool status = false;
*timestamp = 0;
//There's no data left to be read from the bucket i.e. tail = head
if(!BucketCheckDataAvailable()){
return(false);
}
//Attempt looking for the time slot,
uint8_t *cBucketBufHeadTmp = cBucketBufHead;
//Iterate through the cells while handling wraparounds, this is to go backwards looking for the timeslot
for(int i = 0 ; i < 5 ; i++, cBucketBufHeadTmp--){
//if head points to start of bucket, wrap to end of the bucket
if(cBucketBufHeadTmp <= &cbucketBuf[0]){
cBucketBufHeadTmp = &cbucketBuf[BUCKET_SIZE];
}
}
//Now, we should be pointing to the virtual time slot i.e. 0xff
if(*cBucketBufHeadTmp == unixTimeSlot){
//Inc address to skip the virtual time slot i.e. 0xFF
cBucketBufHeadTmp++;
//load the timestamp
for(uint8_t i = 0 ; i < sizeof(uint32_t) ; i++, cBucketBufHeadTmp++){
//Handle if head needs to be wrapped around to read the timestamp
if(cBucketBufHeadTmp >= &cbucketBuf[BUCKET_SIZE]){
cBucketBufHeadTmp = &cbucketBuf[0];
}
*timestamp |= *(uint8_t*)cBucketBufHeadTmp << (8 * i);
}//for
//we found it!
status = true;
}//points to timeslot
return(status);
}
/****************************************************************
* Function Name : BucketGetDataSize
* Description : Gets the size of the item
* Returns : false on error, !0 on OK
* Params @data :points to feed struct
****************************************************************/
static uint8_t BucketGetDataSize(const cbucket_t *data){
uint8_t dataSizeOut = 0;
switch(data->type){
case UINT16:{
//Total data size = 2 bytes i.e. 16 bit unsigned
dataSizeOut = sizeof(uint16_t);
}
break;
case STRING:{
//Total data size = length of the string until null terminated. Now get the length of the string by looking upto '\0'
const uint8_t *bytePtr = (uint8_t*)data->value;
dataSizeOut = (uint8_t)strlen((const char*)bytePtr);
//Include the '\0' to be written. This will be used to indicate the end of string while reading
dataSizeOut++;
}
break;
default:
printf("[BucketGetDataSize], invalid data type\r\n");
break;
}
return(dataSizeOut);
}
/****************************************************************
* Function Name : BucketRegisterFeed
* Description : Registers the feed
* Returns : false on error, true on OK
* Params @feed :Feed to register
****************************************************************/
bool BucketRegisterFeed(cbucket_t *feed) {
uint8_t slot = RegisteredFeedFreeSlot();
if (slot >= BUCKET_MAX_FEEDS){
return(false);
} else{
registeredFeed[slot] = feed;
}
return (true);
}
/****************************************************************
* Function Name : BucketGetTimestampForFeed
* Description : Gets the timestamp for the feed
* Returns : false on error, true on OK.
* Params @timestamp: feeds timestamp while read
****************************************************************/
static bool BucketGetTimestampForFeed(uint32_t *timestamp){
int8_t status = false;
*timestamp = 0;
BucketTailWrapAroundToStart();
//Check if tail is pointing to the virtual time slot
if(*cBucketBufTail == unixTimeSlot){//If so, read the timestamp
printf("[BucketGetTimestampForFeed], tail pointing to time slot, read it.\r\n");
*cBucketBufTail++ = 0; //Skip the virtual timeslot and point to the timestamp
for(uint8_t i = 0 ; i < sizeof(uint32_t) ; i++){
BucketTailWrapAroundToStart();
*timestamp |= *(uint8_t*)cBucketBufTail << (8 * i);
*cBucketBufTail++ = 0;
}//for
status = true;
}else{//timeslot not found?
//means the next byte is the slot index for the next feed which is not what we are looking for.
//Lets look beyond, it must be there! - if not, then there's something seriously wrong with the code
uint8_t *cBucketBufTailTmp = cBucketBufTail;
//Iterate and look for the time slot
while(cBucketBufTailTmp++ <= &cbucketBuf[BUCKET_SIZE]){
if(cBucketBufTailTmp >= &cbucketBuf[BUCKET_SIZE]){
cBucketBufTailTmp = &cbucketBuf[0];
}
//Check if we are pointing to the virtual time slot
if(*cBucketBufTailTmp == unixTimeSlot){
printf("[BucketGetTimestampForFeed], yes!, time slot has been found.\r\n");
cBucketBufTailTmp++;//Skip the virtual timeslot and point to the start of the timestamp
for(uint8_t i = 0 ; i < sizeof(uint32_t) ; i++, cBucketBufTailTmp++){
if(cBucketBufTailTmp >= &cbucketBuf[BUCKET_SIZE]){
cBucketBufTailTmp = &cbucketBuf[0];
}
*timestamp |= *(uint8_t*)cBucketBufTailTmp << (8 * i);
}//read the timestamp
status = true;
break;
}//timeslot
}//while
}//else
return(status);
}
/****************************************************************
* Function Name : BucketGetReadData
* Description : Reads the key and value for that feed/slot.
* Returns : false error, true on success.
* Params @key: key to be populated(static).
@value: value read from the bucket.
****************************************************************/
static bool BucketGetReadData(char *key, char *value){
uint8_t slotIdx;
bool status = true;
//Check if the tail is pointing to the end of the bucket or beyond, wrap around to start of bucket to continue reading
BucketTailWrapAroundToStart();
//Read the slot index for the feed
slotIdx = *(uint8_t*)cBucketBufTail; //this is an int8_t type, if greater, will lead to undefined behavior.
*cBucketBufTail++ = 0;
if(slotIdx > BUCKET_MAX_FEEDS){
printf("[BucketGetReadData], Error, Slot[%u] index is out of bounds\r\n", slotIdx);
return(false);
}else{
printf("[BucketGetReadData], Slot[%d] = %p\r\n", slotIdx, (void *)registeredFeed[slotIdx]->key);
}
//Copy the key for the corresponding slot
strncpy(key, registeredFeed[slotIdx]->key, strlen(registeredFeed[slotIdx]->key));
//Read data based on type
switch(registeredFeed[slotIdx]->type){
case UINT16:{
uint16_t dataU16 = 0;
for(uint8_t i = 0 ; i < sizeof(uint16_t) ; i++){//Read 2 bytes
BucketTailWrapAroundToStart();
dataU16 |= *cBucketBufTail << (8 * i);
*cBucketBufTail++ = 0;
}//for
printf("[BucketGetReadData] dataU16 = %hu [0x%X]\r\n", dataU16, dataU16);
sprintf(value, "%hu", dataU16); //convert the u16 into string
}
break;
case STRING:{
uint8_t i = 0; printf("[BucketGetReadData] dataStr = ");
while(*cBucketBufTail != '\0'){
BucketTailWrapAroundToStart();
printf("0x%x ", *cBucketBufTail);
value[i++] = *cBucketBufTail;
*cBucketBufTail++ = 0;
}//copy data until end of string is reached
//copy the null terminated character and point to start of the next address
value[i] = *cBucketBufTail;
*cBucketBufTail++ = 0;
printf("\r\n");
}
break;
default:
printf("[BucketGetReadData], Error, invalid read type Slot[%d]\r\n", slotIdx);
status = false;
break;
}
return(status);
}
/****************************************************************
* Function Name : RegisteredFeedFreeSlot
* Description : Gets first free slot(index) found, returns
* Returns : slot on success else 0xFF
* Params None.
****************************************************************/
static uint8_t RegisteredFeedFreeSlot(void) {
uint8_t slot;
//Check for slots sequentially, return index of first empty one (null pointer)
for(slot = 0; slot < BUCKET_MAX_FEEDS; slot++) {
if(registeredFeed[slot] == 0)
return (slot);
}
//All slots full
return (0xFF);
}
/****************************************************************
* Function Name : CircularBufferWrite
* Description : Writes data to the bucket
* Returns None.
* Params @itemSize: Size of the data
@data: ptr to data to be written
****************************************************************/
static void CircularBufferWrite(uint8_t itemSize, uint8_t *data){
for(uint8_t i = 0 ; i < itemSize ; i++, cBucketBufHead++){
BucketHeadWrapAroundToStart();
*cBucketBufHead = data[i];
}
}
/****************************************************************
* Function Name : BucketPrepareFrame
* Description : Prepares frame to be written to the bucket
* Returns None.
* Params @dataSizeIn: Size of actual feed data
@frameOut: ptr to frame buffer
@slotIn: slot index for the feed
@dataIn: ptr to the feed struct.
****************************************************************/
static void BucketPrepareFrame(uint8_t dataSizeIn, uint8_t *frameOut, uint8_t slotIn, const cbucket_t *dataIn){
uint8_t i = 0;
uint8_t *bytePtr = (uint8_t*)dataIn->value;
for(i = 0 ; i <= dataSizeIn ; i++){
if(i == 0){
frameOut[i] = slotIn;//copy slot index
}else{
frameOut[i] = *bytePtr++; //copy data
}
}
frameOut[i++] = unixTimeSlot; //copy timeslot index
for(uint8_t j = 0 ; j < sizeof(dataIn->unixTime); j++){
frameOut[i++] = (dataIn->unixTime >> 8*j) & 0xFF; //copy the timestamp
}
}
/****************************************************************
* Function Name : BucketPut
* Description : writes to the bucket
* Returns : true on success else negative..
* Params @data :points to struct to be written
****************************************************************/
int8_t BucketPut(const cbucket_t *data) {
uint8_t slot = 0;
uint8_t dataSize = 0;
uint8_t totalSpaceRequired = 0;
uint16_t remaining = 0;
uint32_t lastStoredTime = 0;
uint8_t frame[64];
//Find the slot for this feed
slot = BucketGetRegisteredFeedSlot(data);
if(slot > BUCKET_MAX_FEEDS){
printf("[BucketPut], Error, feed not registered\r\n");
return(-1);
}
//Get th size of the item and handle storing as appropriate
dataSize = BucketGetDataSize(data);
if(dataSize == false){
printf("[BucketPut], Error, invalid data type\r\n");
return(-2);
}
//Get the amount space left in the bucket
remaining = (cBucketBufTail + BUCKET_SIZE - cBucketBufHead-1) % BUCKET_SIZE;
printf("[BucketPut], bucket size = %d remaining space = %hu dataSize = %u\r\n", (int)BUCKET_SIZE, remaining, dataSize);
//Get the timestamp from the unix time slot
bool found = BucketPutGetTimeStamp(&lastStoredTime);
if(found){//last stored timestamp found
printf("[BucketPut] Last stored timestamp[%lu] found\r\n", lastStoredTime);
}
//Check timestamps
if(lastStoredTime == data->unixTime){
//If timestamp matches the current feed, write only data and slot idx
printf("[BucketPut], [%lu] timestamps matched!\r\n",data->unixTime);
totalSpaceRequired = (uint8_t)(dataSize + sizeof(slot));
}else{
//If timestamps different or unavailable, account for a write including the new timestamp
printf("[BucketPut] Last stored timestamp[%lu] is different from Current feed timestamp[%lu]\r\n", lastStoredTime, data->unixTime);
totalSpaceRequired = (uint8_t)(dataSize + sizeof(slot) + sizeof(data->unixTime) + sizeof(unixTimeSlot));
}
//Proceed further only if enough space is available in the bucket
if(totalSpaceRequired > remaining) {
printf("[BucketPut], Error, no space available, space = %hu, required space = %hu\r\n", remaining, totalSpaceRequired);
return(-3);
}else{
printf("[BucketPut], available space = %hu required space = %hu\r\n", remaining, totalSpaceRequired);
}
//If timestamp had matched, overwrite it with current feed data and append with timestamp.
if(lastStoredTime == data->unixTime){
uint8_t shiftOffset = sizeof(slot) + sizeof(data->unixTime);
//move the head backwards by size of time slot index + size of timestamp.
for(int i = 0 ; i < shiftOffset ; i++, cBucketBufHead--){
if(cBucketBufHead <= &cbucketBuf[0]){
cBucketBufHead = &cbucketBuf[BUCKET_SIZE];
}
}//for
}//timestamp matched!
//Get the size of the item based on the data type
uint8_t totalItemSize = (uint8_t)(dataSize + sizeof(slot) + sizeof(data->unixTime) + sizeof(unixTimeSlot));
//Prepare data to be written to the bucket
if(totalItemSize > sizeof(frame)){
printf("[BucketPut], Error, item size is very large\r\n");
return(-4);
}
//If we have reached here, means all checks have passed and its safe to write the item to the bucket
memset(frame, 0, sizeof(frame));
BucketPrepareFrame(dataSize, frame, slot, data);
CircularBufferWrite(totalItemSize, frame);
return(true);
}
/****************************************************************
* Function Name : BucketGet
* Description :Gets the data
* Returns : true on success else negative..
* Params @keyOut :contains the key
@dataOut:contains the value
@timestampOut: contains the timestamp
****************************************************************/
int8_t BucketGet( char *keyOut, char *dataOut, uint32_t *timestampOut) {
//Check if theres anything in the bucket
printf("<==============================================================================>\r\n");
if(!BucketCheckDataAvailable()){
printf("[BucketGet], AlLERT, Bucket is empty, no more data left to read.\r\n");
return(-1);
}
//Read the key-value for the corresponding feed/slot
if(!BucketGetReadData(keyOut, dataOut)){
printf("[BucketGet], Error, bucket read failed\r\n");
return(-2);
}
//Read the timestamp corresponding to this feed
if(!BucketGetTimestampForFeed(timestampOut)){
printf("[BucketGet], Error, feed timestamp read failed\r\n");
return(-3);
}
//All good, dump the key-value and associated timestamp
printf("[Bucket Get] timestamp = %lu \r\n",*timestampOut);
printf("[Bucket Get] key = %s\r\n", keyOut);
printf("[Bucket Get] value = %s\r\n", dataOut);
printf("<==============================================================================>\r\n");
return(true);
}
/****************************************************************
* Function Name : BucketNumbOfRegisteredFeeds
* Description : Gets the num of registered feeds
* Returns : No. of registered feeds
* Params None.
****************************************************************/
uint8_t BucketNumbOfRegisteredFeeds(void) {
uint8_t slot;
// Check for slots sequentially, return index of first empty one (null pointer)
for(slot = 0; slot < BUCKET_MAX_FEEDS; slot++) {
if(registeredFeed[slot] == 0)
break;
}
return (slot);
}
/*
*====================
* Debug Utils
*====================
*/
/****************************************************************
* Function Name : PrintFeedValue
* Description :Prints feed data value via void pointer
and corrects for type FLOAT AND DOUBLE DONT PRINT ON WASPMOTE
BUT NO REASON TO BELIEVE THEY ARE WRONG
* Returns : None.
* Params @feed: Points to the feed to be printed
****************************************************************/
void PrintFeedValue(cbucket_t *feed) {
switch(feed->type){
case UINT16:
printf("%d",*(uint16_t*)feed->value);
break;
case STRING:
printf("%s",(char*)feed->value);
break;
default:
printf("%s","UNSUPPORTED TYPE");
break;
}
}
/****************************************************************
* Function Name : _DebugPrintRegistrationData
* Description :Prints all registered feeds and their details
* Returns : None.
* Params None.
****************************************************************/
void DebugPrintRegistrationData(void) {
uint8_t slot;
printf("********************** Current Bucket Registration Data **************************\r\n");
printf("slot\taddress\tkey\ttype\tvalue\tunixtime\r\n");
for(slot = 0; slot<BUCKET_MAX_FEEDS; slot++) {
printf("%d\t", slot); // Print index
if (registeredFeed[slot] != NULL) {
printf("%p\t",(void *)registeredFeed[slot]->key); // Print structure address
printf("%s\t",registeredFeed[slot]->key); // Print key
printf("%s\t",cvaluetypes[registeredFeed[slot]->type]); // Print type
PrintFeedValue(registeredFeed[slot]); // Print value
printf("\t%lu\r\n",registeredFeed[slot]->unixTime); // Print time
} else printf("--\t--\tEMPTY\t--\t--\r\n");
}
}
/****************************************************************
* Function Name : _DebugPrintBucket
* Description :Prints all bucket memory, even if empty
* Returns : None.
* Params None.
****************************************************************/
void DebugPrintBucket(void) {
uint16_t readIndex = 0;
printf("\r\n********************* BUCKET START ********************\r\n");
while(readIndex < BUCKET_SIZE) {
printf("0x%04X ", readIndex);
for (uint8_t column = 0; column < 16; column++) {
if(readIndex < BUCKET_SIZE) printf("%02X ",cbucketBuf[readIndex]);
readIndex++;
//delayMicroseconds(78); // Wait for a byte to send at 115200 baud
//delay(0.1);
}
printf("\r\n");
}
printf("********************** BUCKET END *********************\r\n");
}
/****************************************************************
* Function Name : _DebugPrintBucket
* Description : Prints bucket memory that has data
* Returns : None.
* Params None.
****************************************************************/
void DebugPrintBucketTailToHead(void) {
uint8_t *cBucketBufHeadTemp = cBucketBufHead;
uint8_t *cBucketBufTailTemp = cBucketBufTail;
uint16_t index;
printf("\n*************** BUCKET START FROM TAIL ****************\n");
// Label and indent first line
if ((cBucketBufTailTemp - &cbucketBuf[0]) % 16 != 0) {
printf(" ");
for (index = (uint16_t)(cBucketBufTailTemp - &cbucketBuf[0]) % 16; index > 0; index--) {
printf(" ");
}
}
// Print rest of data
while(cBucketBufTailTemp != cBucketBufHeadTemp) { // Increment read address
if(cBucketBufTailTemp >= &cbucketBuf[BUCKET_SIZE]) cBucketBufTailTemp = &cbucketBuf[0]; // Handle wraparound
index = (uint16_t)(cBucketBufTailTemp - &cbucketBuf[0]); // Get current index in buffer
if (index % 16 == 0) printf("\n0x%04X ", cBucketBufTailTemp - &cbucketBuf[0]); // New line every 0x00n0
printf("%02X ", *cBucketBufTailTemp);
cBucketBufTailTemp++; // Print data in buffer
}
printf("\n***************** BUCKET END AT HEAD ******************\n");
}
</code></pre>
<p>Below is the test code</p>
<pre><code>char sensorValStr1[] = "aaaaaaa";
char sensorKey1[] ="sensorRef1";
cbucket_t sensor1 = {sensorKey1, STRING, sensorValStr1, 1613343690};
uint16_t sensorValU16_2 = 0xAAAA;
char sensorKey2[] ="sensorRef2";
cbucket_t sensor2 = {sensorKey2, UINT16, (uint8_t*)&sensorValU16_2, 1613343689};
uint16_t sensorValU16_3 = 0xBBBB;
char sensorKey3[] ="sensorRef3";
cbucket_t sensor3 ={sensorKey3, UINT16, (uint8_t*)&sensorValU16_3, 1613343689};
uint16_t sensorValU16_4 = 0xCCCC;
char sensorKey4[] ="sensorRef4";
cbucket_t sensor4 ={sensorKey4, UINT16, (uint8_t*)&sensorValU16_4, 1613343691};
int main(void) {
char keyOutT[32] = {0};
char valOutT[32] = {0};
int8_t status = 0;
uint32_t timeStmp = 0;
//Initialize drivers
//atmel_start_init();
BucketRegisterFeed(&sensor1);
BucketRegisterFeed(&sensor2);
BucketRegisterFeed(&sensor3);
BucketRegisterFeed(&sensor4);
DebugPrintRegistrationData();
printf("=========================================================================================================\r\n");
printf("[BucketPut], Test case-1: Checking the bucket does not overflow when filled with data same timestamps...\r\n");
printf("=========================================================================================================\r\n");
status = false;
for(int i = 0 ; i < 10; i++){
status = BucketPut(&sensor2);
if(status == -3)
break;
}
if(status == -3){
printf("Test case-1: PASSED\r\n");
}else{
printf("Test case-1: FAILED\r\n");
}
DebugPrintBucket();
//Empty the bucket
while(true){
int8_t status = BucketGet(keyOutT, valOutT, &timeStmp);
if(status < 0){
break;
}else{
DebugPrintBucket();
}
}
printf("=========================================================================================================\r\n");
printf("[BucketPut], Test case-2: Checking the bucket does not overflow when filled with data different timestamps...\r\n");
printf("=========================================================================================================\r\n");
status = false;
for(int i = 0 ; i < 5 ; i++){
status = BucketPut(&sensor2);
if(status == -3){//bucket is full
//do nothing
}else{
sensor2.unixTime += 1;
}
}
if(status == -3){
printf("Test case-2: PASSED\r\n");
}else{
printf("Test case-2: FAILED\r\n");
}
DebugPrintBucket();
//Empty the bucket
while(true){
int8_t status = BucketGet(keyOutT, valOutT, &timeStmp);
if(status < 0){
break;
}else{
DebugPrintBucket();
}
}
printf("=========================================================================================================\r\n");
printf("[BucketPut], Test case-3: Checking the bucket write mixture of data same and different timestamps...\r\n");
printf("=========================================================================================================\r\n");
status = false;
for(int i = 0 ; i < 5 ; i++){
status = BucketPut(&sensor3);
if(status == -3){//bucket is full
//do nothing
}else{
if(i == 2){
}else if(i == 3){
}else{
sensor2.unixTime += 1;
}
}//else
}
DebugPrintBucket();
//Empty the bucket
while(true){
int8_t status = BucketGet(keyOutT, valOutT, &timeStmp);
if(status < 0){
break;
}else{
DebugPrintBucket();
}
}
printf("=========================================================================================================\r\n");
printf("[BucketPut], Test case-3: Checking the bucket write with timestamp wrapped around end-->start\r\n");
printf("=========================================================================================================\r\n");
status = false;
for(int i = 0 ; i < 2; i++){
if(i == 0){
BucketPut(&sensor1);
}
status = BucketPut(&sensor2);
if(status == -3)
break;
}
DebugPrintBucket();
//Empty the bucket
while(true){
int8_t status = BucketGet(keyOutT, valOutT, &timeStmp);
if(status < 0){
break;
}else{
DebugPrintBucket();
}
}
printf("=========================================================================================================\r\n");
printf("[BucketPut], Test case-4: Checking the bucket write with mix of string and uint16_t\r\n");
printf("=========================================================================================================\r\n");
status = false;
for(int i = 0 ; i < 4; i++){
if(i == 0){
BucketPut(&sensor1);
}
status = BucketPut(&sensor3);
if(status == -3)
break;
}
DebugPrintBucket();
//Empty the bucket
while(true){
int8_t status = BucketGet(keyOutT, valOutT, &timeStmp);
if(status < 0){
break;
}else{
DebugPrintBucket();
}
}
while (true) {
//empty loop
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T00:06:50.217",
"Id": "510465",
"Score": "0",
"body": "When I see `void *`, I run for the hills. That is a disaster waiting to happen. And it is too hard to debug."
}
] |
[
{
"body": "<p>I really recommend including <code>"Bucket.h"</code> <em>first</em> in the implementation file. Consider the includes as we currently have them:</p>\n<blockquote>\n<pre><code>#include <stdio.h>\n#include <string.h>\n#include <stdint.h>\n#include <stdbool.h>\n#include "atmel_start.h"\n#include "Bucket.h"\n</code></pre>\n</blockquote>\n<p>This masks the problem that <code>Bucket.h</code> doesn't include everything it needs. At present, it will fail if users haven't included <code><stdint.h></code> and <code><stdbool.h></code> first. That's frustrating for your users, who expect to be able to <code>#include "Bucket.h"</code> and just get going.</p>\n<p>The include of <code>"atmel_start.h"</code> seems not to be needed here - keep it out of the library to maintain portability. You should only be including that in source code that's <em>necessarily</em> platform-dependent.</p>\n<p>A helpful tip is to always include standard library headers in a consistent order (most of us use alphabetical order), so it's easy to confirm whether a needed include is already present.</p>\n<hr />\n<p>Here we have a comment that doesn't quite agree with the code:</p>\n<blockquote>\n<pre><code>const char* key; // MUST BE CONST, since the feeds reference key will never change.\n</code></pre>\n</blockquote>\n<p>I think that really should be const, i.e.</p>\n<pre><code>const char *const key; // the feeds reference key will never change.\n</code></pre>\n<p>Similarly,</p>\n<pre><code>/* For debug purposes */\nconst char *const cvaluetypes[] = {"UINT16", "STRING"};\n</code></pre>\n<hr />\n<p>There's still a few format string errors remaining. For example:</p>\n<blockquote>\n<pre><code>printf("[BucketPut] Last stored timestamp[%lu] found\\r\\n", lastStoredTime);\n</code></pre>\n</blockquote>\n<p>should be</p>\n<pre><code>printf("[BucketPut] Last stored timestamp[%" PRIu32"] found\\r\\n", lastStoredTime);\n</code></pre>\n<hr />\n<blockquote>\n<pre><code>static uint8_t cbucketBuf[BUCKET_SIZE];\nstatic uint8_t *cBucketBufHead = &cbucketBuf[0];\nstatic uint8_t *cBucketBufTail = &cbucketBuf[0];\n</code></pre>\n</blockquote>\n<p><code>&cbucketBuf[0]</code> is just a long-winded way to write <code>cbucketBuf</code> - prefer the simpler expression.</p>\n<p>Is there a reason for the two different spellings <code>cbucket</code> and <code>cBucket</code>?</p>\n<hr />\n<p>This looks unwieldy:</p>\n<blockquote>\n<pre><code> const uint8_t *bytePtr = (uint8_t*)data->value;\n dataSizeOut = (uint8_t)strlen((const char*)bytePtr);\n</code></pre>\n</blockquote>\n<p>There's really no point casting from <code>void*</code> to <code>uint8_t*</code> if all we do with that is cast to <code>char*</code>. Just go directly to <code>char*</code>:</p>\n<pre><code> const char *bytePtr = data->value;\n dataSizeOut = (uint8_t)strlen(bytePtr);\n</code></pre>\n<p>There's a bug here, in that if <code>strlen >= UINT8_MAX</code>, we should be reporting that as an error.</p>\n<p>Other casts are redundant:</p>\n<blockquote>\n<pre><code> *timestamp |= *(uint8_t*)cBucketBufHeadTmp << (8 * i);\n</code></pre>\n</blockquote>\n<p><code>cBucketBufHeadTmp</code> already is a <code>uint8_t*</code>, so casting has no effect other than to make the code harder to read (because all casts require manual checking, since we've told the compiler to ignore the mismatch).</p>\n<hr />\n<p>I don't like the loop that's used where a simple subtraction would suffice:</p>\n<blockquote>\n<pre><code> uint8_t shiftOffset = sizeof(slot) + sizeof(data->unixTime);\n //move the head backwards by size of time slot index + size of timestamp.\n for(int i = 0 ; i < shiftOffset ; i++, cBucketBufHead--){\n if(cBucketBufHead <= &cbucketBuf[0]){\n cBucketBufHead = &cbucketBuf[BUCKET_SIZE];\n }\n }//for\n</code></pre>\n</blockquote>\n<p>That requires a lot of inspection to determine that all it's doing as subtracting the size from <code>cBucketBufHead</code>. Much simpler as:</p>\n<pre><code> int shiftOffset = sizeof slot + sizeof data->unixTime;\n if (cbucketBuf + shiftOffset > cBucketBufHead) {\n /* wrap around */\n shiftOffset -= BUCKET_SIZE;\n }\n cBucketBufHead -= shiftOffset;\n</code></pre>\n<hr />\n<p>I'm not a fan of the overuse of parentheses where they are not needed. Examples:</p>\n<blockquote>\n<pre><code>memset(cbucketBuf, 0, sizeof(cbucketBuf));\n\nreturn(0xFF);\n</code></pre>\n</blockquote>\n<p>Those would be easier to read and more idiomatic as</p>\n<pre><code>memset(cbucketBuf, 0, sizeof cbucketBuf);\n\nreturn 0xFF;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T02:50:44.970",
"Id": "506636",
"Score": "0",
"body": "I have made the changes and posted the updates [here](https://codereview.stackexchange.com/questions/256602/embedded-iot-local-data-storage-second-update) If you're open to having one last look :-)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T10:38:32.567",
"Id": "256564",
"ParentId": "256556",
"Score": "2"
}
},
{
"body": "<p>Since Toby Speight and my own review of the previous code already covered most of the issues, I just wanted to describe a few additional important aspects that may help you simplify and improve your code.</p>\n<h2>Make the buffer size a power of two</h2>\n<p>Here's how I would write some important constants:</p>\n<pre><code>#define BUCKET_LOG2_SIZE 5 \n#define BUCKET_SIZE (1u << BUCKET_LOG2_SIZE) \n#define BUCKET_MASK (BUCKET_SIZE - 1)\n</code></pre>\n<p>Here's why: rather than having to do a costly comparison with the tail or head pointer every time, we can do a very cheap <code>&</code> operation instead. If we store the head as an <em>index</em> instead of an absolute pointer, we can do this:</p>\n<pre><code>static void CircularBufferWriteHead(int offset, size_t size, const void *data) {\n const uint8_t *ptr = data; // convenience cast\n unsigned head = cBucketBufHead - cbucketBuf;\n for (head += offset; size; --size) {\n cbucketBuf[head & BUCKET_MASK] = *ptr++;\n ++head;\n }\n cBucketBufHead = &cbucketBuf[head & BUCKET_MASK];\n}\n\nstatic void CircularBufferReadHead(int offset, size_t size, void *data) {\n uint8_t *ptr = data; // convenience cast\n unsigned head = cBucketBufHead - cbucketBuf;\n for (head += offset; size; --size) {\n *ptr++ = cbucketBuf[head & BUCKET_MASK];\n ++head;\n }\n cBucketBufHead = &cbucketBuf[head & BUCKET_MASK];\n}\n</code></pre>\n<p>Notice how wrapround and moving forwards or backwards is now trivial and automatic. I have written these to be compatible with your existing code, but in a comprehensive design, I'd remove <code>cBucketBufHead</code> entirely and simply store a <code>head</code> index value.</p>\n<p>Here's one of your functions, rewritten much more simply, using this:</p>\n<pre><code>static bool BucketPutGetTimeStamp(uint32_t *timestamp) {\n if (!BucketCheckDataAvailable()) {\n return false;\n }\n uint8_t ts;\n uint32_t timestamp_copy;\n const int sizes = sizeof(ts) + sizeof(timestamp_copy);\n CircularBufferReadHead(-sizes, sizeof(ts), &ts);\n CircularBufferReadHead(0, sizeof(timestamp_copy), &timestamp_copy);\n if (ts == unixTimeSlot) {\n *timestamp = timestamp_copy;\n return true;\n }\n return false;\n}\n</code></pre>\n<p>One can make a similar simplification for code reading and writing at the tail.</p>\n<h2>Consider allowing more than a single instance</h2>\n<p>At the moment, there is only allowed to be a single instance of this buffer. I would suggest that a very neat way to improve this would be to gather all of the details into a <code>struct</code> and then pass a pointer to an instance to each of the functions needing it. There is an overreliance on global variables here than contributes to a brittle and inflexible design.</p>\n<h2>Eliminate double buffering</h2>\n<p>The code now uses a <code>uint8_t frame[64]</code> as a secondary buffer. It writes to that buffer and then copies the data into the real buffer. This wastes CPU cycles and memory (and power if this is battery operated) and we can do better. Instead of this:</p>\n<pre><code>memset(frame, 0, sizeof(frame));\nBucketPrepareFrame(dataSize, frame, slot, data);\nCircularBufferWrite(totalItemSize, frame);\n</code></pre>\n<p>You could simply write this and eliminate the <code>BucketPrepareFrame</code> function entirely:</p>\n<pre><code>CircularBufferWriteHead(0, sizeof(slot), &slot);\nCircularBufferWriteHead(0, dataSize, data->value);\nCircularBufferWriteHead(0, sizeof(unixTimeSlot), &unixTimeSlot);\nCircularBufferWriteHead(0, sizeof(data->unixTime), &(data->unixTime));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T02:47:53.213",
"Id": "506635",
"Score": "0",
"body": "I have made the changes and posted the updates [here](https://codereview.stackexchange.com/questions/256602/embedded-iot-local-data-storage-second-update). A quick final review before I close off? :-)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T16:24:15.580",
"Id": "256577",
"ParentId": "256556",
"Score": "3"
}
},
{
"body": "<p>"Store and forward". Minimize effort in the remote device.</p>\n<ul>\n<li>Always store, even if you are online.</li>\n<li>Serialize the data into a text string. JSON is a good candidate. (XML is too fat and ambiguous.)</li>\n<li>A number is a string of digit characters (plus "." if you have decimal places.) Do not worry in the device about how big the numbers can be.</li>\n<li>Use a "circular" buffer of bytes.</li>\n<li>The buffer is a fixed size</li>\n<li>The sensors are pushing serialized strings into it.</li>\n<li>If it is multi-threaded, you will need some simple interlock to avoid multiple sensors stepping on each other.</li>\n<li>The network transmission will pull as much data out of the buffer as is practical based on data available, packetsize, etc.</li>\n<li>The central computer will worry about parsing the numbers, etc.</li>\n<li>If the circular buffer overflows, you may need some simple checkpoint of where to stop: If less than 100 bytes available, stop pushing data into the buffer. (This means it is really a FIFO.)</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T00:52:33.447",
"Id": "258903",
"ParentId": "256556",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "256577",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T02:15:51.503",
"Id": "256556",
"Score": "4",
"Tags": [
"c",
"database",
"circular-list",
"embedded"
],
"Title": "Embedded IoT: local data storage (Updated)"
}
|
256556
|
<p>I have a valid code in C-style</p>
<pre><code>int arr[10][10] = {0}; // all elements of array are 0
</code></pre>
<p>What is the optimal way to do the same for C++ style array?</p>
<p><strong>My idea is</strong></p>
<pre><code>#include <array>
std::array<std::array<int, 10>, 10> arr = {0}; // is it correct?
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T10:49:48.277",
"Id": "506552",
"Score": "2",
"body": "This appears to be a general \"best-practice\" question, rather than a review of an existing function or program."
}
] |
[
{
"body": "<p>I feel this question is more suited for stack overflow, but I'll answer it anyway. In c++ the preferred way to do this is:</p>\n<pre><code>std::array<std::array<int, 10>, 10> arr = {}; // Without the 0\n</code></pre>\n<p>Also remember that <code>static</code> variables are zero-initialised anyway, so you wouldn't need to do that.</p>\n<p>Because this is code review, I would suggest using a <code>typedef</code> to replace <code>std::array<std::array<int, 10>, 10></code> to make your code more readable.</p>\n<p>EDIT: As pointed out in the comments, <code>using</code> is much more powerful than <code>typedef</code> and more modern-c++ ish and one should preferably use it rather than <code>typedef</code>. It supports type aliasing templates and all other cool stuff, which is why it is preferable to use. ( Though never use <code>using namespace ...;</code>)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T16:07:30.963",
"Id": "506570",
"Score": "1",
"body": "I would suggest to use `using` instead of `typedef` as we want to use modern c++ practices."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T16:59:09.207",
"Id": "506580",
"Score": "0",
"body": "Thank you!!!!!!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T19:31:38.033",
"Id": "506610",
"Score": "1",
"body": "@AndreasBrunnet Yes you are totally right. Will edit the answer."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T08:53:31.790",
"Id": "256561",
"ParentId": "256560",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "256561",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T08:43:37.137",
"Id": "256560",
"Score": "0",
"Tags": [
"c++",
"array"
],
"Title": "2D array zeroing C++ style"
}
|
256560
|
<p>This is a very simple FFT, I am wondering what I can do to make this faster and more memory efficient from the programming side (better data types, and maybe some tricks like unrolling loops or using the preprocessor if that is useful here), and not by using a more efficient mathematical algorithm. Obviously I would appreciate advice on best practices as well.</p>
<pre><code>#include <stdio.h>
#include <vector>
#include <iostream>
#include <complex>
#include <cmath>
#include <algorithm>
#define N 1048576
#define PI 3.14159265358979323846
/*
Creating the table of all N'th roots of unity.
We use notation omega_k = e^(-2 pi i / n).
*/
template<typename U>
std::vector< std::complex<U> > rootsOfUnityCalculator() {
std::vector< std::complex<U> > table;
for (size_t k = 0; k < N; k++) {
std::complex<U> kthRootOfUnity(std::cos(-2.0 * PI * k / N), std::sin(-2.0 * PI * k / N));
table.push_back(kthRootOfUnity);
}
return table;
}
/*
Fast Fourier transform, T is the precision level, so float or double.
table is a look up table of the roots of unity. Overwrites the input.
For now only works for N a power of 2.
*/
template<typename T>
void FFT(std::complex<T>* input, const std::vector< std::complex<T> >& table, size_t n) {
if (n % 2 == 0) {
// Split up the input in even and odd components
std::complex<T>* evenComponents = new std::complex<T>[n/2];
std::complex<T>* oddComponents = new std::complex<T>[n/2];
for (size_t k = 0; k < n/2; k++) {
evenComponents[k] = input[2 * k];
oddComponents[k] = input[2 * k + 1];
}
// Transform the even and odd input
FFT(evenComponents, table, n/2);
FFT(oddComponents, table, n/2);
// Use the algorithm from Danielson and Lanczos
for (size_t k = 0; k < n/2; k++) {
std::complex<T> plusMinus = table[N / n * k] * oddComponents[k]; // omega_n^k = (omega_N^(N/n))^k = omega_N^(Nk/n)
input[k] = evenComponents[k] + plusMinus;
input[k + n/2] = evenComponents[k] - plusMinus;
}
delete[] evenComponents;
delete[] oddComponents;
} else {
// The Fourier transform on one element does not do anything, so
// nothing needed here.
}
}
int main() {
std::complex<double>* input = new std::complex<double>[N];
for (size_t k = 0; k < N; k++) {
input[k] = k;
}
const std::vector< std::complex<double> > table = rootsOfUnityCalculator<double>();
// Overwrites the input with its Fourier transform
FFT<double>(input, table, N);
delete[] input;
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T03:38:10.110",
"Id": "506638",
"Score": "1",
"body": "You might also like the https://www.jjj.de/fxt/#fxtbook"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T23:27:09.383",
"Id": "506842",
"Score": "1",
"body": "\"What I can do to make this faster and more memory efficient from the programming side\" -- Truly _fast_ FFTs are several orders of magnitude faster than naive ones, and the techniques to get that performance are a better fit for a textbook than a StackExchange answer. Look at the [Halide FFT](https://github.com/halide/Halide/tree/master/apps/fft) or [FFTW](https://github.com/FFTW/fftw3) to see what goes into this.."
}
] |
[
{
"body": "<p>Prefer C++ headers (such as <code><cstdio></code>) to the C compatibility headers (<code><stdio.h></code>). The C++ headers define identifiers in the <code>std</code> namespace where we want them.</p>\n<p>It seems that this header isn't even used here, so we can omit it completely.</p>\n<hr />\n<p><code>std::size_t</code> is misspellt throughout as <code>size_t</code>. This commonly happens when writing on a platform that declares it in the global namespace as well as in <code>std</code>, but that's not a portable assumption.</p>\n<hr />\n<p>We only use <code>PI</code> as a double, so we can declare it as a constant rather than as a macro:</p>\n<pre><code>constexpr double pi = 3.14159265358979323846;\n</code></pre>\n<p>Or to make it more obviously correct:</p>\n<pre><code>const double pi = std::acos(-1.0);\n</code></pre>\n<hr />\n<p>We can avoid naked <code>new[]</code> and <code>delete[]</code> using <code>std::vector</code>. If we use <code>std::vector::reserve</code> before adding any elements, there should be no performance impact, only improved code safety.</p>\n<p>Using a vector saves having to pass the array size explicitly, too.</p>\n<hr />\n<p>A helpful technique to determine whether a number is a power of two is that bitwise-and of the number and its arithmetic predecessor is zero for powers of two:</p>\n<pre><code>constexpr bool is_power_of_two(unsigned n)\n{\n return n && (n & (n-1) == 0);\n}\n</code></pre>\n<hr />\n<p>A single value of <code>N</code> is probably not very useful in general. We could make it a template parameter, or a simple function argument, to make our code useful for other sizes of input.</p>\n<hr />\n<h1>Modified version</h1>\n<p>I split <code>FFT()</code> into a simple public function that ensures arguments are valid and the internal recursive implementation. I've used a <code>requires</code> to constrain the complex type we accept (integer types aren't useful here), but that can be omitted for plain C++17.</p>\n<pre><code>#include <complex>\n#include <vector>\n\nnamespace internal\n{\n /*\n Creating the table of all N'th roots of unity.\n We use notation ω_i = e^(-2πi/n).\n */\n template<typename U>\n constexpr auto rootsOfUnity(std::size_t n)\n {\n constexpr auto pi = std::acos(U{-1.0});\n std::vector<std::complex<U>> table;\n table.reserve(n);\n\n for (std::size_t i = 0; i < n; ++i) {\n table.emplace_back(std::cos(-2.0 * pi * i / n), std::sin(-2.0 * pi * i / n));\n }\n\n return table;\n }\n\n template<typename V> // V is vector of complex\n void FFT(V& input, const V& table, std::size_t total_size)\n {\n if (input.size() <= 1) {\n // The Fourier transform on one element does not do\n // anything, so nothing needed here.\n return;\n }\n\n const auto n2 = input.size() / 2;\n\n // Split up the input in even and odd components\n V evenComponents; evenComponents.reserve(n2);\n V oddComponents; oddComponents.reserve(n2);\n\n for (std::size_t i = 0; i < input.size(); ) {\n evenComponents.push_back(input[i++]);\n oddComponents.push_back(input[i++]);\n }\n\n // Transform the even and odd input\n FFT(evenComponents, table, total_size);\n FFT(oddComponents, table, total_size);\n\n // Use the algorithm from Danielson and Lanczos\n for (std::size_t i = 0; i < n2; ++i) {\n // ω_n^i = (ω_N^(N/n))^i = ω_N^(Nk/n)\n auto const plusMinus = table[total_size / n2 * i] * oddComponents[i];\n input[i] = evenComponents[i] + plusMinus;\n input[i + n2] = evenComponents[i] - plusMinus;\n }\n }\n}\n\n/*\n Fast Fourier transform\n T is the precision level: float, double, long double.\n Overwrites the input.\n Only works for input sizes that are a power of 2.\n*/\ntemplate<typename T>\n requires std::is_floating_point<T>\nvoid FFT(std::vector<std::complex<T>>& input)\n{\n if (input.size() == 0) {\n throw std::invalid_argument("input is empty");\n }\n if (input.size() & (input.size() - 1)) {\n throw std::invalid_argument("input length is not a power of two");\n }\n\n auto const table = internal::rootsOfUnity<T>(input.size());\n internal::FFT(input, table, input.size());\n}\n</code></pre>\n\n<pre><code>// Test program\n#include <iostream>\n\nint main()\n{\n static constexpr size_t n = 1048576;\n std::vector<std::complex<double>> input;\n for (std::size_t i = 0; i < n; ++i) {\n input.emplace_back(i);\n }\n\n // Overwrite input with its Fourier transform\n FFT<double>(input);\n\n // use the result, to avoid optimising out\n std::cout << input[0] << '\\n';\n}\n</code></pre>\n\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T19:29:21.673",
"Id": "506608",
"Score": "2",
"body": "Could you add some speed comparisons?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T19:29:32.607",
"Id": "506609",
"Score": "11",
"body": "my preference for pi has been to initialise it using `std::acos(-1.0)` since -1.0 is exactly representable and obviously correct compared to a long constant that could have a mistake hiding at a digit I don't have memorised"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T21:05:29.543",
"Id": "506616",
"Score": "3",
"body": "@kelalaka, the speed is identical to the original, to within 1 standard deviation of my measurements. I was focusing on robustness; see other answer for performance improvements."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T21:06:26.880",
"Id": "506617",
"Score": "2",
"body": "Ok, thanks for the speed share."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T09:42:12.867",
"Id": "506653",
"Score": "2",
"body": "@TobySpeight Is there a reason for `throw **new** <exception>`? Would it not simplify exception handling to omit the `new`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T09:54:24.430",
"Id": "506654",
"Score": "2",
"body": "@radioflash, I think you're right. I was getting mixed up because we always want to catch by pointer or reference (to avoid slicing). I'll change that to be more idiomatic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T10:04:35.200",
"Id": "506655",
"Score": "2",
"body": "@Flexo, yes, π should not be written as a decimal. I've updated to use `acos` with argument of the appropriate precision."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T09:31:18.227",
"Id": "506763",
"Score": "1",
"body": "I would make your `is_power_of_two` more explicit with the remainder operator. It may run slower (possibly not even), but since it is constexpr it will only do it at compile time. Right now, the purpose of the function is only given by its name (maybe obvious if you are a bitwise expert), and bit fiddling is typo-prone."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T15:12:43.900",
"Id": "506790",
"Score": "4",
"body": "C++20 *finally* has `std::numbers::pi` so we don't need to define it ourselves."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T04:54:19.457",
"Id": "506861",
"Score": "2",
"body": "@Flexo: it's not guaranteed that `std::acos(-1.0)` returns a correctly-rounded result; i.e. it might have more than 0.5ulp of rounding error. (Although a global constexpr should encourage the compiler to do constant-propagation through it, hopefully with more accuracy than the actual library function, so maybe it works well in practice.) Fortunately C++20 has https://en.cppreference.com/w/cpp/numeric/constants, but without that I'd be inclined to write Pi as decimal digits. (Especially if you know them by heart or copy/paste to reduce chance of error.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T05:04:27.227",
"Id": "506862",
"Score": "2",
"body": "@Flexo: just tried it: https://godbolt.org/z/z63Gs5 with `constexpr double pi = std::acos(-1.0);` at local or global scope, clang complains that it isn't a constant expression. Even with optimization enabled and `-std=gnu++17`, with libstdc++ or libc++. Also, with optimization disabled, `const double pi = std::acos(-1.0)` at global scope does call acos at runtime, using clang: https://godbolt.org/z/s73hGG"
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T11:55:28.957",
"Id": "256567",
"ParentId": "256565",
"Score": "18"
}
},
{
"body": "<h1>Avoid excessive memory usage</h1>\n<p>At each step of the recursion, you allocate two arrays that together are as large as the input. That means that your algorithm uses <span class=\"math-container\">\\$\\mathcal{O}(N \\log N)\\$</span> space. It should be possible to rewrite your code so you only use <span class=\"math-container\">\\$\\mathcal{O}(N)\\$</span> space without substantially changing the algorithm. But this also brings me to:</p>\n<h1>In-place vs. out-of-place algorithms</h1>\n<p>While the function signature makes it looks like you are doing an in-place FFT transform, you are actually doing an out-of-place transform (using extra memory), and then copying the result back into the input array. However, there are also real <a href=\"https://en.wikipedia.org/wiki/Cooley%E2%80%93Tukey_FFT_algorithm#Data_reordering,_bit_reversal,_and_in-place_algorithms\" rel=\"noreferrer\">in-place FFT algorithms</a> that, apart from a few variables, do not need any extra memory, and by their nature overwrite the input array. This means they use only <span class=\"math-container\">\\$\\mathcal{O}(1)\\$</span> memory. The drawback of the in-place algorithms is that the transformed data is not in the order you expect; you might have to use a bit-reversed index to access the data. However, for some applications this doesn't matter at all, for example if you perform convolutions using FFT.</p>\n<p>If you do use an out-of-place algorithm then I suggest you make this explicit, and either return a <code>std::vector</code> with the results, or add a parameter to the function that tells it where to store the results.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T14:05:15.947",
"Id": "506785",
"Score": "0",
"body": "It's ironic that the in-place algorithms may leave the output in an order you do not expect -- i.e. not in it's place !"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T13:53:25.103",
"Id": "256571",
"ParentId": "256565",
"Score": "15"
}
},
{
"body": "<p><strong>Use <code>unique_ptr</code> instead of <code>new[]</code>/<code>delete[]</code></strong></p>\n<pre><code>std::complex<double>* input = new std::complex<double>[N];\n\n...\n\ndelete[] input;\n</code></pre>\n<p>This line can be replaced by appropriate use of <code>std::unique_ptr</code>:</p>\n<pre><code>auto input_storage = std::make_unique<std::complex<double>[]>(N); // #include <memory>\nstd::complex<double>* input = input_storage.get();\n</code></pre>\n<p>The memory is automatically reclaimed once <code>input_storage</code> goes out of scope.</p>\n<p>I originally suggested <code>unique_ptr</code> here because it's the moral equivalent of your code (has identical run-time behavior), but there are other options that might be more suitable for your situation:</p>\n<ul>\n<li><p><code>std::vector<T></code> (referenced in <a href=\"https://codereview.stackexchange.com/a/256567\">another answer</a>):</p>\n<ul>\n<li><p>More flexible than <code>unique_ptr<T[]></code> since you can <code>resize</code> and <code>push_back</code>.</p>\n</li>\n<li><p>Keeps track of its own length and capacity, unlike <code>unique_ptr<T[]></code> where you need to store the length as a separate variable. Hence, less error-prone, but more memory footprint (not likely to matter unless you have lots of <code>vector</code>s).</p>\n</li>\n</ul>\n</li>\n<li><p><code>std::array<T, N></code>: This is similar to a C-style array <code>T[N]</code>, but offers an <a href=\"https://en.cppreference.com/w/cpp/container/array\" rel=\"noreferrer\">API more consistent with other C++ containers</a>. It shares some of the same limitations as C-style arrays though:</p>\n<ul>\n<li><p>A crucial limitation is that the length has to be known at compile-time (<code>constexpr</code> or <code>static const</code>), whereas both <code>unique_ptr<T[]></code> and <code>vector</code> accept lengths at run time.</p>\n</li>\n<li><p>A large <code>array<T, N></code> allocated on the stack can overflow the stack, so you generally want to keep <code>N</code> rather small, or use a smart pointer to <code>std::array</code>.</p>\n</li>\n</ul>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T23:07:10.750",
"Id": "256596",
"ParentId": "256565",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "256571",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T10:52:39.033",
"Id": "256565",
"Score": "15",
"Tags": [
"c++",
"performance",
"beginner",
"c++17"
],
"Title": "C++ Fast Fourier transform"
}
|
256565
|
<p>I'm trying to build an extension method that will allow me to subdivide a huge array into much smaller ones. My current code is the following but it still takes about 2s to generate with an array of size 512x512x512 and the size of the sub cubes set to 32x32x32</p>
<pre><code>public static T[][][][] Divide<T>(this T[][][] array, int xSize, int ySize, int zSize)
{
int numberOfCubesInAxisX = array.Length / xSize;
int numberOfCubesInAxisY = array[0].Length / ySize;
int numberOfCubesInAxisZ = array[0][0].Length / zSize;
T[][][][] arrayDivided = new T[numberOfCubesInAxisX * numberOfCubesInAxisY * numberOfCubesInAxisZ][][][];
int index = 0;
while (index < arrayDivided.Length)
{
int xIndex = index / numberOfCubesInAxisZ / numberOfCubesInAxisX;
int yIndex = index / numberOfCubesInAxisZ % numberOfCubesInAxisY;
int zIndex = index % numberOfCubesInAxisZ;
arrayDivided[index] = new T[xSize][][];
for (int x = 0; x < xSize; x++)
{
arrayDivided[index][x] = new T[ySize][];
for (int y = 0; y < ySize; y++)
{
arrayDivided[index][x][y] = new T[zSize];
for (int z = 0; z < zSize; z++)
{
arrayDivided[index][x][y][z] = array[x + (xIndex * xSize)][y + (yIndex * ySize)][z + (zIndex * zSize)];
}
}
}
index++;
}
return arrayDivided;
}
</code></pre>
<p>If anyone have any clue on how to optimize it, i'll be glad to hear it!
Thanks!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T15:24:26.283",
"Id": "506563",
"Score": "0",
"body": "I have rolled back your latest edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T18:08:47.513",
"Id": "506592",
"Score": "0",
"body": "Jagged array is slow choice. I would like multi-dimentional one. `[,,,]` instead of `[][][]` for each cube. Additionally a pair of some math and `Array.Copy` calls will do the magic. Also `Buffer.BlockCopy` is the fastest for non-generic primitive-typed solution. Potentially you can speed up this by ~100 times."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T18:34:38.520",
"Id": "506600",
"Score": "0",
"body": "@aepot i have hard time knowing if jagged array are faster or not than multi-dimensional. Multiple link tell me otherwise (https://stackoverflow.com/questions/597720/what-are-the-differences-between-a-multidimensional-array-and-an-array-of-arrays) and testing it on Unity (so with Mono) show me that jagged array are faster.\nRegarding Buffer.BlockCopy, i was currently looking into it and i think i can remove completly the z loop but the other one will be tough to delete..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T18:37:47.577",
"Id": "506601",
"Score": "0",
"body": "For `T` you can't use `Buffer.BlockCopy` but can `Array.Copy`. First copies array segment only as bytes thus you must know the exact item size in bytes. `Array.Copy` will do it for `T` fluently, a bit slower but a payment for Generic method nature."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T18:50:04.090",
"Id": "506603",
"Score": "0",
"body": "About \"slow\" multi-dimentional array. Yes it can be slower to retreive an element while you iteration in one row but if yu want to copy a memory, the single-dimentional array will be rather faster as it provides solid memory area while. In other words if i want to copu 3xJagged, i go throug 2 loops. If I want to copy X-dimentional array, I call single `Buffer.BlockCopy` operation. For large data set single-dimentional array is best choice. Because calculating item address like `x * ySize * zSize + y * zSize + z` is always faster than go through 3 index-bound-checks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T18:51:45.890",
"Id": "506605",
"Score": "0",
"body": "... Write own `Matrix3d` class with single-dimentional array as underlying storage and test the performance."
}
] |
[
{
"body": "<p>Just a quick shot regarding performance.....</p>\n<p>The code is calculating</p>\n<p><code>xIndex * xSize</code> <code>xSize*ySize*zSize</code> times<br />\n<code>yIndex * ySize</code> <code>xSize*ySize*zSize</code> times<br />\n<code>zIndex * zSize</code> <code>xSize*ySize*zSize</code> times</p>\n<p>while it only should be calculated once for each iteration of the <code>while</code> loop.</p>\n<p>In addition, <code>x</code> only changes in the first <code>for</code> loop and <code>y</code> only changes in the second <code>for</code> loop.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T15:18:26.803",
"Id": "506562",
"Score": "0",
"body": "Hi, thanks for the tip, i've indeed changed the code a little bit. The result is not an astronomical gain in time but it's a small good upgrade. Thanks for the tip."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T14:55:09.930",
"Id": "256574",
"ParentId": "256569",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T12:55:09.597",
"Id": "256569",
"Score": "0",
"Tags": [
"c#",
"matrix",
"generics"
],
"Title": "Divide a 3D matrix into multiple smaller 3D matrix"
}
|
256569
|
<p>Wondering about efficiency here - I have a bit of code that does what I want; but it is terribly slow. I structured the code in a way that made sense to me logically, but I'm wondering if someone else could take a look at the code and find a shortcut or two that might make it faster. I'm guessing that I am referencing the Worksheet too often in one of the loops, but haven't been able to find a good way to restructure to improve performance.</p>
<p>What is it doing: Each row contains a record with a single ID, Name, etc. on the row. There are also multiple response items that work together and those are basically a table or array that is 9 columns wide and however many rows tall based on the current Alternate Logic in the table. So if a single record has 2 types of alternate logic at the beginning, the array would be (1 to 9, 1 to 2) or I guess (0 to 8, 0 to 1). I'm basically looking for a specific row in the existing table and then adding new lines. So when I'm done, I expect the array to be taller by at least one more row.</p>
<p>Why are we doing it? Each record is a charge code for a hospital, and the charge codes have a default Revenue Code, but depending on the cost center or payer - an alternate Revenue Code may be needed. I need to copy all lines where a specific cost center is used to identify alternate Revenue Codes and then copy that existing data and add my new line(s) where the only change on the new lines from the source line is the cost center ID itself.</p>
<pre><code>Option Explicit
Sub addAlternateRevCodeLogic()
Dim WS As Worksheet
Dim rng As Range
Dim lastColumn As Long
Dim row As Long
Dim i As Long
Dim ReferenceStyle As XlReferenceStyle
'Arrays of the different Alt Rev Code fields on an EAP
Dim AltID() As String
Dim EffFrom() As String
Dim EffTo() As String
Dim ProvType() As String
Dim BCC() As String
Dim DEP() As String
Dim EAF() As String
Dim Class() As String
Dim RevCode() As String
'Alt Rev Code data from the matching rows
Dim rowAltID As String
Dim rowEffFrom As String
Dim rowEffTo As String
Dim rowProvType As String
Dim rowBCC As String
Dim rowDEP As String
Dim rowEAF As String
Dim rowClass As String
Dim rowRevCode As String
'New and old cost centers
Dim newBCC() As String
Dim oldBCC As String
Dim CostCenter As Variant
Dim userInput As String
'Columns for Rev Code Ranges
Dim AltIDcol As Long 'I EAP 2431
Dim EffFromcol As Long 'I EAP 2434
Dim EffTocol As Long 'I EAP 2435
Dim ProvTypecol As Long 'I EAP 2439
Dim BCCcol As Long 'I EAP 2438
Dim DEPcol As Long 'I EAP 2437
Dim EAFcol As Long 'I EAP 2436
Dim Classcol As Long 'I EAP 2432
Dim RevCodecol As Long 'I EAP 2433
Application.ScreenUpdating = False
ReferenceStyle = Application.ReferenceStyle
If ReferenceStyle = xlR1C1 Then Application.ReferenceStyle = xlA1 'There are certain assumptions in the ranges that don't play nicely with R1C1
'Data is Chr(10) delimited
'Define the range of the EAP Export
Set WS = Worksheets("export")
lastColumn = eap.Cells.Find("*", After:=eap.Cells(1), LookIn:=xlValues, LookAt:=xlWhole, SearchDirection:=xlPrevious, SearchOrder:=xlByColumns).Column
Set rng = WS.Range("A1", WS.Columns(1).Find(what:="#LAST_ROW", LookIn:=xlComments, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False).Offset(0, lastColumn))
'Define all of the column IDs
AltIDcol = FindCol(2431, eap, True, 1, 1, 1, lastColumn)
EffFromcol = FindCol(2434, eap, True, 1, 1, 1, lastColumn)
EffTocol = FindCol(2435, eap, True, 1, 1, 1, lastColumn)
ProvTypecol = FindCol(2439, eap, True, 1, 1, 1, lastColumn)
BCCcol = FindCol(2438, eap, True, 1, 1, 1, lastColumn)
DEPcol = FindCol(2437, eap, True, 1, 1, 1, lastColumn)
EAFcol = FindCol(2436, eap, True, 1, 1, 1, lastColumn)
Classcol = FindCol(2432, eap, True, 1, 1, 1, lastColumn)
RevCodecol = FindCol(2433, eap, True, 1, 1, 1, lastColumn)
oldBCC = InputBox("What cost center do you want to copy?" & vbNewLine & "Select only one, and don't make typos")
If oldBCC = "" Then MsgBox "Must choose a cost center!", vbOKOnly + vbCritical: Exit Sub
Do
userInput = InputBox("What are the new cost centers that need added?" & vbNewLine & "You can enter multiple, just keep adding them and then leave the box blank after the last one" & vbNewLine & "Don't make typos", "New Cost Centers")
Select Case True
Case CostCenter = "" And userInput <> "" 'Handle the 1st cost center
CostCenter = userInput
Case CostCenter <> "" And userInput <> "" 'Handle each new input
CostCenter = CostCenter & "," & userInput
Case CostCenter = "" And userInput = "" 'Handle no input
MsgBox "Must choose at least one new cost center!", vbOKOnly + vbCritical: Exit Sub
End Select
Loop While userInput <> ""
'oldBCC = "10005320" 'Test Emergency Cost Center
'oldBCC = "10004320" 'Test Pediatrics Cost Center
'CostCenter = "70005320" 'Test New Emergency Cost Center
'CostCenter = "70004110,70004130,70004140,70004200,70004420,70004510,70004400,70004430,70004500" 'Test New Pediatrics Cost Centers
newBCC() = Split(CostCenter, ",")
With rng
For row = LBound(.Value2) To UBound(.Value2) 'Loop through each row from the export
If Not IsEmpty(.Value2(row, RevCodecol)) Then 'Find any row that contains an alternate revenue code
If InStr(1, .Value2(row, BCCcol), oldBCC) Then 'Check if the TRH Emergency Cost Center is using one of the alternate revenue codes
'Build an array for each Alt Rev Code data item
RevCode() = Split(.Value2(row, RevCodecol), Chr(10))
AltID() = Split(.Value2(row, AltIDcol), Chr(10))
EffFrom() = Split(.Value2(row, EffFromcol), Chr(10))
EffTo() = Split(.Value2(row, EffTocol), Chr(10))
ProvType() = Split(.Value2(row, ProvTypecol), Chr(10))
BCC() = Split(.Value2(row, BCCcol), Chr(10))
DEP() = Split(.Value2(row, DEPcol), Chr(10))
EAF() = Split(.Value2(row, EAFcol), Chr(10))
Class() = Split(.Value2(row, Classcol), Chr(10))
For i = LBound(RevCode()) To UBound(RevCode())
If InStr(1, BCC(i), oldBCC) Then 'Set row data for a line with the cost center to copy
rowAltID = AltID(i)
rowEffFrom = EffFrom(i)
rowEffTo = EffTo(i)
rowProvType = ProvType(i)
rowBCC = BCC(i)
rowDEP = DEP(i)
rowEAF = EAF(i)
rowClass = Class(i)
rowRevCode = RevCode(i)
'Copy the existing value and add the new line(s)
For Each CostCenter In newBCC 'Copy existing lines and add a new entry for each new cost center
.Cells(row, AltIDcol).Value = .Value2(row, AltIDcol) & Chr(10) & rowAltID ' & Chr(10)
.Cells(row, EffFromcol).Value = .Value2(row, EffFromcol) & Chr(10) & rowEffFrom ' & Chr(10)
.Cells(row, EffTocol).Value = .Value2(row, EffTocol) & Chr(10) & rowEffTo ' & Chr(10)
.Cells(row, ProvTypecol).Value = .Value2(row, ProvTypecol) & Chr(10) & rowProvType ' & Chr(10)
.Cells(row, BCCcol).Value = .Value2(row, BCCcol) & Chr(10) & CostCenter ' & Chr(10)
.Cells(row, DEPcol).Value = .Value2(row, DEPcol) & Chr(10) & rowDEP ' & Chr(10)
.Cells(row, EAFcol).Value = .Value2(row, EAFcol) & Chr(10) & rowEAF ' & Chr(10)
.Cells(row, Classcol).Value = .Value2(row, Classcol) & Chr(10) & rowClass ' & Chr(10)
.Cells(row, RevCodecol).Value = .Value2(row, RevCodecol) & Chr(10) & rowRevCode ' & Chr(10)
Next CostCenter
End If
Next i
End If
End If
Next row
End With
If ReferenceStyle = xlR1C1 Then Application.ReferenceStyle = xlR1C1
Application.ScreenUpdating = True
MsgBox "Rev Codes updated. Test the import.", vbInformation + vbOKOnly
End Sub
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T14:56:07.270",
"Id": "506560",
"Score": "1",
"body": "Welcome to the Code Review Community. We need some background details. How much data is being processed? Please quantify `terribly slow`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T16:00:09.857",
"Id": "506568",
"Score": "0",
"body": "You need to explain better what your code is trying to do in a fair bit of detail rather than just dumping code here and expecting us to fathom its working. You should also take the time to update your code with more meaningful and user friendly variable names. At present, your code is fairly impenetrable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T16:27:51.863",
"Id": "506573",
"Score": "0",
"body": "1. Terribly slow is several minutes for about 900 rows in a spreadsheet.\n2. Wasn't a fan of pasting the code in initially, but let's say I get rid of most of the code block and just provide an example - would that suffice? I found that saying in words what I was trying to do was difficult and there was a not that \"The more code you share, the better\" so I went big"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T16:36:34.133",
"Id": "506575",
"Score": "1",
"body": "If you can't explain what you want to do simply and succinctly there's little chance of being able to write decent code as typically the inability to explain is linked to a lack of understanding about what is required and how to translate the requirement into code. So please, for now, just focus on clearly and succinctly explaining what it is you are trying to achieve."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T09:49:06.740",
"Id": "506765",
"Score": "1",
"body": "Hi, don't worry lots of code is good, we need all the info we can get! Indeed you haven't included the `FindCol` function and I'm guessing `eap` is your worksheet's code name because I can't see it defined anywhere, but do confirm? In terms of extra context, it would be useful to include a sample of the data to see if its structure yields some insight. As it stands this is doing much more than just _copying data from one place to another adding newlines_ so if you could explain that in more detail, the _why_ of your code, it would help people understand it to give useful feedback."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T15:30:07.967",
"Id": "507756",
"Score": "0",
"body": "Findcol is a borrowed function that finds a column given a header, pretty basic. EAP export is the sheet's actual name, I might have tweaked the code before uploading it so it might not be 100% right actually, I'll fix that in the question when I get a chance."
}
] |
[
{
"body": "<p>You are right in what you are thinking: reading from and writing to the worksheet is <a href=\"https://stackoverflow.com/a/30880184/6351539\">notoriously slow</a>.</p>\n<p>Without doing anything else, you will probably get a significant performance boost just from turning Calculation off at the same place in your code where you are turning ScreenUpdating on and off:</p>\n<pre><code> 'Variable Declarations\n\nApplication.ScreenUpdating = False\nApplication.Calculation = xlCalculationManual\n\n 'The rest of your code here\n\nApplication.Calculation = xlAutomatic\nApplication.ScreenUpdating = True\n</code></pre>\n<p>It would be so much easier if each existing cost center was on its own row instead of having many in each! We'll just assume that you don't have any control over this and commiserate with you :)</p>\n<p>Each time your code finds the user-input old cost code in the BCCcol column, it copies the old cost code details in that row. Then it appends the cells in that row with the new cost code(s) and those copied details.</p>\n<p>If you were to use one of your commented test examples:</p>\n<pre><code>'oldBCC = "10004320" 'Test Pediatrics Cost Center\n'CostCenter = "70004110,70004130,70004140,70004200,70004420,70004510,70004400,70004430,70004500" 'Test New Pediatrics Cost Centers\n</code></pre>\n<p>There are nine new cost centers in CostCenter, so each time your code finds oldBCC in a row, it appends the cells in that row nine times. There are nine cells to append each time, so that's 81 separate writes to the worksheet for each row where there is a match. This will be slow.</p>\n<p>There <em>must</em> be a better way to go than splitting each relevant cell into its own little array, but I'm going to leave that for someone more experienced that me.</p>\n<p>I'm not sure your row string variables are adding much benefit either (e.g. rowAltID). I think the code for appending the new cost centers would be just as easy to read without them (but I also don't think they're slowing your code down much).</p>\n<p>If you were to write each cell's new value to a string variable and then only update the cells in the row with the new string variables once at the end you should see another large improvement. I'll use the AltID column as an example:</p>\n<pre><code>Dim newAltID As String\n\n '...string declarations for the other cells go here...\n\n '...then other initial code as before...\n\nFor i = LBound(RevCode()) To UBound(RevCode())\n\n If InStr(1, BCC(i), oldBCC) Then 'Set row data for a line with the cost center to copy\n \n 'Put the existing cell values into their string variables\n newAltID = .Cells(row, AltIDcol).Value\n\n '...continue for the other cell's strings\n\n \n For Each CostCenter In newBCC 'Add a new entry for each new cost center\n\n newAltID = newAltID & Chr(10) & AltID(i)\n 'or newAltID = newAltID & Chr(10) & rowAltID \n\n '...continue for the other cell's strings\n\n Next CostCenter\n\n 'Then write the appended strings back to the worksheet once at the end\n .Cells(row, AltIDcol).Value = newAltID\n\n '...continue for the other cell's strings\n\n End If\n\nNext i\n</code></pre>\n<p>Edit: removed personal opinion where it was unnecessary.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T15:25:47.810",
"Id": "507755",
"Score": "0",
"body": "Thanks for the insight, I don't have a spreadsheet handy at the moment, but I'll update my question with an example to help visualize. I do technically have the option to split the data to different rows rather than Chr(10) delimited, but it adds a bit of extra complexity I wanted to avoid, especially the fact that insert row is going to be slow. This is really helpful though and I realize now that the main drag is the writing part, so I'm thinking about saving the source data into a variant array variable, making all updates in a new array, and then writing the entire array at once-Copy/paste"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T08:38:19.813",
"Id": "257055",
"ParentId": "256570",
"Score": "1"
}
},
{
"body": "<p>Ok i'll try have a crack it with the info you've given...\nthe code isnt going to be elegant but i've tried my best. I cant check if the code works since i dont have the full code / sheet you've provided.</p>\n<p>If you are not interested in how it all works go to the bottom of the post and you'll see the full code combined together. just copy and paste and see if it works!</p>\n<p>As a few of the answers mentioned commincating with a sheet can be extremely slow (especially if you've got calculations on at the same time).</p>\n<p>At the start of your code i would recommond:</p>\n<pre><code>Application.ScreenUpdating = True '**** see below\nApplication.Calculation = xlCalculationManual\n\n' if your code errors and produces a pop up this can cause your excel to crash i prefer to keep this until you are well versed with how VBA works\n' if your code is fully using arrays then screen updating usually provides a negligible benefit\n' if you are unfamiliar with using arrays i suggest finalising your code and then turning it off\n</code></pre>\n<p>At the end of your code i would recommond:</p>\n<pre><code>Application.ScreenUpdating = True \nApplication.Calculation = xlCalculationAutomatic\n</code></pre>\n<p>Method:</p>\n<ol>\n<li>Loop through the data (as an array this time and not a range)</li>\n<li>Find out the size of the new insert</li>\n<li>Loop through the data again this time into the array</li>\n<li>paste the data at the bottom of the sheet</li>\n</ol>\n<p>Looping through an array twice should still be 100x (dont quote me) faster.</p>\n<p>I've made two assumptions:</p>\n<ol>\n<li>The section of code below gets the data from the sheet called "export" with column one being the master column (the one if you go to the end it shows the last row)</li>\n<li>You paste the data back into the 'Export' sheet at the bottom of the page to the next line.</li>\n</ol>\n<p>for point 1 - i've replaced the following code:</p>\n<pre><code>set WS = Worksheets("export")\nlastColumn = eap.Cells.Find("*", After:=eap.Cells(1), LookIn:=xlValues, LookAt:=xlWhole, SearchDirection:=xlPrevious, SearchOrder:=xlByColumns).Column\nSet rng = WS.Range("A1", WS.Columns(1).Find(what:="#LAST_ROW", LookIn:=xlComments, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False).Offset(0, lastColumn))\n</code></pre>\n<hr />\n<p>with:</p>\n<pre><code>Dim arr() As Variant\narr() = GetArr("export")\n</code></pre>\n<hr />\n<p>for point 2 - i've added the following code at the end:</p>\n<pre><code>PasteArr "export", arrNew, 1, False, True\n</code></pre>\n<hr />\n<p>I've added two functions:\none to get the array from the sheet, one to paste the array to the sheet</p>\n<hr />\n<pre><code>'------- ---------------------- ---------\n'------- Get Data into an Array ---------\n'------- ---------------------- ---------\n\nFunction GetArr(SheetName As String, Optional ColumnForSize As Long = 1, Optional Rowstart As Long = 1)\n\nDim ws As Worksheet\nDim vArray() As Variant\n\nOn Error GoTo ErrH\n Set ws = ThisWorkbook.Sheets(SheetName): On Error GoTo 0\n \nWith ws\n If .FilterMode = True Then .ShowAllData\n lRow = .Cells(.Rows.Count, ColumnForSize).End(xlUp).row\n lCol = .Cells(1, .Columns.Count).End(xlToLeft).Column\n If lRow > 1 Or lCol > 1 Then\n vArray() = .Cells(Rowstart, 1).Resize(lRow - Rowstart + 1, lCol).Value2\n GetArr = vArray()\n End If\nEnd With\n\nEndFunction:\nExit Function\n\nErrH:\nDebug.Print "Worksheet name '" & SheetName & "' not found."\nResume EndFunction\n\nEnd Function\n\n\n\n'------- -------------------- ---------\n'------- Paste Array to Sheet ---------\n'------- -------------------- ---------\n\nFunction PasteArr(SheetName As String, vArray() As Variant, Optional ColumnForSize As Long = 1, Optional bClearContents As Boolean = True, Optional bLastRow As Boolean, Optional bOmitFirstRow As Boolean)\n\nDim ws As Worksheet\n\nOn Error GoTo ErrH\n Set ws = ThisWorkbook.Sheets(SheetName): On Error GoTo 0\n\nx = 0\n\nWith ws\n If .FilterMode = True Then .ShowAllData\n If bClearContents Then\n lRow = .Cells(.Rows.Count, ColumnForSize).End(xlUp).row\n lCol = .Cells(1, .Columns.Count).End(xlToLeft).Column\n If lRow > 1 Then .Cells(1, 1).Resize(lRow, lCol).ClearContents\n End If\n If bOmitFirstRow Then\n For i = LBound(vArray, 2) To UBound(vArray, 2)\n vArray(LBound(vArray), i) = vArray(UBound(vArray), i)\n vArray(UBound(vArray), i) = ""\n Next\n x = 1\n End If\n If Not (Not vArray()) Then\n If bLastRow Then\n lRow = .Cells(.Rows.Count, ColumnForSize).End(xlUp).row + 1\n .Cells(lRow, 1).Resize(UBound(vArray) - x, UBound(vArray, 2)) = vArray()\n Else\n .Cells(1, 1).Resize(UBound(vArray) - x, UBound(vArray, 2)) = vArray()\n End If\n End If\nEnd With\n\n\nEndFunction:\nExit Function\n\nErrH:\nDebug.Print "Worksheet name '" & SheetName & "' not found."\nResume EndFunction\n\nEnd Function\n</code></pre>\n<hr />\n<p>Packaging all the above comments together this is what it looks like:</p>\n<hr />\n<pre><code>Option Base 1\n\nSub addAlternateRevCodeLogic()\n\nApplication.ScreenUpdating = True\nApplication.Calculation = xlCalculationManual\n\nDim ws As Worksheet\nDim rng As Range\nDim lastColumn As Long\nDim row As Long\nDim i As Long\n\nDim ReferenceStyle As XlReferenceStyle\n\n'Arrays of the different Alt Rev Code fields on an EAP\nDim AltID() As String\nDim EffFrom() As String\nDim EffTo() As String\nDim ProvType() As String\nDim BCC() As String\nDim DEP() As String\nDim EAF() As String\nDim Class() As String\nDim RevCode() As String\n\n\n'Alt Rev Code data from the matching rows\nDim rowAltID As String\nDim rowEffFrom As String\nDim rowEffTo As String\nDim rowProvType As String\nDim rowBCC As String\nDim rowDEP As String\nDim rowEAF As String\nDim rowClass As String\nDim rowRevCode As String\n\n'New and old cost centers\nDim newBCC() As String\nDim oldBCC As String\nDim CostCenter As Variant\nDim userInput As String\n\n'Columns for Rev Code Ranges\nDim AltIDcol As Long 'I EAP 2431\nDim EffFromcol As Long 'I EAP 2434\nDim EffTocol As Long 'I EAP 2435\nDim ProvTypecol As Long 'I EAP 2439\nDim BCCcol As Long 'I EAP 2438\nDim DEPcol As Long 'I EAP 2437\nDim EAFcol As Long 'I EAP 2436\nDim Classcol As Long 'I EAP 2432\nDim RevCodecol As Long 'I EAP 2433\n\n'Application.ScreenUpdating = False\nReferenceStyle = Application.ReferenceStyle\nIf ReferenceStyle = xlR1C1 Then Application.ReferenceStyle = xlA1 'There are certain assumptions in the ranges that don't play nicely with R1C1\n\n'Data is Chr(10) delimited\n'Define the range of the EAP Export\nDim arr() As Variant\nDim arrNew() As Variant\narr() = GetArr("export")\n\n\n'Define all of the column IDs\nAltIDcol = FindCol(2431, eap, True, 1, 1, 1, lastColumn)\nEffFromcol = FindCol(2434, eap, True, 1, 1, 1, lastColumn)\nEffTocol = FindCol(2435, eap, True, 1, 1, 1, lastColumn)\nProvTypecol = FindCol(2439, eap, True, 1, 1, 1, lastColumn)\nBCCcol = FindCol(2438, eap, True, 1, 1, 1, lastColumn)\nDEPcol = FindCol(2437, eap, True, 1, 1, 1, lastColumn)\nEAFcol = FindCol(2436, eap, True, 1, 1, 1, lastColumn)\nClasscol = FindCol(2432, eap, True, 1, 1, 1, lastColumn)\nRevCodecol = FindCol(2433, eap, True, 1, 1, 1, lastColumn)\n\noldBCC = InputBox("What cost center do you want to copy?" & vbNewLine & "Select only one, and don't make typos")\nIf oldBCC = "" Then MsgBox "Must choose a cost center!", vbOKOnly + vbCritical: Exit Sub\n\nDo\n userInput = InputBox("What are the new cost centers that need added?" & vbNewLine & "You can enter multiple, just keep adding them and then leave the box blank after the last one" & vbNewLine & "Don't make typos", "New Cost Centers")\n Select Case True\n Case CostCenter = "" And userInput <> "" 'Handle the 1st cost center\n CostCenter = userInput\n Case CostCenter <> "" And userInput <> "" 'Handle each new input\n CostCenter = CostCenter & "," & userInput\n Case CostCenter = "" And userInput = "" 'Handle no input\n MsgBox "Must choose at least one new cost center!", vbOKOnly + vbCritical: Exit Sub\n End Select\nLoop While userInput <> ""\n\n'oldBCC = "10005320" 'Test Emergency Cost Center\n'oldBCC = "10004320" 'Test Pediatrics Cost Center\n'CostCenter = "70005320" 'Test New Emergency Cost Center\n'CostCenter = "70004110,70004130,70004140,70004200,70004420,70004510,70004400,70004430,70004500" 'Test New Pediatrics Cost Centers\nnewBCC() = Split(CostCenter, ",")\n\nxCounter = 0\nFor row = LBound(arr) To UBound(arr) 'Loop through each row from the export\n If Not IsEmpty(arr(row, RevCodecol)) Then 'Find any row that contains an alternate revenue code\n If InStr(1, arr(row, BCCcol), oldBCC) Then 'Check if the TRH Emergency Cost Center is using one of the alternate revenue codes\n 'Build an array for each Alt Rev Code data item\n RevCode() = Split(arr(row, RevCodecol), Chr(10))\n AltID() = Split(arr(row, AltIDcol), Chr(10))\n EffFrom() = Split(arr(row, EffFromcol), Chr(10))\n EffTo() = Split(arr(row, EffTocol), Chr(10))\n ProvType() = Split(arr(row, ProvTypecol), Chr(10))\n BCC() = Split(arr(row, BCCcol), Chr(10))\n DEP() = Split(arr(row, DEPcol), Chr(10))\n EAF() = Split(arr(row, EAFcol), Chr(10))\n Class() = Split(arr(row, Classcol), Chr(10))\n For i = LBound(RevCode()) To UBound(RevCode())\n If InStr(1, BCC(i), oldBCC) Then 'Set row data for a line with the cost center to copy\n rowAltID = AltID(i)\n rowEffFrom = EffFrom(i)\n rowEffTo = EffTo(i)\n rowProvType = ProvType(i)\n rowBCC = BCC(i)\n rowDEP = DEP(i)\n rowEAF = EAF(i)\n rowClass = Class(i)\n rowRevCode = RevCode(i)\n 'Copy the existing value and add the new line(s)\n For Each CostCenter In newBCC 'Copy existing lines and add a new entry for each new cost center\n xCounter = xCounter = 1\n Next CostCenter\n End If\n Next i\n End If\n End If\nNext\n\nIf xCounter > 0 Then\n ReDim arrNew(xCounter, UBound(arr, 2))\n xCounter = 0\n For row = LBound(arr) To UBound(arr) 'Loop through each row from the export\n If Not IsEmpty(arr(row, RevCodecol)) Then 'Find any row that contains an alternate revenue code\n If InStr(1, arr(row, BCCcol), oldBCC) Then 'Check if the TRH Emergency Cost Center is using one of the alternate revenue codes\n 'Build an array for each Alt Rev Code data item\n RevCode() = Split(arr(row, RevCodecol), Chr(10))\n AltID() = Split(arr(row, AltIDcol), Chr(10))\n EffFrom() = Split(arr(row, EffFromcol), Chr(10))\n EffTo() = Split(arr(row, EffTocol), Chr(10))\n ProvType() = Split(arr(row, ProvTypecol), Chr(10))\n BCC() = Split(arr(row, BCCcol), Chr(10))\n DEP() = Split(arr(row, DEPcol), Chr(10))\n EAF() = Split(arr(row, EAFcol), Chr(10))\n Class() = Split(arr(row, Classcol), Chr(10))\n For i = LBound(RevCode()) To UBound(RevCode())\n If InStr(1, BCC(i), oldBCC) Then 'Set row data for a line with the cost center to copy\n rowAltID = AltID(i)\n rowEffFrom = EffFrom(i)\n rowEffTo = EffTo(i)\n rowProvType = ProvType(i)\n rowBCC = BCC(i)\n rowDEP = DEP(i)\n rowEAF = EAF(i)\n rowClass = Class(i)\n rowRevCode = RevCode(i)\n 'Copy the existing value and add the new line(s)\n For Each CostCenter In newBCC 'Copy existing lines and add a new entry for each new cost center\n xCounter = xCounter = 1\n arrNew(xCounter, AltIDcol).Value = arr(row, AltIDcol) & Chr(10) & rowAltID ' & Chr(10)\n arrNew(xCounter, EffFromcol).Value = arr(row, EffFromcol) & Chr(10) & rowEffFrom ' & Chr(10)\n arrNew(xCounter, EffTocol).Value = arr(row, EffTocol) & Chr(10) & rowEffTo ' & Chr(10)\n arrNew(xCounter, ProvTypecol).Value = arr(row, ProvTypecol) & Chr(10) & rowProvType ' & Chr(10)\n arrNew(xCounter, BCCcol).Value = arr(row, BCCcol) & Chr(10) & CostCenter ' & Chr(10)\n arrNew(xCounter, DEPcol).Value = arr(row, DEPcol) & Chr(10) & rowDEP ' & Chr(10)\n arrNew(xCounter, EAFcol).Value = arr(row, EAFcol) & Chr(10) & rowEAF ' & Chr(10)\n arrNew(xCounter, Classcol).Value = arr(row, Classcol) & Chr(10) & rowClass ' & Chr(10)\n arrNew(xCounter, RevCodecol).Value = arr(row, RevCodecol) & Chr(10) & rowRevCode ' & Chr(10)\n Next CostCenter\n End If\n Next i\n End If\n End If\n Next\nEnd If\n\n\nPasteArr "export", arrNew, 1, False, True\n\nApplication.Calculation = xlCalculationAutomatic\n\nIf ReferenceStyle = xlR1C1 Then Application.ReferenceStyle = xlR1C1\nApplication.ScreenUpdating = True\nMsgBox "Rev Codes updated. Test the import.", vbInformation + vbOKOnly\n\nEnd Sub\n\n\n'------- ---------------------- ---------\n'------- Get Data into an Array ---------\n'------- ---------------------- ---------\n\nFunction GetArr(SheetName As String, Optional ColumnForSize As Long = 1, Optional Rowstart As Long = 1)\n\nDim ws As Worksheet\nDim vArray() As Variant\n\nOn Error GoTo ErrH\n Set ws = ThisWorkbook.Sheets(SheetName): On Error GoTo 0\n \nWith ws\n If .FilterMode = True Then .ShowAllData\n lRow = .Cells(.Rows.Count, ColumnForSize).End(xlUp).row\n lCol = .Cells(1, .Columns.Count).End(xlToLeft).Column\n If lRow > 1 Or lCol > 1 Then\n vArray() = .Cells(Rowstart, 1).Resize(lRow - Rowstart + 1, lCol).Value2\n GetArr = vArray()\n End If\nEnd With\n\nEndFunction:\nExit Function\n\nErrH:\nDebug.Print "Worksheet name '" & SheetName & "' not found."\nResume EndFunction\n\nEnd Function\n\n\n\n'------- -------------------- ---------\n'------- Paste Array to Sheet ---------\n'------- -------------------- ---------\n\nFunction PasteArr(SheetName As String, vArray() As Variant, Optional ColumnForSize As Long = 1, Optional bClearContents As Boolean = True, Optional bLastRow As Boolean, Optional bOmitFirstRow As Boolean)\n\nDim ws As Worksheet\n\nOn Error GoTo ErrH\n Set ws = ThisWorkbook.Sheets(SheetName): On Error GoTo 0\n\nx = 0\n\nWith ws\n If .FilterMode = True Then .ShowAllData\n If bClearContents Then\n lRow = .Cells(.Rows.Count, ColumnForSize).End(xlUp).row\n lCol = .Cells(1, .Columns.Count).End(xlToLeft).Column\n If lRow > 1 Then .Cells(1, 1).Resize(lRow, lCol).ClearContents\n End If\n If bOmitFirstRow Then\n For i = LBound(vArray, 2) To UBound(vArray, 2)\n vArray(LBound(vArray), i) = vArray(UBound(vArray), i)\n vArray(UBound(vArray), i) = ""\n Next\n x = 1\n End If\n If Not (Not vArray()) Then\n If bLastRow Then\n lRow = .Cells(.Rows.Count, ColumnForSize).End(xlUp).row + 1\n .Cells(lRow, 1).Resize(UBound(vArray) - x, UBound(vArray, 2)) = vArray()\n Else\n .Cells(1, 1).Resize(UBound(vArray) - x, UBound(vArray, 2)) = vArray()\n End If\n End If\nEnd With\n\n\nEndFunction:\nExit Function\n\nErrH:\nDebug.Print "Worksheet name '" & SheetName & "' not found."\nResume EndFunction\n\nEnd Function\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-24T19:17:26.850",
"Id": "257632",
"ParentId": "256570",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T13:29:00.283",
"Id": "256570",
"Score": "0",
"Tags": [
"performance",
"vba"
],
"Title": "Copy a block of data into existing cells, adding a new line"
}
|
256570
|
<p>I made a multithreaded logger years ago when I was still a total newbie. It "worked" (when it didn't deadlock). Now that I'm slightly less newbie I'd like to get some criticism on this new version.</p>
<p>The logger spawns an internal thread on its own method <code>writer()</code>, whose purpose is writing (to console and to file) the logging information.</p>
<p>There are two queues, one from which the writer writes data (<code>queue_write</code>), the other where the rest of the program can push data (<code>queue_log</code>). Upon pushing, the writer is awakened, it takes control of a mutex to make sure no other thread is accessing the <code>queue_log</code> queue, and it swaps the content with <code>queue_write</code>; then releases the lock. That way, threads using the logger would at worst have to wait for a simple pointer swap between two queues, which should be efficient.</p>
<p>After the swap, the writer thread empties his new queue on the output streams, until it's empty, then proceeds to check if the logger is still running (false when destructed or explicitly closed), takes the lock again, and if the <code>queue_log</code> is empty it goes asleep releasing the lock.</p>
<p>A couple of notes:</p>
<ul>
<li>The "<code>utils</code>" namespace is a namespace of utilities I made for myself and willingly reflects the STL implementation. The choice of having the class start in lower case is made on purpose.</li>
<li>The logger is made with one thread producing and the inner thread consuming; it's not made for multiple consumers. It can have multiple producers but it's not optimized with that in mind.</li>
<li>The <code>Message</code> class I use in the usage example is stripped down of all the non-relevant content (I've another portion of <code>utils</code> taking care of colouring output to console).</li>
</ul>
<h2>logger.h</h2>
<pre><code>#pragma once
#include <fstream>
#include <iostream>
#include <queue>
#include <thread>
#include <mutex>
namespace utils
{
//TODO
// With C++20 replace the time_points with actual readable time https://stackoverflow.com/questions/62954221/c-print-chronotime-pointchronohigh-resolution-clock-to-be-readable
template <typename Message_type>
class logger
{
private:
std::ofstream file;
std::queue<Message_type> queue_log;
std::queue<Message_type> queue_write;
std::thread thread;
std::atomic_bool running = true;
std::mutex queue_free;
std::condition_variable work_available;
void writer()
{
while (running)
{
if (true)
{
std::unique_lock lock{queue_free};
if (queue_log.empty()) { work_available.wait(lock); }
queue_write.swap(queue_log);
}
write_all();
}
}
void write_all()
{
while (!queue_write.empty())
{
Message_type& message = queue_write.front();
std::cout << message << std::endl;
file << message << std::endl;
queue_write.pop();
}
}
public:
logger(const std::string& file_name = "log.txt")
: thread(&logger::writer, this) { file.open(file_name); }
logger(const logger& copy) = delete; // don't copy threads please, thank you
logger& operator=(const logger& copy) = delete; // don't copy threads please, thank you
logger(logger&& move) noexcept = default; //could make those (running is already a flag for the instance being alive or not) but I'm lazy
logger& operator=(logger&& move) = default; //could make those (running is already a flag for the instance being alive or not) but I'm lazy
~logger() { if (running) { close(); } }
//Push messages begin
void operator<<(const Message_type& message) { push(message); }
void operator()(const Message_type& message) { push(message); }
template <typename ...Args>
void emplace(Args&&... args)
{
Message_type message{args...};
push(message);
}
void push(const Message_type& message)
{
if (true)
{
std::lock_guard lock(queue_free);
queue_log.push(message);
}
work_available.notify_one();
}
//Push messages end
void close()
{
running = false;
work_available.notify_one();
thread.join();
queue_write.swap(queue_log);
write_all();
file.close();
}
};
}
</code></pre>
<hr />
<h1>Usage example</h1>
<h2>Message.h</h2>
<pre><code>#pragma once
#include <chrono>
#include <iomanip>
#include <string>
#include <string_view>
class Message
{
private:
static std::string filter_last_newline(const std::string& string)
{
if (string.length() > 0 && string[string.length() - 1] == '\n') { return string.substr(0, string.length() - 1); }
else { return string; }
}
public:
enum class Type { log, dgn, inf, wrn, err };
Message(Type type, const std::string& string, std::chrono::time_point<std::chrono::system_clock> time) noexcept
: type(type), string(string), time(time)
{}
Message(Type type, const std::string& string) noexcept
: type(type), string(string), time(std::chrono::system_clock::now())
{}
Message(const std::string& string) noexcept
: type(Type::log), string(string), time(std::chrono::system_clock::now())
{}
Type type = Type::log;
std::string string = "";
std::chrono::time_point<std::chrono::system_clock> time;
const char* out_type() const noexcept
{
switch (type)
{
case Message::Type::log: return "[LOG]"; // [LOG]
case Message::Type::dgn: return "[DGN]"; // [DIAGNOSTIC]
case Message::Type::inf: return "[INF]"; // [INFO]
case Message::Type::wrn: return "[WRN]"; // [WARNING]
case Message::Type::err: return "[ERR]"; // [ERROR]
}
}
static Message log(const std::string& string) { return {Type::log, filter_last_newline(string), std::chrono::system_clock::now()}; }
static Message dgn(const std::string& string) { return {Type::dgn, filter_last_newline(string), std::chrono::system_clock::now()}; }
static Message inf(const std::string& string) { return {Type::inf, filter_last_newline(string), std::chrono::system_clock::now()}; }
static Message wrn(const std::string& string) { return {Type::wrn, filter_last_newline(string), std::chrono::system_clock::now()}; }
static Message err(const std::string& string) { return {Type::err, filter_last_newline(string), std::chrono::system_clock::now()}; }
friend std::ostream& operator<<(std::ostream& os, const Message& m)
{
size_t beg = 0;
size_t end = m.string.find_first_of('\n', beg);
if (end == std::string::npos) { end = m.string.length(); }
//First line
os << std::setw(18) << m.time.time_since_epoch().count() << ' ';
os << m.out_type();
os << ' ' << std::string_view(m.string).substr(beg, end - beg) << '\n';
//Other lines
while (true)
{
if (end == m.string.length()) { break; }
else
{
beg = end + 1;
end = m.string.find_first_of('\n', beg);
if (end == std::string::npos) { end = m.string.length(); }
}
os << std::setw(24) << '|';
os << ' ' << std::string_view(m.string).substr(beg, end - beg) << '\n';
}
return os;
}
};
</code></pre>
<h2>Main.cpp</h2>
<pre><code>#include "utils/logger.h"
#include "Message.h"
int main()
{
utils::logger<Message> logger;
logger.push(Message(Message::Type::err, "This is a verbose way to write an error."));
logger.emplace(Message::Type::err, "This is a still quite verbose to write an error.");
logger.push(Message::err("This is a less verbose way to write an error."));
logger << Message::err("This is the slightly shorter way to write an error.");
logger(Message::err("This is the shortest I could think of, although far from the \"standard\" way of doing things."));
logger(Message::wrn("Multi\nline\nwarning\njust\nto\nmake\nsure\nit\nworks."));
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T14:47:56.867",
"Id": "506559",
"Score": "0",
"body": "One question - why are the messages written to `std::cout` rather than to `std::clog`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T15:36:49.943",
"Id": "506564",
"Score": "0",
"body": "@TobySpeight they're not necessarily errors, and clog outputs to the error channel. There's arguments for either of them, I just didn't want to make its usage more clunky than it already is by asking the user what stream he wants to output on too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T22:08:38.817",
"Id": "506620",
"Score": "1",
"body": "Can you clarify why you need a multi threaded logger instead of a thread safe logger?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T22:28:54.853",
"Id": "506623",
"Score": "0",
"body": "@EmilyL. any instance where the thread outputting log messages needs to spend as little time logging as possible. Then you have the second thread bothering with slow i/o operation while the rest of the program can keep doing what it's doing as fast as it can. An example could be a game engine, this way you can log multiple things every frame without it inhibiting the fps too much."
}
] |
[
{
"body": "<p>While formatting is a matter of preference, you shouldn't stray too far away from common ground. Consider moving your opening and closing brackets back, so:</p>\n<pre><code>int main()\n{\n return 0;\n}\n</code></pre>\n<p>instead of</p>\n<pre><code>int main()\n {\n return 0;\n }\n</code></pre>\n<hr />\n<pre><code>Message_type\n</code></pre>\n<p>Make a stand, either CamelCase or snake_case, not some weird offspring.</p>\n<hr />\n<pre><code> while (running)\n {\n if (true)\n</code></pre>\n<p><code>if (true)</code> is redundant here, you can use <code>{ .. }</code> only.</p>\n<hr />\n<pre><code>if (queue_log.empty()) { work_available.wait(lock); }\n</code></pre>\n<p>instead go:</p>\n<pre><code>work_available.wait(lock, [&]() { return !running || !queue_log.empty(); });\n</code></pre>\n<p><code>std::condition_variable::wait()</code> might awake spuriously (without reason), in which case your <code>queue_log</code> will be empty and you called <code>write_all</code> for nothing. <code>wait</code> call with predicate takes care of this.</p>\n<hr />\n<pre><code>Message_type& message = queue_write.front();\n</code></pre>\n<p>use <code>auto</code>:</p>\n<pre><code>auto& message = queue_write.front();\n</code></pre>\n<p>this will make refactoring the code easier.</p>\n<hr />\n<pre><code> while (!queue_write.empty())\n {\n Message_type& message = queue_write.front();\n\n std::cout << message << std::endl;\n file << message << std::endl;\n\n queue_write.pop();\n }\n</code></pre>\n<p>Use <code>std::vector</code> instead of <code>std::queue</code> - you don't need to pop from <code>queue_write</code>, you can just iterate over it and destroy it all together. So:</p>\n<pre><code>for(auto &message : queue_write) {\n std::cout << message << std::endl;\n file << message << std::endl;\n}\n</code></pre>\n<p>and:</p>\n<pre><code> std::vector<Message_type> queue_log;\n std::vector<Message_type> queue_write;\n</code></pre>\n<p>instead of:</p>\n<pre><code> std::queue<Message_type> queue_log;\n std::queue<Message_type> queue_write;\n</code></pre>\n<hr />\n<p>Pass <code>queue_write</code> by an argument. Don't keep it as member field. Passing it as an argument shows the value is "private" to a caller and callee. When you put it as a member field, every member function can access it so anyone else will have to scan more source code to see, that it's being accessed in two functions only. So:</p>\n<pre><code> void write_all(const std::vector<Message_type> &queue_write) {\n for(auto &message: queue_write) {\n std::cout << message << std::endl;\n file << message << std::endl;\n }\n }\n</code></pre>\n<p>and</p>\n<pre><code> void writer() {\n while (running) {\n std::vector<Message_type> queue_write;\n {\n std::unique_lock lock{queue_free};\n if (queue_log.empty()) { work_available.wait(lock); }\n\n queue_write.swap(queue_write);\n }\n\n write_all(queue_write);\n }\n }\n</code></pre>\n<hr />\n<pre><code> logger(const std::string& file_name = "log.txt")\n : thread(&logger::writer, this) { file.open(file_name); }\n</code></pre>\n<p>this is undefined behaviour (race condition) and major error. You create a thread, which uses <code>file</code> variable and also uses this variable in a constructor, which is on <em>different</em> thread. Instead write it like this:</p>\n<pre><code> logger(const std::string& file_name = "log.txt")\n : file(file_name), thread(&logger::writer, this) {}\n</code></pre>\n<p><code>file</code> variable is before <code>thread</code> variable, which means it will be initialized first. Thus you will certainly create thread <em>after</em> opening your file for writing.</p>\n<hr />\n<pre><code> void operator<<(const Message_type& message) { push(message); }\n void operator()(const Message_type& message) { push(message); }\n</code></pre>\n<p>instead write:</p>\n<pre><code> void operator<<(Message_type message) { push(std::move(message)); }\n void operator()(Message_type message) { push(std::move(message)); }\n</code></pre>\n<p>This might prevent copying <code>message</code>.</p>\n<hr />\n<pre><code>void push(const Message_type& message)\n \n</code></pre>\n<p>instead use:</p>\n<pre><code> void push(Message_type message)\n {\n if (true)\n {\n std::lock_guard lock(queue_free);\n queue_log.push(std::move(message));\n }\n work_available.notify_one();\n }\n</code></pre>\n<p>If you're worried about <code>Message_type</code> being not movable, then provide both <code>const Message_type &</code> and <code>Message_type &&</code> overloads.</p>\n<hr />\n<pre><code> static std::string filter_last_newline(const std::string& string)\n {\n if (string.length() > 0 && string[string.length() - 1] == '\\n') { return string.substr(0, string.length() - 1); }\n else { return string; }\n }\n</code></pre>\n<p>instead write:</p>\n<pre><code> static std::string filter_last_newline(std::string str) {\n if (!str.empty() && str.back() == '\\n')\n str.pop_back();\n // c++17 rules about copy ellision are convoluted,\n // i'm not sure, if compiler will be forced to do std::move here\n // when returning value passed in as an argument, so just in case\n // we std::move explicitly\n return std::move(str);\n }\n</code></pre>\n<p>This might prevent unnecesary coping a string.</p>\n<hr />\n<pre><code> Message(Type type, const std::string& string, std::chrono::time_point<std::chrono::system_clock> time) noexcept\n : type(type), string(string), time(time)\n {}\n</code></pre>\n<p>as a rule of thumb, take arguments in constructors by value, not by const reference, so:</p>\n<pre><code> Message(Type type, std::string string, std::chrono::time_point<std::chrono::system_clock> time) noexcept\n : type(type), string(std::move(string)), time(time)\n {}\n</code></pre>\n<p>once again this might prevent copying the string.</p>\n<hr />\n<pre><code>std::string string = "";\n</code></pre>\n<p><code>std::string</code> already has a default constructor, so <code>= ""</code> is redundant.</p>\n<hr />\n<pre><code> switch (type)\n {\n case Message::Type::log: return "[LOG]"; // [LOG]\n case Message::Type::dgn: return "[DGN]"; // [DIAGNOSTIC]\n case Message::Type::inf: return "[INF]"; // [INFO]\n case Message::Type::wrn: return "[WRN]"; // [WARNING]\n case Message::Type::err: return "[ERR]"; // [ERROR]\n }\n</code></pre>\n<p>in such case always add an assert at the end of the function to make sure noone will get there. This oneliner can save you a lot of debugging.</p>\n<hr />\n<pre><code> while (true)\n {\n if (end == m.string.length()) { break; }\n</code></pre>\n<p>instead use <code>while</code> condition:</p>\n<pre><code> while (end < m.string.length()) {\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T19:48:08.623",
"Id": "506611",
"Score": "0",
"body": "Generally logging should appear in the order received. By using a properly thread-safe queue (by wrapping a `std::queue` interface with `std::scoped_lock`) this is handled automatically and is easy to understand. Using a `std::vector` is not intuitive and potentially confusing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T22:32:36.880",
"Id": "506625",
"Score": "0",
"body": "\"Make a stand, either CamelCase or snake_case, not some weird offspring.\" camelCase and snake_case are more about what separates the first word from the second. The first letter being capital or not is usually used to split instances from classes.CamelCase and Snake_case would be classes, camelCase and snake_case would be instances. Unless you go the prefix way \"class_xxx\", \"obj_xxx\" etcc. Similar thing for the braces positioning, I use whitesmiths indentation, which is admittedly not much popular. https://en.wikipedia.org/wiki/Indentation_style"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T22:34:57.537",
"Id": "506626",
"Score": "0",
"body": "What I mostly care about here is having the interface be as much stl-like as I can. Ty for the straightforwards filter_last_newline implementation, I didn't even know there was a pop method for strings. I'll surely look closer at all the copy-avoiding optimizations you've pointed out, thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T19:01:16.847",
"Id": "506820",
"Score": "0",
"body": "@Casey this depends on the environment. I'm senior with around 15 years of experience and my peers would actually find std::deque confusing. First question would be what do you need deque for, when vector is enough (he only push_bac's onto it and iterates over whole content)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T19:05:42.563",
"Id": "506823",
"Score": "0",
"body": "@Barnack \"Make a stand...\" comment was intended as piece of humour within many comments. My point is - once you start working with others, you need to \"get with a program\". We're creatures of habbits and having a habbit of using non-standard (unheard of) convention of names / indentation will only bring you pain. It's extremely unlikeable you will be able to convince anyone to follow it, as it would be \"whole team must switch\" - unlikely anyone else uses even similar convention. Thus they will force you to change and it will take time and some work. Why not start now?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T19:06:58.073",
"Id": "506824",
"Score": "0",
"body": "@Barnack I don't remember ever seeing Camel_snake mutation and i'm in industry over 15 years (to put things into perspecitve - i remember, when git was created and my friend was like: this tool is amasing, merges are so easy... we're switching from subversion now). I've never seen class_xxx and obj_xxx as well and thanks god g_xxx or even worse xxxs, xxxi, xxxpi and so on is also dying breed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T17:37:43.157",
"Id": "507004",
"Score": "0",
"body": "@RadosławCybulski I started programming with GameMaker 8.1 during highschool, it uses obj_xxx et cetera for naming. It also uses Whithesmiths indentation in documentation and that's where I got the habit. I've no problem switching case/underscore. Capital_snake for classes with lower_snake for instances reflects CapitalCamel for classes with lowerCamel for instances. No probs switching between those."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T17:38:37.657",
"Id": "507005",
"Score": "0",
"body": "@RadosławCybulski but why is the indent style such a big deal? It requires a simple key shortcut in any ide I can think of to reformat files you're opening with whatever style you're most comfortable reading..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T13:19:25.763",
"Id": "507845",
"Score": "0",
"body": "Because people are lazy. For example you're asking strangers to do code review for you for free. And there will be people, who won't do it just because they see the code. Unless you work alone you want others to work with you. Others will be more willing / happy to work with you if the environment is easy on them."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T19:19:26.267",
"Id": "256587",
"ParentId": "256572",
"Score": "4"
}
},
{
"body": "<p>IMO, I think that the logger is being too busy. Every push into <code>queue_log</code> is being moved into <code>queue_write</code> instantly (with some caveats, see addendum), which sort of negates the advantage of having a separate write queue for I/O. A potential optimization would be to wait for <code>N</code> log entries before performing the write. A high <code>N</code> will be more efficient, but will have higher latency, and higher risk in case of a crash because you can potentially lose the last N log entries; so choose wisely.</p>\n<p>For example:</p>\n<pre><code>while (queue_log.size() < 10)\n work_available.wait(lock);\n</code></pre>\n<p>Now your <code>queue_write</code> will be populated when you have 10 log entries.</p>\n<p>Also in your <code>write_all</code> function you use <code>std::endl</code> for every <code>Message</code>, which can be replaced with newlines in the loop and a flush at the end. Flushing is an expensive operation which should be done sparingly. Obviously, the same caveats apply, this is more risky; a crash and you will lose some log entries.</p>\n<pre><code>while (!queue_write.empty())\n{\n ...\n\n std::cout << message << '\\n';\n file << message << '\\n';\n\n ...\n}\nfile << std::flush;\nstd::cout << std::flush;\n</code></pre>\n<hr />\n<p>Addendum:</p>\n<p>The other issue (other than the spurious wakeup case, which Radoslaw mentioned) with the use of condition variables in your code is that you did not take the case of missed notifications into account. A condition variable needs to be in a wait state, for a <code>notify_one/all()</code> to work.</p>\n<blockquote>\n<p>The effects of notify_one()/notify_all() and each of the three atomic parts of wait()/wait_for()/wait_until() (unlock+wait, wakeup, and lock) take place in a single total order that can be viewed as modification order of an atomic variable: the order is specific to this individual condition_variable. <strong>This makes it impossible for notify_one() to, for example, be delayed and unblock a thread that started waiting just after the call to notify_one() was made.</strong></p>\n</blockquote>\n<p>From <a href=\"https://en.cppreference.com/w/cpp/thread/condition_variable/wait\" rel=\"nofollow noreferrer\">cppreference : std::condition_variable::wait()</a>; emphasis mine.</p>\n<p>A possible modification would be</p>\n<pre><code>while (queue_log.empty()) {\n using namespace std::chrono_literals;\n work_available.wait_for(lock, 2s); // or whatever interval you choose\n}\n</code></pre>\n<p>Now the thread will wakeup every 2s and check if the condition (<code>queue_log.empty()</code>) is still true, and go back to sleep if it is. I doubt this is much of an issue in a logging scenario, but rather general advice about using condition variables.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T15:48:28.070",
"Id": "257102",
"ParentId": "256572",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "256587",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T14:15:36.337",
"Id": "256572",
"Score": "3",
"Tags": [
"c++",
"asynchronous",
"c++17",
"logging"
],
"Title": "Multithreaded logger"
}
|
256572
|
<p>I have a .net core console app that gets some data from an external API and inserts it into a SQL database table. It is working as expected but I wonder if you guys have any suggestions to make it more maintainable, testable, robust, and dynamic. By the way, I will add logging when getting data from API, inserting it into the database and when gets exceptions.</p>
<p>Here is the code:</p>
<pre><code>class Program
{
static async Task Main(string[] args)
{
var builder = new HostBuilder()
.ConfigureServices((hostContext, services) =>
{
//Setting up API Client
services.AddHttpClient("OrdersClient", client =>
{
client.BaseAddress =
new Uri("https://test/282675/orders?status=Created");
client.DefaultRequestHeaders.Add("Accept", "application/json");
});
services.AddSingleton<IHostedService, BusinessService>();
//Setting up app settings configuration
var config = LoadConfiguration();
services.AddSingleton(config);
});
await builder.RunConsoleAsync();
public static IConfiguration LoadConfiguration()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
return builder.Build();
}
}
public class BusinessService : IHostedService
{
private IHttpClientFactory _httpClientFactory;
private readonly IHostApplicationLifetime _applicationLifetime;
private IConfiguration _configuration;
public BusinessService(IHttpClientFactory httpClientFactory, IHostApplicationLifetime applicationLifetime, IConfiguration configuration)
{
_httpClientFactory = httpClientFactory;
_applicationLifetime = applicationLifetime;
_configuration = configuration;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
await MakeRequestsToRemoteService();
//Stop Application
_applicationLifetime.StopApplication();
}
public async Task MakeRequestsToRemoteService()
{
HttpClient httpClient = _httpClientFactory.CreateClient("OrdersClient");
var authenticationBytes = Encoding.ASCII.GetBytes("test:1234");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(authenticationBytes));
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await httpClient.GetAsync("https://test/282675/orders?startDate=1612126800000");
Console.WriteLine(DateTime.Now);
if (response.IsSuccessStatusCode)
{
Root orders = await response.Content.ReadAsAsync<Root>();
if (orders.Content.Count > 0)
{
foreach (var content in orders.Content)
{
Console.Write(content.CustomerId + " " + content.CustomerFirstName + " " + content.CustomerLastName + " " + content.CustomerEmail +" " + content.TotalPrice + " "+ content.InvoiceAddress.Phone + " " + content.Lines[0].ProductCode + " " +content.Lines[0].ProductName );
InsertData(content);
}
}
}
}
public void InsertData(Content content)
{
string connString = _configuration["ConnectionStrings:Development"];
using (SqlConnection sqlConnection = new SqlConnection(connString))
{
sqlConnection.Open();
using (SqlCommand command = new SqlCommand())
{
command.Connection = sqlConnection;
string sql = @"insert into Orders (id, customerId, firstName, lastName, phone, productCode, productName, price, orderDate, status) values (@id, @customerId, @firstName, @lastName, @phone, @productCode, @productName, @price, @orderDate, @status)";
command.CommandText = sql;
command.Parameters.Clear();
try
{
command.Parameters.Add("id", SqlDbType.BigInt).Value = content.Id;
command.Parameters.Add("customerId", SqlDbType.Int).Value = content.CustomerId;
command.Parameters.Add("firstName", SqlDbType.VarChar).Value = content.CustomerFirstName;
command.Parameters.Add("lastName", SqlDbType.VarChar).Value = content.CustomerLastName;
command.Parameters.Add("phone", SqlDbType.VarChar).Value = content.InvoiceAddress.Phone;
command.Parameters.Add("productCode", SqlDbType.Int).Value = content.Lines[0].ProductCode;
command.Parameters.Add("productName", SqlDbType.VarChar).Value = content.Lines[0].ProductName;
command.Parameters.Add("price", SqlDbType.Float).Value = content.TotalPrice;
command.Parameters.Add("orderDate", SqlDbType.BigInt).Value = content.OrderDate;
command.Parameters.Add("status", SqlDbType.TinyInt).Value = 1; //Retrieved
command.ExecuteNonQuery();
}
catch (SqlException exception)
{
if (exception.Number == 2627) // Cannot insert duplicate key row in object error
{
Console.WriteLine("Duplicates...");
}
else
throw; // Throw exception if this exception is unexpected
}
}
}
}
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T15:39:25.573",
"Id": "506565",
"Score": "1",
"body": "Why not use Dapper -- https://dapper-tutorial.net/ ? Far nicer to use than ADO.NET. Also, using a `SqlException` to detect a duplicate row is a bad practice, and you can solve that by using the proper SQL: https://stackoverflow.com/a/20971775/648075 ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T16:47:29.467",
"Id": "506578",
"Score": "2",
"body": "Please [edit] your post to use a more descriptive title about what your code does."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T17:40:12.930",
"Id": "506584",
"Score": "0",
"body": "@BCdotWEB, do you mean adding `IGNORE_DUP_KEY` to the primary key?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T17:46:18.570",
"Id": "506586",
"Score": "1",
"body": "`var response = await...` => `using var response = await...`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T17:48:11.157",
"Id": "506587",
"Score": "0",
"body": "@aepot, for httpclient?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T17:52:35.837",
"Id": "506588",
"Score": "1",
"body": "For `HttpResponseMessage` which is `IDisposable`. But better is `using var response = await httpClient.GetAsync(\"url\", HttpCompletionOption.ResponseHeadersRead);`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T17:54:20.363",
"Id": "506590",
"Score": "0",
"body": "I am using HTTP client factory, should I need `using`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T17:57:21.630",
"Id": "506591",
"Score": "0",
"body": "Do you see a difference between `HttpClient` and `HttpResponseMessage`? I'm talking nothing about `HttpClient`."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T15:05:50.097",
"Id": "256575",
"Score": "0",
"Tags": [
"c#",
"sql",
".net",
".net-core"
],
"Title": ".net core console app read from external API and write into a database"
}
|
256575
|
<p>I try to solve a kata on codewars which let you write a skyscraper solver for skyscrapers up to size 11x11.</p>
<p>Basic Example what is a skyscraper puzzle (here with 4by4 but the principle stays the same):</p>
<p>In a grid of 4 by 4 squares you want to place a skyscraper in each square with only some clues:</p>
<p>-The height of the skyscrapers is between 1 and 4</p>
<p>-No two skyscrapers in a row or column may have the same number of floors</p>
<p>-A clue is the number of skyscrapers that you can see in a row or column from the outside</p>
<p>-Higher skyscrapers block the view of lower skyscrapers located behind them</p>
<p>To understand how the puzzle works, this is an example of a row with 2 clues. Seen from the left side there are 4 buildings visible while seen from the right side only 1:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>4</th>
<th></th>
<th></th>
<th></th>
<th></th>
<th>1</th>
</tr>
</thead>
</table>
</div>
<p>There is only one way in which the skyscrapers can be placed. From left-to-right all four buildings must be visible and no building may hide behind another building:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>4</th>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>1</th>
</tr>
</thead>
</table>
</div>
<p>Example of a 4 by 4 puzzle with the solution:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th></th>
<th>0</th>
<th>0</th>
<th>1</th>
<th>2</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td>0</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>2</td>
</tr>
<tr>
<td>0</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td>1</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td>0</td>
<td>0</td>
<td>3</td>
<td>0</td>
<td></td>
</tr>
</tbody>
</table>
</div>
<p>Which results in:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th></th>
<th>0</th>
<th>0</th>
<th>1</th>
<th>2</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>2</td>
<td>1</td>
<td>4</td>
<td>3</td>
<td>0</td>
</tr>
<tr>
<td>0</td>
<td>3</td>
<td>4</td>
<td>1</td>
<td>2</td>
<td>2</td>
</tr>
<tr>
<td>0</td>
<td>4</td>
<td>2</td>
<td>3</td>
<td>1</td>
<td>0</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>3</td>
<td>2</td>
<td>4</td>
<td>0</td>
</tr>
<tr>
<td></td>
<td>0</td>
<td>0</td>
<td>3</td>
<td>0</td>
<td></td>
</tr>
</tbody>
</table>
</div>
<p>The clues are passed as an vector clockwise like so:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th></th>
<th>0</th>
<th>1</th>
<th>2</th>
<th>3</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>15</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>4</td>
</tr>
<tr>
<td>14</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>5</td>
</tr>
<tr>
<td>13</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>6</td>
</tr>
<tr>
<td>12</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>7</td>
</tr>
<tr>
<td></td>
<td>11</td>
<td>10</td>
<td>9</td>
<td>8</td>
<td></td>
</tr>
</tbody>
</table>
</div>
<p>Also in a skyscraper puzzle there can be already provided solved skyscrapers at start (Interesting for bigger sizes than 4):</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th></th>
<th>0</th>
<th>0</th>
<th>1</th>
<th>2</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td>0</td>
<td></td>
<td>4</td>
<td></td>
<td></td>
<td>2</td>
</tr>
<tr>
<td>0</td>
<td></td>
<td></td>
<td>3</td>
<td></td>
<td>0</td>
</tr>
<tr>
<td>1</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td>0</td>
<td>0</td>
<td>3</td>
<td>0</td>
<td></td>
</tr>
</tbody>
</table>
</div>
<p>You can read more about skyscrapers puzzles <a href="https://www.conceptispuzzles.com/index.aspx?uri=puzzle/skyscrapers/" rel="nofollow noreferrer">here</a>:</p>
<p>To understand the problem it is good idea to solve some skyscrapers.</p>
<p>My code for this works perfectly fine for all my test cases but there is this restriction that the code is run against unit tests on the codewars server. The restriction there is all unit tests have to pass in less than 12 seconds. And that is not happening at the moment.</p>
<p>I already asked with a stripped down code <a href="https://codereview.stackexchange.com/questions/256236/generating-permutations-fast">here</a> but I think maybe it is better to show the whole program.</p>
<p>I wonder if my code can be optimized more or my approach is completely wrong in terms of speed.</p>
<p>Here a short rundown of the classes in use to give an overview what the program does:</p>
<ul>
<li><p><code>Span</code>: Since Codewars only supports C++17 this is a stripped down basic implementation of <code>std::span</code> we use for looking at <code>Permutations</code> from <code>Rows</code></p>
</li>
<li><p><code>Nopes</code>: Represents which buildings are not present on a <code>Field</code></p>
</li>
<li><p><code>BorderIterator</code>: Is used to iterate over the edges of the <code>Board</code> without having to think about x/y coordinates</p>
</li>
<li><p><code>Board</code>: Contains skyscrapers and <code>Nopes</code> separated. To supply skyscrapers only easy for the solution.</p>
</li>
<li><p><code>Field</code>: View to one <code>Field</code> of the whole <code>Board</code>. Contains skyscrapers and <code>Nopes</code>.</p>
</li>
<li><p><code>Row</code>: View to one <code>Row</code> of the <code>Board</code>. Is connected to crossing <code>Rows</code>.</p>
</li>
<li><p><code>CluePair</code>: Contains how many buildigns are visible from the front and back of a <code>Row</code>. Clue = 0 means no clue.</p>
</li>
<li><p><code>Slice</code>: View to a <code>Row</code> which keeps track of possible Permutations per <code>Row</code></p>
</li>
<li><p><code>Permutations</code>: Generates all <code>Permutations</code> and gives out indexes to valid Permutations depending on <code>CluePairs</code>.</p>
</li>
</ul>
<p>I basically do the following steps to solve the Skyscraper:</p>
<ol>
<li><p>Create the <code>Board</code>. Fill it with initial skyscrapers if skyscrapers are known.</p>
</li>
<li><p>Create the <code>Rows</code> with the <code>Fields</code>.</p>
</li>
<li><p>Generate all <code>Permutations</code> for the size of the board. For Example for a board size = 4 we get <code>1*2*3*4=24</code> possible <code>Permutations</code> per row. At the same time we determine which <code>Permutations</code> are valid for each <code>Slice</code>.</p>
</li>
<li><p>Create the Slices with the permutations indexes.</p>
</li>
<li><p>From here on we try to reduce the possible permutation per row which gives us new <code>Nopes</code> and <code>Skyscrapers</code> until the board is solved.</p>
</li>
</ol>
<p>Now I profiled the code and it looks like most of the runtime is wasted in generating the permutations.</p>
<p>Please let men know how I can improve the performance. I already tried to use an alternate approach for <code> std::next_permutation</code> like <a href="https://en.wikipedia.org/wiki/Heap%27s_algorithm" rel="nofollow noreferrer">Heaps Algorithm</a> but it was even slower.</p>
<p>Is there a way to use maybe threading to increase the performance.</p>
<p>Or am I on the wrong train even generating all permutations?</p>
<p>So please mainly tell me what can be done to increase the speed of the computation.</p>
<p>If you see other bad practices / design issues feel free to also mention them.</p>
<p>Here is the code (It is all in one file because it is a codewars requirement):</p>
<pre><code>#include <algorithm>
#include <cassert>
#include <cstddef>
#include <functional>
#include <iterator>
#include <map>
#include <numeric>
#include <set>
#include <type_traits>
#include <unordered_set>
#include <chrono>
#include <iomanip>
#include <iostream>
template <typename T> class Span {
public:
using element_type = T;
using value_type = std::remove_cv_t<T>;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using pointer = T *;
using const_pointer = const T *;
using reference = T &;
using const_reference = const T &;
using const_iterator = const_pointer;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
Span(const_pointer ptr, size_type size);
constexpr const_pointer data() const noexcept;
constexpr size_type size() const noexcept;
constexpr const_reference operator[](size_type idx) const;
constexpr const_iterator cbegin() const noexcept;
constexpr const_iterator cend() const noexcept;
constexpr const_reverse_iterator crbegin() const noexcept;
constexpr const_reverse_iterator crend() const noexcept;
private:
const_pointer mPtr;
size_type mSize;
};
template <typename T>
Span<T>::Span(const_pointer ptr, size_type size) : mPtr{ptr}, mSize{size}
{
}
template <typename T>
constexpr typename Span<T>::const_pointer Span<T>::data() const noexcept
{
return mPtr;
}
template <typename T>
constexpr typename Span<T>::size_type Span<T>::size() const noexcept
{
return mSize;
}
template <typename T>
constexpr typename Span<T>::const_reference
Span<T>::operator[](Span::size_type idx) const
{
assert(idx < mSize);
return *(data() + idx);
}
template <typename T>
constexpr typename Span<T>::const_iterator Span<T>::cbegin() const noexcept
{
return data();
}
template <typename T>
constexpr typename Span<T>::const_iterator Span<T>::cend() const noexcept
{
return data() + size();
}
template <typename T>
constexpr typename Span<T>::const_reverse_iterator
Span<T>::crbegin() const noexcept
{
return reverse_iterator(cend());
}
template <typename T>
constexpr typename Span<T>::const_reverse_iterator
Span<T>::crend() const noexcept
{
return reverse_iterator(cbegin());
}
template <typename It> int missingNumberInSequence(It begin, It end)
{
int n = std::distance(begin, end) + 1;
double projectedSum = (n + 1) * (n / 2.0);
int actualSum = std::accumulate(begin, end, 0);
return projectedSum - actualSum;
}
class Nopes {
public:
Nopes(int size);
void insert(int value);
void insert(const std::vector<int> &values);
bool sizeReached() const;
int missingNumberInSequence() const;
bool contains(int value) const;
bool contains(const std::vector<int> &values);
bool isEmpty() const;
void clear();
std::vector<int> containing() const;
// for debug print
std::unordered_set<int> values() const;
private:
int mSize;
std::unordered_set<int> mValues;
};
Nopes::Nopes(int size) : mSize{size}
{
assert(size > 0);
}
void Nopes::insert(int value)
{
assert(value >= 1 && value <= mSize + 1);
mValues.insert(value);
}
void Nopes::insert(const std::vector<int> &values)
{
mValues.insert(values.begin(), values.end());
}
bool Nopes::sizeReached() const
{
return mValues.size() == static_cast<std::size_t>(mSize);
}
int Nopes::missingNumberInSequence() const
{
assert(sizeReached());
return ::missingNumberInSequence(mValues.begin(), mValues.end());
}
bool Nopes::contains(int value) const
{
auto it = mValues.find(value);
return it != mValues.end();
}
bool Nopes::contains(const std::vector<int> &values)
{
for (const auto &value : values) {
if (!contains(value)) {
return false;
}
}
return true;
}
bool Nopes::isEmpty() const
{
return mValues.empty();
}
void Nopes::clear()
{
mValues.clear();
}
std::vector<int> Nopes::containing() const
{
std::vector<int> nopes;
nopes.reserve(mValues.size());
for (const auto &value : mValues) {
nopes.emplace_back(value);
}
return nopes;
}
std::unordered_set<int> Nopes::values() const
{
return mValues;
}
struct Point {
int x;
int y;
};
inline bool operator==(const Point &lhs, const Point &rhs)
{
return lhs.x == rhs.x && lhs.y == rhs.y;
}
inline bool operator!=(const Point &lhs, const Point &rhs)
{
return !(lhs == rhs);
}
enum class ReadDirection { topToBottom, rightToLeft };
void nextDirection(ReadDirection &readDirection)
{
assert(readDirection != ReadDirection::rightToLeft);
int dir = static_cast<int>(readDirection);
++dir;
readDirection = static_cast<ReadDirection>(dir);
}
void advanceToNextPosition(Point &point, ReadDirection readDirection,
int clueIdx)
{
if (clueIdx == 0) {
return;
}
switch (readDirection) {
case ReadDirection::topToBottom:
++point.x;
break;
case ReadDirection::rightToLeft:
++point.y;
break;
}
}
class BorderIterator {
public:
BorderIterator(std::size_t boardSize);
Point point() const;
ReadDirection readDirection() const;
BorderIterator &operator++();
private:
int mIdx = 0;
std::size_t mBoardSize;
Point mPoint{0, 0};
ReadDirection mReadDirection{ReadDirection::topToBottom};
};
BorderIterator::BorderIterator(std::size_t boardSize) : mBoardSize{boardSize}
{
}
Point BorderIterator::point() const
{
return mPoint;
}
ReadDirection BorderIterator::readDirection() const
{
return mReadDirection;
}
BorderIterator &BorderIterator::operator++()
{
++mIdx;
if (mIdx == static_cast<int>(2 * mBoardSize)) {
return *this;
}
if (mIdx != 0 && mIdx % mBoardSize == 0) {
nextDirection(mReadDirection);
}
advanceToNextPosition(mPoint, mReadDirection, mIdx % mBoardSize);
return *this;
}
struct Board {
Board(int size);
std::vector<std::vector<int>> skyscrapers{};
std::vector<std::vector<Nopes>> nopes;
private:
std::vector<std::vector<int>> makeSkyscrapers(int size);
std::vector<std::vector<Nopes>> makeNopes(int size);
};
Board::Board(int size)
: skyscrapers{makeSkyscrapers(size)}, nopes{makeNopes(size)}
{
}
std::vector<std::vector<int>> Board::makeSkyscrapers(int size)
{
std::vector<int> skyscraperRow(size, 0);
return std::vector<std::vector<int>>(size, skyscraperRow);
}
std::vector<std::vector<Nopes>> Board::makeNopes(int size)
{
std::vector<Nopes> nopesRow(size, Nopes{size - 1});
return std::vector<std::vector<Nopes>>(size, nopesRow);
}
void debug_print(Board &board, const std::string &title = "")
{
std::cout << title << '\n';
for (std::size_t y = 0; y < board.skyscrapers.size(); ++y) {
for (std::size_t x = 0; x < board.skyscrapers[y].size(); ++x) {
if (board.skyscrapers[y][x] != 0) {
std::cout << std::setw(board.skyscrapers.size() * 2);
std::cout << "V" + std::to_string(board.skyscrapers[y][x]);
}
else if (board.skyscrapers[y][x] == 0 &&
!board.nopes[y][x].isEmpty()) {
auto nopes_set = board.nopes[y][x].values();
std::vector<int> nopes(nopes_set.begin(), nopes_set.end());
std::sort(nopes.begin(), nopes.end());
std::string nopesStr;
for (std::size_t i = 0; i < nopes.size(); ++i) {
nopesStr.append(std::to_string(nopes[i]));
if (i != nopes.size() - 1) {
nopesStr.push_back(',');
}
}
std::cout << std::setw(board.skyscrapers.size() * 2);
std::cout << nopesStr;
}
else {
std::cout << ' ';
}
}
std::cout << '\n';
}
std::cout << '\n';
}
class Field {
public:
Field(int &skyscraper, Nopes &nopes);
void insertSkyscraper(int skyscraper);
void insertNope(int nope);
void insertNopes(const std::vector<int> &nopes);
bool fullOfNopes() const;
int skyscraper() const;
Nopes nopes() const;
bool hasSkyscraper() const;
std::optional<int> lastMissingNope() const;
private:
int *mSkyscraper;
Nopes *mNopes;
bool mHasSkyscraper = false;
};
Field::Field(int &skyscraper, Nopes &nopes)
: mSkyscraper{&skyscraper}, mNopes{&nopes}
{
}
void Field::insertSkyscraper(int skyscraper)
{
assert(*mSkyscraper == 0 || skyscraper == *mSkyscraper);
if (mHasSkyscraper) {
return;
}
*mSkyscraper = skyscraper;
mHasSkyscraper = true;
// potentially performance problem ???
mNopes->clear();
}
void Field::insertNope(int nope)
{
if (mHasSkyscraper) {
return;
}
mNopes->insert(nope);
}
void Field::insertNopes(const std::vector<int> &nopes)
{
if (mHasSkyscraper) {
return;
}
mNopes->insert(nopes);
}
bool Field::fullOfNopes() const
{
return mNopes->sizeReached();
}
int Field::skyscraper() const
{
return *mSkyscraper;
}
Nopes Field::nopes() const
{
return *mNopes;
}
bool Field::hasSkyscraper() const
{
return mHasSkyscraper;
}
std::optional<int> Field::lastMissingNope() const
{
if (!mNopes->sizeReached()) {
return {};
}
return mNopes->missingNumberInSequence();
}
Point calcPosition(std::size_t idx, const Point &startPoint,
const ReadDirection &readDirection)
{
Point point = startPoint;
if (idx == 0) {
return startPoint;
}
switch (readDirection) {
case ReadDirection::topToBottom:
point.y += idx;
break;
case ReadDirection::rightToLeft:
point.x -= idx;
break;
}
return point;
}
std::vector<std::vector<Field>> makeFields(Board &board)
{
std::vector<std::vector<Field>> fields(board.skyscrapers.size());
for (auto &row : fields) {
row.reserve(fields.size());
}
for (std::size_t y = 0; y < board.skyscrapers.size(); ++y) {
for (std::size_t x = 0; x < board.skyscrapers[y].size(); ++x) {
fields[y].emplace_back(
Field{board.skyscrapers[y][x], board.nopes[y][x]});
}
}
return fields;
}
class Row {
public:
Row(std::vector<std::vector<Field>> &fields, const Point &startPoint,
const ReadDirection &readDirection);
void insertSkyscraper(int pos, int skyscraper);
std::size_t size() const;
void addCrossingRows(Row *crossingRow);
bool hasOnlyOneNopeField() const;
void addLastMissingSkyscraper();
void addNopesToAllNopeFields(int nope);
bool allFieldsContainSkyscraper() const;
int skyscraperCount() const;
int nopeCount(int nope) const;
void guessSkyscraperOutOfNeighbourNopes();
enum class Direction { front, back };
bool hasSkyscrapers(const std::vector<int> &skyscrapers,
Direction direction) const;
bool hasNopes(const std::vector<std::vector<int>> &nopes,
Direction direction) const;
void addSkyscrapers(const std::vector<int> &skyscrapers,
Direction direction);
void addNopes(const std::vector<std::vector<int>> &nopes,
Direction direction);
std::vector<Field *> getFields() const;
private:
template <typename SkyIterator, typename FieldIterator>
bool hasSkyscrapers(SkyIterator skyItBegin, SkyIterator skyItEnd,
FieldIterator fieldItBegin,
FieldIterator fieldItEnd) const;
template <typename NopesIterator, typename FieldIterator>
bool hasNopes(NopesIterator nopesItBegin, NopesIterator nopesItEnd,
FieldIterator fieldItBegin, FieldIterator fieldItEnd) const;
template <typename SkyIterator, typename FieldIterator>
void addSkyscrapers(SkyIterator skyItBegin, SkyIterator skyItEnd,
FieldIterator fieldItBegin, FieldIterator fieldItEnd);
template <typename NopesIterator, typename FieldIterator>
void addNopes(NopesIterator nopesItBegin, NopesIterator nopesItEnd,
FieldIterator fieldItBegin, FieldIterator fieldItEnd);
template <typename IteratorType>
void insertSkyscraper(IteratorType it, int skyscraper);
template <typename IteratorType> void insertNope(IteratorType it, int nope);
template <typename IteratorType>
void insertNopes(IteratorType it, const std::vector<int> &nopes);
int getIdx(std::vector<Field *>::const_iterator cit) const;
int getIdx(std::vector<Field *>::const_reverse_iterator crit) const;
std::vector<Field *> getRowFields(const ReadDirection &readDirection,
std::vector<std::vector<Field>> &fields,
const Point &startPoint);
bool onlyOneFieldWithoutNope(int nope) const;
std::optional<int> nopeValueInAllButOneField() const;
void insertSkyscraperToFirstFieldWithoutNope(int nope);
bool hasSkyscraper(int skyscraper) const;
std::vector<Row *> mCrossingRows;
std::vector<Field *> mRowFields;
};
Row::Row(std::vector<std::vector<Field>> &fields, const Point &startPoint,
const ReadDirection &readDirection)
: mRowFields{getRowFields(readDirection, fields, startPoint)}
{
}
void Row::insertSkyscraper(int pos, int skyscraper)
{
assert(pos >= 0 && pos < static_cast<int>(mRowFields.size()));
assert(skyscraper > 0 && skyscraper <= static_cast<int>(mRowFields.size()));
auto it = mRowFields.begin() + pos;
insertSkyscraper(it, skyscraper);
}
std::size_t Row::size() const
{
return mRowFields.size();
}
void Row::addCrossingRows(Row *crossingRow)
{
assert(crossingRow != nullptr);
assert(mCrossingRows.size() < size());
mCrossingRows.push_back(crossingRow);
}
bool Row::hasOnlyOneNopeField() const
{
return skyscraperCount() == static_cast<int>(size() - 1);
}
void Row::addLastMissingSkyscraper()
{
assert(hasOnlyOneNopeField());
auto nopeFieldIt = mRowFields.end();
std::vector<int> sequence;
sequence.reserve(size() - 1);
for (auto it = mRowFields.begin(); it != mRowFields.end(); ++it) {
if ((*it)->hasSkyscraper()) {
sequence.emplace_back((*it)->skyscraper());
}
else {
nopeFieldIt = it;
}
}
assert(nopeFieldIt != mRowFields.end());
assert(skyscraperCount() == static_cast<int>(sequence.size()));
auto missingValue =
missingNumberInSequence(sequence.begin(), sequence.end());
assert(missingValue >= 0 && missingValue <= static_cast<int>(size()));
insertSkyscraper(nopeFieldIt, missingValue);
}
void Row::addNopesToAllNopeFields(int nope)
{
for (auto it = mRowFields.begin(); it != mRowFields.end(); ++it) {
if ((*it)->hasSkyscraper()) {
continue;
}
insertNope(it, nope);
}
}
bool Row::allFieldsContainSkyscraper() const
{
return skyscraperCount() == static_cast<int>(size());
}
int Row::skyscraperCount() const
{
int count = 0;
for (auto cit = mRowFields.cbegin(); cit != mRowFields.cend(); ++cit) {
if ((*cit)->hasSkyscraper()) {
++count;
}
}
return count;
}
int Row::nopeCount(int nope) const
{
int count = 0;
for (auto cit = mRowFields.cbegin(); cit != mRowFields.cend(); ++cit) {
if ((*cit)->nopes().contains(nope)) {
++count;
}
}
return count;
}
void Row::guessSkyscraperOutOfNeighbourNopes()
{
for (;;) {
auto optNope = nopeValueInAllButOneField();
if (!optNope) {
break;
}
insertSkyscraperToFirstFieldWithoutNope(*optNope);
}
}
bool Row::hasSkyscrapers(const std::vector<int> &skyscrapers,
Row::Direction direction) const
{
if (direction == Direction::front) {
return hasSkyscrapers(skyscrapers.cbegin(), skyscrapers.cend(),
mRowFields.cbegin(), mRowFields.cend());
}
return hasSkyscrapers(skyscrapers.cbegin(), skyscrapers.cend(),
mRowFields.crbegin(), mRowFields.crend());
}
bool Row::hasNopes(const std::vector<std::vector<int>> &nopes,
Direction direction) const
{
if (direction == Direction::front) {
return hasNopes(nopes.cbegin(), nopes.cend(), mRowFields.cbegin(),
mRowFields.cend());
}
return hasNopes(nopes.cbegin(), nopes.cend(), mRowFields.crbegin(),
mRowFields.crend());
}
void Row::addSkyscrapers(const std::vector<int> &skyscrapers,
Direction direction)
{
if (direction == Direction::front) {
addSkyscrapers(skyscrapers.begin(), skyscrapers.end(),
mRowFields.begin(), mRowFields.end());
}
else {
addSkyscrapers(skyscrapers.begin(), skyscrapers.end(),
mRowFields.rbegin(), mRowFields.rend());
}
}
void Row::addNopes(const std::vector<std::vector<int>> &nopes,
Direction direction)
{
if (direction == Direction::front) {
addNopes(nopes.begin(), nopes.end(), mRowFields.begin(),
mRowFields.end());
}
else {
addNopes(nopes.begin(), nopes.end(), mRowFields.rbegin(),
mRowFields.rend());
}
}
std::vector<Field *> Row::getFields() const
{
return mRowFields;
}
template <typename SkyIterator, typename FieldIterator>
bool Row::hasSkyscrapers(SkyIterator skyItBegin, SkyIterator skyItEnd,
FieldIterator fieldItBegin,
FieldIterator fieldItEnd) const
{
auto skyIt = skyItBegin;
for (auto fieldIt = fieldItBegin;
fieldIt != fieldItEnd && skyIt != skyItEnd; ++fieldIt, ++skyIt) {
if (*skyIt == 0 && (*fieldIt)->hasSkyscraper()) {
continue;
}
if ((*fieldIt)->skyscraper() != *skyIt) {
return false;
}
}
return true;
}
template <typename NopesIterator, typename FieldIterator>
bool Row::hasNopes(NopesIterator nopesItBegin, NopesIterator nopesItEnd,
FieldIterator fieldItBegin, FieldIterator fieldItEnd) const
{
auto nopesIt = nopesItBegin;
for (auto fieldIt = fieldItBegin;
fieldIt != fieldItEnd && nopesIt != nopesItEnd; ++fieldIt, ++nopesIt) {
if (nopesIt->empty()) {
continue;
}
if ((*fieldIt)->hasSkyscraper()) {
return false;
}
if (!(*fieldIt)->nopes().contains(*nopesIt)) {
return false;
}
}
return true;
}
template <typename SkyIterator, typename FieldIterator>
void Row::addSkyscrapers(SkyIterator skyItBegin, SkyIterator skyItEnd,
FieldIterator fieldItBegin, FieldIterator fieldItEnd)
{
auto skyIt = skyItBegin;
for (auto fieldIt = fieldItBegin;
fieldIt != fieldItEnd && skyIt != skyItEnd; ++fieldIt, ++skyIt) {
if (*skyIt == 0) {
continue;
}
insertSkyscraper(fieldIt, *skyIt);
}
}
template <typename NopesIterator, typename FieldIterator>
void Row::addNopes(NopesIterator nopesItBegin, NopesIterator nopesItEnd,
FieldIterator fieldItBegin, FieldIterator fieldItEnd)
{
auto nopesIt = nopesItBegin;
for (auto fieldIt = fieldItBegin;
fieldIt != fieldItEnd && nopesIt != nopesItEnd; ++fieldIt, ++nopesIt) {
if (nopesIt->empty()) {
continue;
}
insertNopes(fieldIt, *nopesIt);
}
}
template <typename FieldIterator>
void Row::insertSkyscraper(FieldIterator fieldIt, int skyscraper)
{
assert(mCrossingRows.size() == size());
if ((*fieldIt)->hasSkyscraper()) {
return;
}
(*fieldIt)->insertSkyscraper(skyscraper);
if (hasOnlyOneNopeField()) {
addLastMissingSkyscraper();
}
addNopesToAllNopeFields(skyscraper);
int idx = getIdx(fieldIt);
if (mCrossingRows[idx]->hasOnlyOneNopeField()) {
mCrossingRows[idx]->addLastMissingSkyscraper();
}
mCrossingRows[idx]->addNopesToAllNopeFields(skyscraper);
}
template <typename FieldIterator>
void Row::insertNope(FieldIterator fieldIt, int nope)
{
if ((*fieldIt)->hasSkyscraper()) {
return;
}
if ((*fieldIt)->nopes().contains(nope)) {
return;
}
(*fieldIt)->insertNope(nope);
auto optlastMissingNope = (*fieldIt)->lastMissingNope();
if (optlastMissingNope) {
insertSkyscraper(fieldIt, *optlastMissingNope);
}
if (onlyOneFieldWithoutNope(nope)) {
insertSkyscraperToFirstFieldWithoutNope(nope);
}
int idx = getIdx(fieldIt);
if (mCrossingRows[idx]->onlyOneFieldWithoutNope(nope)) {
mCrossingRows[idx]->insertSkyscraperToFirstFieldWithoutNope(nope);
}
}
template <typename IteratorType>
void Row::insertNopes(IteratorType it, const std::vector<int> &nopes)
{
for (const auto &nope : nopes) {
insertNope(it, nope);
}
}
int Row::getIdx(std::vector<Field *>::const_iterator cit) const
{
return std::distance(mRowFields.cbegin(), cit);
}
int Row::getIdx(std::vector<Field *>::const_reverse_iterator crit) const
{
return size() - std::distance(mRowFields.crbegin(), crit) - 1;
}
std::vector<Field *>
Row::getRowFields(const ReadDirection &readDirection,
std::vector<std::vector<Field>> &boardFields,
const Point &startPoint)
{
std::vector<Field *> fields;
fields.reserve(boardFields.size());
std::size_t x = startPoint.x;
std::size_t y = startPoint.y;
for (std::size_t i = 0; i < boardFields.size(); ++i) {
fields.emplace_back(&boardFields[y][x]);
if (readDirection == ReadDirection::topToBottom) {
++y;
}
else {
--x;
}
}
return fields;
}
bool Row::onlyOneFieldWithoutNope(int nope) const
{
auto cit = std::find_if(
mRowFields.cbegin(), mRowFields.cend(),
[nope](const auto &field) { return field->skyscraper() == nope; });
if (cit != mRowFields.cend()) {
return false;
}
if (nopeCount(nope) < static_cast<int>(size()) - skyscraperCount() - 1) {
return false;
}
return true;
}
std::optional<int> Row::nopeValueInAllButOneField() const
{
std::unordered_map<int, int> nopeAndCount;
for (auto cit = mRowFields.cbegin(); cit != mRowFields.cend(); ++cit) {
if (!(*cit)->hasSkyscraper()) {
auto nopes = (*cit)->nopes().containing();
for (const auto &nope : nopes) {
if (hasSkyscraper(nope)) {
continue;
}
++nopeAndCount[nope];
}
}
}
for (auto cit = nopeAndCount.cbegin(); cit != nopeAndCount.end(); ++cit) {
if (cit->second == static_cast<int>(size()) - skyscraperCount() - 1) {
return {cit->first};
}
}
return {};
}
void Row::insertSkyscraperToFirstFieldWithoutNope(int nope)
{
for (auto it = mRowFields.begin(); it != mRowFields.end(); ++it) {
if ((*it)->hasSkyscraper()) {
continue;
}
if (!(*it)->nopes().contains(nope)) {
insertSkyscraper(it, nope);
return; // there can be max one skyscraper per row;
}
}
}
bool Row::hasSkyscraper(int skyscraper) const
{
for (const auto &field : mRowFields) {
if (field->skyscraper() == skyscraper) {
return true;
}
}
return false;
}
class CluePair {
public:
CluePair(int front, int back);
int front() const;
int back() const;
bool frontIsEmpty() const;
bool backIsEmpty() const;
bool isEmpty() const;
bool operator<(const CluePair &other) const
{
return front() < other.front() ||
(front() == other.front() && back() < other.back());
}
private:
int mFront;
int mBack;
bool mFrontIsEmpty;
bool mBackIsEmpty;
bool mIsEmpty;
};
CluePair::CluePair(int front, int back)
: mFront{front}, mBack{back}, mFrontIsEmpty{mFront == 0},
mBackIsEmpty{mBack == 0}, mIsEmpty{mFrontIsEmpty && mBackIsEmpty}
{
}
int CluePair::front() const
{
return mFront;
}
int CluePair::back() const
{
return mBack;
}
bool CluePair::frontIsEmpty() const
{
return mFrontIsEmpty;
}
bool CluePair::backIsEmpty() const
{
return mBackIsEmpty;
}
bool CluePair::isEmpty() const
{
return mIsEmpty;
}
struct FieldElements {
std::vector<int> skyscrapers{};
std::vector<std::vector<int>> nopes{};
};
std::vector<CluePair> makeCluePairs(const std::vector<int> &clues)
{
std::vector<CluePair> cluePairs;
cluePairs.reserve(clues.size() / 2);
std::size_t startOffset = clues.size() / 4 * 3 - 1;
std::size_t offset = startOffset;
for (std::size_t i = 0; i < clues.size() / 2; ++i, offset -= 2) {
if (i == clues.size() / 4) {
offset = startOffset;
}
int backClueIdx = i + offset;
cluePairs.emplace_back(CluePair{clues[i], clues[backClueIdx]});
}
return cluePairs;
}
bool isValidPermutation(const Span<int> &permutation,
const std::vector<Field *> fields)
{
auto permIt = permutation.cbegin();
for (auto fieldIt = fields.cbegin();
fieldIt != fields.cend() && permIt != permutation.cend();
++fieldIt, ++permIt) {
if ((*fieldIt)->hasSkyscraper()) {
if ((*fieldIt)->skyscraper() != *permIt) {
return false;
}
}
else if (!(*fieldIt)->nopes().isEmpty()) {
if ((*fieldIt)->nopes().contains(*permIt)) {
return false;
}
}
}
return true;
}
bool fieldsIdentical(const std::vector<Field> &lastFields,
const std::vector<Field *> &currFields)
{
if (lastFields.size() != currFields.size()) {
return false;
}
auto lastIt = lastFields.begin();
auto currPtrIt = currFields.begin();
for (; lastIt != lastFields.end(); ++lastIt, ++currPtrIt) {
if (lastIt->skyscraper() != (*currPtrIt)->skyscraper()) {
return false;
}
if (lastIt->nopes().values() != (*currPtrIt)->nopes().values()) {
return false;
}
}
return true;
}
std::vector<Field> copyField(const std::vector<Field *> &currFields)
{
std::vector<Field> result;
result.reserve(currFields.size());
for (const auto &currField : currFields) {
result.emplace_back(Field{*currField});
}
return result;
}
std::vector<Row> makeRows(std::vector<std::vector<Field>> &fields)
{
BorderIterator borderIterator{fields.size()};
std::size_t size = fields.size() * 2;
std::vector<Row> rows;
rows.reserve(size);
for (std::size_t i = 0; i < size; ++i, ++borderIterator) {
rows.emplace_back(Row{fields, borderIterator.point(),
borderIterator.readDirection()});
}
return rows;
}
void connectRowsWithCrossingRows(std::vector<Row> &rows)
{
std::size_t boardSize = rows.size() / 2;
std::vector<int> targetRowsIdx(boardSize);
std::iota(targetRowsIdx.begin(), targetRowsIdx.end(), boardSize);
for (std::size_t i = 0; i < rows.size(); ++i) {
if (i == rows.size() / 2) {
std::iota(targetRowsIdx.begin(), targetRowsIdx.end(), 0);
std::reverse(targetRowsIdx.begin(), targetRowsIdx.end());
}
for (const auto &targetRowIdx : targetRowsIdx) {
rows[i].addCrossingRows(&rows[targetRowIdx]);
}
}
}
void insertExistingSkyscrapersFromStartingGrid(
std::vector<Row> &rows, const std::vector<std::vector<int>> startingGrid)
{
assert(startingGrid.size() == rows.size() / 2);
assert(startingGrid[0].size() == rows.size() / 2);
std::size_t verticalRowsSize = rows.size() / 2;
for (std::size_t x = 0; x < verticalRowsSize; ++x) {
for (std::size_t y = 0; y < verticalRowsSize; ++y) {
if (startingGrid[y][x] == 0) {
continue;
}
rows[x].insertSkyscraper(static_cast<int>(y), startingGrid[y][x]);
}
}
}
int factorial(int n)
{
if (n == 0) {
return 1;
}
return n * factorial(n - 1);
}
template <typename BuildingIt>
int buildingsVisible(BuildingIt begin, BuildingIt end)
{
int visibleBuildingsCount = 0;
int highestSeen = 0;
for (auto it = begin; it != end; ++it) {
if (*it > highestSeen) {
++visibleBuildingsCount;
highestSeen = *it;
}
}
return visibleBuildingsCount;
}
bool existingSkyscrapersInPermutation(const std::vector<Field *> &fields,
const std::vector<int> &permutation)
{
assert(fields.size() == permutation.size());
auto fieldIt = fields.cbegin();
auto permutationIt = permutation.cbegin();
for (; fieldIt != fields.cend() && permutationIt != permutation.cend();
++fieldIt, ++permutationIt) {
if (!(*fieldIt)->hasSkyscraper()) {
continue;
}
if ((*fieldIt)->skyscraper() != *permutationIt) {
return false;
}
}
return true;
}
class Permutations {
public:
Permutations(std::size_t size, Span<CluePair> cluePairs, Span<Row> rows);
Span<int> operator[](std::size_t permutationIndex) const;
std::vector<std::size_t> permutationIndexs(std::size_t cluePairIndex) const;
private:
void addSequenceToCluePairs(const std::vector<int> &sequence,
int currIndex);
bool permutationFitsCluePair(const CluePair &cluePair, int front, int back);
Span<CluePair> mCluePairs;
Span<Row> mRows;
std::size_t mSize;
std::size_t mPermutationCount;
std::vector<std::vector<std::size_t>> mCluePairsPermutationIndexes;
std::vector<int> mPermutations;
};
Permutations::Permutations(std::size_t size, Span<CluePair> cluePairs,
Span<Row> rows)
: mCluePairs(cluePairs), mRows{rows}, mSize{size},
mCluePairsPermutationIndexes(cluePairs.size())
{
assert(cluePairs.size() == rows.size());
std::vector<int> sequence(mSize);
std::iota(sequence.begin(), sequence.end(), 1);
mPermutationCount = factorial(sequence.size());
mPermutations.reserve(mPermutationCount * mSize);
int *p = &mPermutations[0];
for (auto &cluePairPermutationIndexes : mCluePairsPermutationIndexes) {
cluePairPermutationIndexes.reserve(mPermutationCount);
}
std::size_t currIndex = 0;
do {
addSequenceToCluePairs(sequence, currIndex);
std::copy(sequence.begin(), sequence.end(), p);
p += mSize;
++currIndex;
} while (std::next_permutation(sequence.begin(), sequence.end()));
};
Span<int> Permutations::operator[](std::size_t elem) const
{
auto ptr = &mPermutations[elem * mSize];
return Span{ptr, mSize};
}
std::vector<std::size_t>
Permutations::permutationIndexs(std::size_t cluePairIndex) const
{
return mCluePairsPermutationIndexes[cluePairIndex];
}
void Permutations::addSequenceToCluePairs(const std::vector<int> &sequence,
int currIndex)
{
auto front = buildingsVisible(sequence.cbegin(), sequence.cend());
auto back = buildingsVisible(sequence.crbegin(), sequence.crend());
for (std::size_t i = 0; i < mCluePairs.size(); ++i) {
if (!permutationFitsCluePair(mCluePairs[i], front, back)) {
continue;
}
auto fields = mRows[i].getFields();
if (!existingSkyscrapersInPermutation(fields, sequence)) {
continue;
}
mCluePairsPermutationIndexes[i].emplace_back(currIndex);
}
}
bool Permutations::permutationFitsCluePair(const CluePair &cluePair, int front,
int back)
{
if (cluePair.isEmpty()) {
return false;
}
if (!cluePair.frontIsEmpty() && cluePair.front() != front) {
return false;
}
if (!cluePair.backIsEmpty() && cluePair.back() != back) {
return false;
}
return true;
}
class Slice {
public:
Slice(Permutations &permutations,
const std::vector<std::size_t> &permutationIndexes, Row &row);
void guessSkyscraperOutOfNeighbourNopes();
bool isSolved() const;
void solveFromPossiblePermutations();
bool reducePossiblePermutations();
private:
std::vector<std::set<int>> getPossibleBuildings() const;
FieldElements
getFieldElements(const std::vector<std::set<int>> &possibleBuildings);
Permutations *mPermutations;
std::vector<std::size_t> mPermutationIndexes;
Row *mRow;
};
Slice::Slice(Permutations &permutations,
const std::vector<std::size_t> &permutationIndexes, Row &row)
: mPermutations{&permutations},
mPermutationIndexes{permutationIndexes}, mRow{&row}
{
if (permutationIndexes.empty()) {
return;
}
auto possibleBuildings = getPossibleBuildings();
auto fieldElements = getFieldElements(possibleBuildings);
mRow->addSkyscrapers(fieldElements.skyscrapers, Row::Direction::front);
mRow->addNopes(fieldElements.nopes, Row::Direction::front);
}
void Slice::guessSkyscraperOutOfNeighbourNopes()
{
mRow->guessSkyscraperOutOfNeighbourNopes();
}
bool Slice::isSolved() const
{
return mRow->allFieldsContainSkyscraper();
}
void Slice::solveFromPossiblePermutations()
{
if (mPermutationIndexes.empty()) {
return;
}
while (reducePossiblePermutations()) {
auto lastFields = copyField(mRow->getFields());
auto possibleBuildings = getPossibleBuildings();
auto fieldElements = getFieldElements(possibleBuildings);
mRow->addSkyscrapers(fieldElements.skyscrapers, Row::Direction::front);
mRow->addNopes(fieldElements.nopes, Row::Direction::front);
if (fieldsIdentical(lastFields, mRow->getFields())) {
break;
}
}
}
bool Slice::reducePossiblePermutations()
{
auto startSize = mPermutationIndexes.size();
auto it = mPermutationIndexes.begin();
auto fields = mRow->getFields();
while (it != mPermutationIndexes.end()) {
if (!isValidPermutation(mPermutations->operator[](*it), fields)) {
it = mPermutationIndexes.erase(it);
}
else {
++it;
}
}
return startSize > mPermutationIndexes.size();
}
std::vector<std::set<int>> Slice::getPossibleBuildings() const
{
std::vector<std::set<int>> possibleBuildingsOnFields(mRow->size());
for (const auto &permutationIndex : mPermutationIndexes) {
auto permutation = mPermutations->operator[](permutationIndex);
for (std::size_t i = 0; i < permutation.size(); ++i) {
possibleBuildingsOnFields[i].insert(permutation[i]);
}
}
return possibleBuildingsOnFields;
}
FieldElements
Slice::getFieldElements(const std::vector<std::set<int>> &possibleBuildings)
{
FieldElements fieldElements;
fieldElements.skyscrapers.reserve(possibleBuildings.size());
fieldElements.nopes.reserve(possibleBuildings.size());
for (std::size_t i = 0; i < possibleBuildings.size(); ++i) {
if (possibleBuildings[i].size() == 1) {
fieldElements.skyscrapers.emplace_back(
*possibleBuildings[i].begin());
fieldElements.nopes.emplace_back(std::vector<int>{});
}
else {
std::vector<int> nopes;
nopes.reserve(possibleBuildings.size());
for (std::size_t j = 0; j < possibleBuildings.size(); ++j) {
auto it = possibleBuildings[i].find(j + 1);
if (it == possibleBuildings[i].end()) {
nopes.emplace_back(j + 1);
}
}
fieldElements.skyscrapers.emplace_back(0);
fieldElements.nopes.emplace_back(nopes);
}
}
return fieldElements;
}
std::vector<Slice> makeSlices(Permutations &permutations,
std::vector<Row> &rows,
const std::vector<CluePair> &cluePairs)
{
std::vector<Slice> slices;
slices.reserve(rows.size());
for (std::size_t i = 0; i < cluePairs.size(); ++i) {
slices.emplace_back(
Slice{permutations, permutations.permutationIndexs(i), rows[i]});
}
return slices;
}
std::vector<std::vector<int>>
SolvePuzzle(const std::vector<int> &clues,
std::vector<std::vector<int>> startingGrid, int)
{
assert(clues.size() % 4 == 0);
auto cluePairs = makeCluePairs(clues);
int boardSize = clues.size() / 4;
Board board{boardSize};
auto fields = makeFields(board);
auto rows = makeRows(fields);
connectRowsWithCrossingRows(rows);
if (!startingGrid.empty()) {
insertExistingSkyscrapersFromStartingGrid(rows, startingGrid);
}
// auto t1 = std::chrono::high_resolution_clock::now();
Permutations permutations(boardSize, Span{&cluePairs[0], cluePairs.size()},
Span{&rows[0], rows.size()});
// auto t2 = std::chrono::high_resolution_clock::now();
// std::cout << "generate permutations:"
// << std::chrono::duration_cast<std::chrono::milliseconds>(t2
// - t1)
// .count()
// << '\n';
// auto t3 = std::chrono::high_resolution_clock::now();
std::vector<Slice> slices = makeSlices(permutations, rows, cluePairs);
// auto t4 = std::chrono::high_resolution_clock::now();
// std::cout << "make slices:"
// << std::chrono::duration_cast<std::chrono::milliseconds>(t4
// - t3)
// .count()
// << '\n';
// auto t5 = std::chrono::high_resolution_clock::now();
int count = 0;
for (;;) {
++count;
if (count > 1000) {
debug_print(board);
break;
}
bool allFull = true;
for (std::size_t i = 0; i < slices.size(); ++i) {
if (slices[i].isSolved()) {
continue;
}
slices[i].solveFromPossiblePermutations();
slices[i].guessSkyscraperOutOfNeighbourNopes();
if (!slices[i].isSolved()) {
allFull = false;
}
}
if (allFull) {
break;
}
}
// auto t6 = std::chrono::high_resolution_clock::now();
// std::cout << "solving loop:"
// << std::chrono::duration_cast<std::chrono::milliseconds>(t6
// - t5)
// .count()
// << '\n';
return board.skyscrapers;
}
std::vector<std::vector<int>> SolvePuzzle(const std::vector<int> &clues)
{
return SolvePuzzle(clues, std::vector<std::vector<int>>{}, 0);
}
</code></pre>
<p>The full project with unit tests (which I cannot post because of the post char limit) can be found on github <a href="https://github.com/SandroWissmann/Skyscrapers" rel="nofollow noreferrer">here</a>.</p>
<p>EDIT:</p>
<p>As mentioned in the comments currently I once generate all permutations of one row. For n=11 this is 11! which is about ~80 million permutations.</p>
<p>I can reduce these permutations while generating them depending on the clues and existing scrapers but I still have to go through all of them at least once (or not?).</p>
<p>Any way to overcome this approach?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T16:51:02.793",
"Id": "506693",
"Score": "0",
"body": "I provided an easy example with an easy small 4by4 Skyscraper. Many more boards can be found in the unit tests for sizes 4by4 up tp 11by11 with pre existing skyscrapers and without. Let me know If you have more questions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T16:52:49.280",
"Id": "506694",
"Score": "1",
"body": "Thank you - that makes a better question now!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T17:56:52.560",
"Id": "506814",
"Score": "0",
"body": "I would use a backtracking approach with some implication rules. So concretely, for any partial placement of skyscrapers, check first whether there are rows or columns with 3 skyscrapers, and put the remaining one in that square. I am sure you can think of a few more implications like this. Repeat these rules until nothing can be found.\n\nThen go to the next square and make a guess. Then do the rules again, and make sure to label which guess implies their placements. Check validity and repeat. If it is not valid, undo the latest guess and its implications and try the next guess."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T17:58:43.670",
"Id": "506816",
"Score": "0",
"body": "If you do not mind using functions you have not written yourself, you could formulate it as a SAT instance and use a SAT solver like minisat."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T21:39:54.007",
"Id": "506833",
"Score": "0",
"body": "Off topic: For those who'd like to implement the algorithm in their brain instead of a computer program and test it, this is a **Towers** puzzle from the **Simon Tatham's Portable Puzzle Collection** https://www.chiark.greenend.org.uk/~sgtatham/puzzles/"
}
] |
[
{
"body": "<h1>Don't generate all possible permutations</h1>\n<p>Generating all possible permutations will be horribly slow. If you treat the <span class=\"math-container\">\\$N \\times N\\$</span> board as a sequence of <span class=\"math-container\">\\$N^2\\$</span> values, where the values are <span class=\"math-container\">\\$1\\dots N\\$</span> with every value having equal probability, then the number of permutations is <span class=\"math-container\">\\$\\frac{N^2!}{N!^N}\\$</span>. If you generate all permutations for a single row, and repeat that for every row, then you still generate <span class=\"math-container\">\\$N\\cdot N!\\$</span> permutations. Try to calculate this for a few board sizes and you will quickly see the issue with this. Note that it doesn't matter that you filter out the impossible permutations; this might speed up the rest of the algorithm, but for large boards your runtime will be dominated by the algorithmic complexity of permutation generation.</p>\n<h1>Other ways to solve the game</h1>\n<p>Consider that humans solving these puzzles don't generate all permutations, but solve this puzzle in a very different way. Similar to Sudoku, the main trick is to note down for each grid cell what the possible values are. You start by allowing all <span class=\"math-container\">\\$N\\$</span> values, and based on the hints and grid cells for which you have already solved the height of the skyscraper, you remove values from the set that are not possible. You quickly narrow down the possibilities you have to check this way.</p>\n<p>So then the question is, how do we actually narrow down the possibilities? There are several heuristics that can be used, including:</p>\n<h2>Edge clues</h2>\n<p>Some clues at the edge will immediately tell us what the height is of towers in their row or column. For example, if an edge clue is 1 in an <span class=\"math-container\">\\$N \\times N\\$</span> game, then you know that the height of the skyscraper right next to the clue should be <span class=\"math-container\">\\$N\\$</span>. Similarly, if the edge clue is <span class=\"math-container\">\\$N\\$</span> then you know that in that row or column, the skyscapers are in sorted order from 1 to <span class=\"math-container\">\\$N\\$</span>.</p>\n<p>Other edge clues might also provide information, but typically they don't immediately reveal the height of skyscrapers, but rather limit the possibilities of their heights in certain positions.</p>\n<h2>Elimination</h2>\n<p>Once clues restrict the possible heights at a given position so much that only one possibility is left, you can fill in the height at that locations. At the same time, this means that that height value is no longer a valid option for any of the other positions in the same row and column. This eliminates more possibilities, and can reveal even more positions.</p>\n<h2>Trial and error</h2>\n<p>Once the above heuristics no longer eliminate possibilities or reveal heights, most humans will just start tying to guess a height at a certain position, and then try to see what they can then eliminate based on that, and so on, until either they solve the remainder of the puzzle, or hit a dead end. When you hit a dead end, you know that the choices you made up to that point were bad. This should also give you information.</p>\n<p>A typical way to do this programmatically is to use a <a href=\"https://en.wikipedia.org/wiki/Backtracking\" rel=\"nofollow noreferrer\">backtracking algorithm</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T20:11:31.700",
"Id": "506612",
"Score": "0",
"body": "I wonder how to prevent generate all. Currently I check all generated ones already if they can be valid ones on the board. How can I not generate some at all depending on the clues and present skyscrapers. I guess I really need some starting code. But the number of Permutations I generate is only N! already."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T20:13:57.860",
"Id": "506613",
"Score": "0",
"body": "So currently I generate all permutations for a row which is N!. Then I sort them in as possible permutations in the row depending on the clues and present scrapers. So I dont generate all for the whole board."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T20:39:50.110",
"Id": "506614",
"Score": "0",
"body": "Be aware that 11! is almost 40 million. CPU cycles are cheap, but you still have to multiply this by whatever else you do with these permutations. Also, storing this many permutations will require a lot of memory as well; if it doesn't fit in the CPU cache anymore things quickly become very slow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T06:36:02.843",
"Id": "506644",
"Score": "0",
"body": "Yes im aware that I still generate these 40 millions. I judt dont know a better way to not generate them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T07:27:10.637",
"Id": "506878",
"Score": "0",
"body": "Edge clues and Eliminations already happens in my code. The problem is with bigger sizes >4 with that alone you cannot solve the board. Only via the permutation generation and then consider with the clues I could get the solution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T07:28:42.450",
"Id": "506880",
"Score": "0",
"body": "The backtracking algorithm sounds interesting. I just have no idea how to implement it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T07:37:03.127",
"Id": "506884",
"Score": "1",
"body": "There are plenty of examples to be found if you search on the Internet for \"backtracking algorithm\". One of the top search results is https://www.geeksforgeeks.org/backtracking-algorithms/, have a look at that. You can also search for \"backtracking algorithm\" here on Code Review; there are plenty of questions where people want their implementations of backtracking algorithms reviewed, so you can learn from those as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T08:15:09.090",
"Id": "506892",
"Score": "0",
"body": "I will look into that. Im really curious if it will be really faster for big sizes like `n=11`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T08:29:46.647",
"Id": "506895",
"Score": "1",
"body": "I think I get it now Fill in skyscrapers and nopes from the clues and also nopes from existing skyscrapers. And only after then no solution is found use backtracking. That should narrow the possibilities already down quite a lot."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T16:52:35.177",
"Id": "507701",
"Score": "1",
"body": "I implemented the program with backtracking and wow is it fast. I think I will post that solution for annother code review because one unit test is extremly slow for n=7. All the other ones are blazing fast. Maybe there can be some more optimization in reducing the traverse paths."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T18:06:04.827",
"Id": "507954",
"Score": "0",
"body": "I solved it with backtracking. See here a new question: https://codereview.stackexchange.com/questions/257197/skyscraper-solver-for-nxn-size-version-2-using-backtracking"
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T19:54:38.163",
"Id": "256589",
"ParentId": "256579",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "256589",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T17:22:03.603",
"Id": "256579",
"Score": "3",
"Tags": [
"c++",
"performance",
"c++17"
],
"Title": "Skyscraper Solver for NxN Size"
}
|
256579
|
<p>So I have a solution for this which uses a for loop and calculates distance between the main point and other points. I found the code for distance between two points online, changed it to my needs and wrote the rest of the code. While this code works pretty well, I'm just curious if there's a better and more efficient way of doing this. This fits really well with my current code as it's just a small scale project. But I always like looking for stuff I can optimise and improve.</p>
<pre class="lang-js prettyprint-override"><code>function findDistanceInKm(location1, location2) {
const lat1 = location1.lat;
const lon1 = location1.lon;
const lat2 = location2.lat;
const lon2 = location2.lon;
const earthRadius = 6371;
const dLat = convertDegToRad(lat2 - lat1);
const dLon = convertDegToRad(lon2 - lon1);
const squarehalfChordLength =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(convertDegToRad(lat1)) * Math.cos(convertDegToRad(lat2)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
const angularDistance = 2 * Math.atan2(Math.sqrt(squarehalfChordLength), Math.sqrt(1 - squarehalfChordLength));
const distance = earthRadius * angularDistance;
return distance;
}
function convertDegToRad(deg) {
return deg * (Math.PI/180)
}
let nearLocations = [];
let newLocation = {
lat: 65.33714,
lon: -82.11508
}
let locationList = [
{
lat: 65.33714,
lon: -82.11503
},
{
lat: -1.38370,
lon: 10.32156
},
{
lat: -69.98601,
lon: 18.80178
},
{
lat: -29.37968,
lon: -156.32350
},
]
for(let i =0; i < locationList.length; i++){
let distance = findDistanceInKm(newLocation, locationList[i]);
console.log(distance)
if(distance < 1){
nearLocations.push(locationList[i])
}
}
</code></pre>
|
[] |
[
{
"body": "<p>There are a number of performance optimization tricks that you can take advantage of when trying to find efficiency. One mechanism commonly used is to reduce complexity of the code by algorithmic change..... but in your case, you can't really improve the "Big O" complexity that way, you are running at O(n) already, and there's nothing you can do to improve that.</p>\n<p>So, it then comes down to nickel-and-diming the current algorithm to shave time off of the work you're already doing. This requires looking at the expensive computations, and reducing the number of operations to improve them.</p>\n<p>In your example, you're converting degrees to radians often. In the case of <code>newLocation</code> you're doing it repeatedly for each comparison. It would make sense for you to convert all locations to radian form, and then not have any conversions inside the computation loop. This will be especially useful if your real-world code has to do multiple comparisons on the locations.</p>\n<p>So, simply doing something like (include the radian values as part of the location):</p>\n<pre><code>func locationToRadians(degrees) {\n return {\n lat: degrees.lat,\n lon: degrees.lon,\n rlat: convertDegToRad(degrees.lat),\n rlon: convertDegToRad(degrees.long)\n }\n}\n\n\nconst locationListRadians = locationList.map(locationToRadians);\n</code></pre>\n<p>Do the same with the <code>fromLocation</code>.</p>\n<p>Now, in your distance function, you're repeating complex computations (trig functions are non-trivial at a computational level, so let's avoid repeats - I realize that premature optimization is not always great, but this also improves the readability). Your distance computation is significantly simpler:</p>\n<pre><code>function findDistanceInKm(location1, location2) {\n const sinLat = Math.sin((location2.rlat - location1.rlat) / 2);\n const sinLon = Math.sin((location2.rlon - location1.rlon) / 2);\n const earthRadius = 6371;\n const squarehalfChordLength =\n sinLat * sinLat +\n sinLon * sinLon *\n Math.cos(location1.rlat) * Math.cos(location2.rlat);\n\n const angularDistance = 2 * Math.atan2(Math.sqrt(squarehalfChordLength), Math.sqrt(1 - squarehalfChordLength));\n const distance = earthRadius * angularDistance;\n return distance;\n}\n</code></pre>\n<p>Now, you can add in the distances that way.</p>\n<p>The savings from doing the above will only be noticeable if you reuse computations often, but in a busy system where lots of locations are being repeatedly compared to each other I can easily see a 50% CPU saving.</p>\n<p>As a final comment, the last loop does not need the indexing mechanism, a filter is better:</p>\n<pre><code>const neadLocations = locationList.filter(location => {\n const distance = findDistanceInKm(newLocation, location);\n console.log(distance);\n return distance < 1\n});\n</code></pre>\n<p>(it would be better without the console logging in there...)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T16:04:36.673",
"Id": "506687",
"Score": "1",
"body": "Wow I didn't really expect this in depth of an answer, thank you so much. Will make changes to the current code. Thank you again"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T01:33:27.247",
"Id": "256601",
"ParentId": "256580",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "256601",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T17:53:23.887",
"Id": "256580",
"Score": "4",
"Tags": [
"javascript",
"coordinate-system"
],
"Title": "Get locations that are x km away using Latitude/Longitude"
}
|
256580
|
<p>How can I decrease the time complexity and increase efficiency, without writing a new algorithm. My solution solves the majority of puzzles in a fast time, but for some difficult ones it can take over a minute! I have added some of the difficult puzzles below the code.</p>
<pre><code>import numpy as np
from skimage.util import view_as_blocks # pip install scikit-image
#input: 9x9 numpy array, empty cell = 0
#output: 9x9 numpy array: if not solution all array entries should be -1
#backtracking depth-first search with constraint propagation
#searches for 0 value in board
def zero_search(sudoku):
for i in range(len(sudoku)):
for j in range(len(sudoku[0])):
if sudoku[i][j] == 0:
return (i, j) # row, col
return False
#parameters: board, num = inserted value, pos = board position(vector/tuple)
def valid(sudoku, num, pos):
# Check row
for i in range(len(sudoku[0])):
if sudoku[pos[0]][i] == num and pos[1] != i:
return False
# Check column
for i in range(len(sudoku)):
if sudoku[i][pos[1]] == num and pos[0] != i:
return False
# Check box
box_x = pos[1] // 3
box_y = pos[0] // 3
#y-axis/columns
for i in range(box_y*3, box_y*3 + 3):
#x-axis/rows
for j in range(box_x * 3, box_x*3 + 3):
if sudoku[i][j] == num and (i,j) != pos:
return False
return True
def solver(sudoku):
find = zero_search(sudoku)
if not find:
return True
else:
row, col = find
#check insertion values 1-9
for i in range(1,10):
if valid(sudoku, i, (row, col)):
sudoku[row][col] = i
if solver(sudoku):
return True
sudoku[row][col] = 0
return False
def initial_invalid(sudoku):
# Check row
for i in range(9):
dup_lst=[]
for j in range(9):
if sudoku[j][i]!=0:
if sudoku[j][i] in dup_lst:
return True
else:
dup_lst.append(sudoku[j][i])
#check column
for i in range(9):
dup_lst=[]
for j in range(9):
if sudoku[i][j]!=0:
if sudoku[i][j] in dup_lst:
return True
else:
dup_lst.append(sudoku[i][j])
#not needed
def final_valid (sudoku):
subgrids = view_as_blocks(sudoku, (3, 3))
sums = [np.sum(subgrids[i][j]) for j in range(3) for i in range(3)]
if sum(sums) !=405:
return False
else:
return True
#row_sum = sudoku.sum(axis=1)
#if sum(row_sum) != 405:
# return False
#col_sum = sudoku.sum(axis=0)
#if sum(col_sum) != 405:
# return False
def sudoku_solver(sudoku):
if initial_invalid(sudoku):
return np.full((9,9),-1)
if solver(sudoku):
return sudoku
else:
return np.full((9,9),-1)
</code></pre>
<pre class="lang-py prettyprint-override"><code>[[0 8 0 4 3 0 0 0 0]
[0 0 5 0 0 9 0 0 0]
[6 0 0 0 8 0 0 7 0]
[0 0 0 0 9 0 0 0 3]
[0 0 0 8 0 7 0 0 0]
[9 0 0 0 0 0 0 5 4]
[0 6 0 0 0 0 0 0 5]
[0 0 8 0 0 0 4 0 0]
[0 4 0 0 0 6 0 1 0]]
[[0 0 2 0 0 0 0 0 4]
[0 5 0 0 1 3 7 0 0]
[7 9 0 0 0 0 0 5 0]
[0 0 9 0 0 0 0 6 0]
[0 0 0 0 3 0 5 0 8]
[5 0 7 0 0 0 4 0 0]
[0 0 0 0 6 0 8 0 0]
[0 6 0 0 2 7 0 4 0]
[8 0 0 0 0 0 0 2 0]]
[[0 0 0 6 0 0 2 0 0]
[0 0 0 0 0 9 0 6 0]
[0 8 0 0 0 5 0 0 3]
[1 0 0 4 0 0 9 0 0]
[8 3 0 0 0 0 0 0 0]
[0 2 0 0 0 6 0 0 0]
[0 0 0 0 6 0 0 0 0]
[2 5 0 3 0 7 0 9 0]
[0 0 1 0 0 0 0 8 4]]
</code></pre>
|
[] |
[
{
"body": "<h2>Keep track of possible values</h2>\n<p>A comment in your code says:</p>\n<blockquote>\n<p>#backtracking depth-first search with constraint propagation</p>\n</blockquote>\n<p>...but you're not actually propagating constraints. You can reduce the number of move validations by keeping track of the possible moves, i.e. the values a cell can actually have. Each inserted value (correct or not) constrains the possible values of cells in the same row, column and box, thus reducing the number of values you have to consider in subsequent recursive calls.</p>\n<h2>Choose empty cells with least number of possible values</h2>\n<p>You're choosing the first empty cell. If that happens to have very little constraints, you're unnecessarily exploring a lot of possibilities that may have been invalidated if you had chosen a different cell first. Choosing the empty cell with the least number of possible values drastically reduces the breadth of your depth-first search tree.</p>\n<h2>Example implementation</h2>\n<p>I tried to stay close to your original code and this code should only demonstrate how you can implement the mentioned concepts. There are still things that could be improved, but since you specifically asked about time complexity I concentrated purely on that.</p>\n<pre><code>import numpy as np\nfrom skimage.util import view_as_blocks # pip install scikit-image\n\n# input: 9x9 numpy array, empty cell = 0\n# output: 9x9 numpy array: if not solution all array entries should be -1\n# backtracking depth-first search with constraint propagation\n\n\n# Returns (row, col) of an empty cell with the least number of possible values.\n# Returns False if no empty cell exists.\ndef get_emtpy_cell_with_least_possible_values(sudoku, possible_values):\n min_possible_values = 10\n min_row = -1\n min_col = -1\n for i in range(len(sudoku)):\n for j in range(len(sudoku[0])):\n if sudoku[i][j] == 0:\n num_possible_numbers = sum(possible_values[i][j])\n if num_possible_numbers < min_possible_values:\n min_possible_values = num_possible_numbers\n min_row = i\n min_col = j\n if min_possible_values < 10:\n return (min_row, min_col)\n else:\n # No empty cell found\n return False\n\n\ndef remove_possible_values(possible_values, row, col, value):\n """ Remove 'value' from the possible values in row, col, and the box containing\n cell [row][col]. Returns a list of tuples (row, col) for each cell that has been changed.\n """\n cells_changed = []\n for c_index, c in enumerate(possible_values[row]):\n if c[value - 1] == 1:\n cells_changed.append((row, c_index))\n c[value - 1] = 0\n\n for r in range(9):\n if possible_values[r][col][value - 1] == 1:\n cells_changed.append((r, col))\n possible_values[r][col][value - 1] = 0\n\n # Check box\n box_x = col // 3\n box_y = row // 3\n\n # y-axis/columns\n for i in range(box_y*3, box_y*3 + 3):\n # x-axis/rows\n for j in range(box_x * 3, box_x*3 + 3):\n if possible_values[i][j][value - 1] == 1:\n cells_changed.append((i,j))\n possible_values[i][j][value - 1] = 0\n return cells_changed\n\ndef restore_possible_values(possible_values, value, changed_cells):\n """ Restore 'value' as possible value for each cell (row, col) in 'changed_cells'.\n """\n for row, col in changed_cells:\n possible_values[row][col][value - 1] = 1\n\n\ndef solver(sudoku, possible_values):\n next_cell = get_emtpy_cell_with_least_possible_values(sudoku, possible_values)\n if not next_cell:\n return True\n else:\n row, col = next_cell\n\n # check insertion values 1-9\n for guessed_value in range(1, 10):\n if possible_values[row][col][guessed_value - 1] != 1:\n continue\n # update possible values and sudoku board for recursive call\n changed_cells = remove_possible_values(possible_values, row, col, guessed_value)\n sudoku[row][col] = guessed_value\n\n if solver(sudoku, possible_values):\n return True\n # restore possible values and sudoku board for next iteration\n restore_possible_values(possible_values, guessed_value, changed_cells)\n sudoku[row][col] = 0\n\n return False\n\n\ndef initial_invalid(sudoku):\n\n # Check row\n for i in range(9):\n dup_lst = []\n for j in range(9):\n if sudoku[j][i] != 0:\n if sudoku[j][i] in dup_lst:\n return True\n\n else:\n dup_lst.append(sudoku[j][i])\n\n # check column\n for i in range(9):\n dup_lst = []\n for j in range(9):\n if sudoku[i][j] != 0:\n if sudoku[i][j] in dup_lst:\n return True\n\n else:\n dup_lst.append(sudoku[i][j])\n\n\n\ndef sudoku_solver(sudoku):\n\n if initial_invalid(sudoku):\n return np.full((9, 9), -1)\n\n possible_values = np.ones((9,9,9), dtype=int)\n # initialize possible values based on already existing values\n for row in range(9):\n for col in range(9):\n value = sudoku[row][col]\n if value != 0:\n remove_possible_values(possible_values, row, col, value)\n\n if solver(sudoku, possible_values):\n return sudoku\n else:\n return np.full((9, 9), -1)\n\n</code></pre>\n<p>Some measurements on my computer using your examples:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th></th>\n<th>original code</th>\n<th>improved code</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Sudoku 1</td>\n<td>21.836s</td>\n<td>1.449s</td>\n</tr>\n<tr>\n<td>Sudoku 2</td>\n<td>2.753s</td>\n<td>0.639s</td>\n</tr>\n<tr>\n<td>Sudoku 3</td>\n<td>50.993s</td>\n<td>0.479s</td>\n</tr>\n</tbody>\n</table>\n</div>",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T17:39:32.050",
"Id": "256627",
"ParentId": "256582",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "256627",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T18:00:07.550",
"Id": "256582",
"Score": "1",
"Tags": [
"python",
"performance",
"numpy"
],
"Title": "decreasing solver speed"
}
|
256582
|
<p>In option API <em>(Vue 2 syntax which is still available in version 3)</em> we could extract some repeated pieces inside many components and define them as mixin that could be reusable like :</p>
<pre><code>const colorable = {
props: {
bgColor: {
type: String,
default: "",
},
color: {
type: String,
default: "",
},
},
computed:{
colorClasses(){
return `text--${this.color} bg--${this.bgColor}`
}
}
}
</code></pre>
<p>then we use that mixin in any component like :</p>
<pre><code>mixins:[colorable]
</code></pre>
<p>In vue 3 they introduced the new composition api that enforces the code reusability and organization, so if we want to convert the code above to be compatible with this API we could do something like :</p>
<pre><code>const colorable = {
props: {
// the same props as above
},
}
</code></pre>
<p>and composable function :</p>
<pre><code>const useColor=(props)=>{
return {
classes: computed(()=>`text--${props.color} bg--${props.bgColor}`)
}
}
</code></pre>
<p>then in some component :</p>
<pre><code>mixins:[colorable],
setup(props){
const {classes}=useColor(props);
return {classes}
}
}
</code></pre>
<p>This works fine I look for a better solution to get rid of the <code>mixins</code> option.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T18:32:24.883",
"Id": "256584",
"Score": "0",
"Tags": [
"javascript",
"typescript",
"vue.js"
],
"Title": "What's the best way to make props reusable across many components in Vue.js 3?"
}
|
256584
|
<p>Below is my code for the problem:</p>
<pre><code>ItoR = {
1: 'I',
4: 'IV',
5: 'V',
9: 'IX',
10: 'X',
40: 'XL',
50: 'L',
90: 'XC',
100: 'C',
400: 'CD',
500: 'D',
900: 'CM',
1000: 'M'
}
def convertItoR(number):
number_str = str(number)
number_len = len(number_str)
rom_str = ''
for i in range(number_len):
# Extracting the digit
digit = int(number_str[i])
position = number_len - i - 1
num_pos = digit * 10 ** position
print(num_pos)
# Converting digit to roman string
if num_pos in ItoR.keys():
rom_str += ItoR[num_pos]
elif digit > 1 and digit < 4:
first = 1 * 10 ** position
rom_str += ItoR[first] * digit
elif digit > 5 and digit < 9:
first = 1 * 10 ** position
fifth = 5 * 10 ** position
rom_str += ItoR[fifth] + ItoR[first] * (digit - 5)
print(rom_str)
return rom_str
</code></pre>
<p>Can it be optimized?</p>
|
[] |
[
{
"body": "<p>maybe if you introduce a layer for positioning to your map, you could make the code slightly more readable (use the position instead of calculating map index):</p>\n<pre><code>ItoR = {\n1: {1: 'I',\n 4: 'IV',\n 5: 'V',\n 9: 'IX'},\n2: {\n 1: 'X',\n 4: 'XL',\n 5: 'L',\n 9: 'XC'},\n...\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T19:53:42.377",
"Id": "256588",
"ParentId": "256586",
"Score": "2"
}
},
{
"body": "<p>You asked about optimization, which usually refers either to speed or memory\nusage, neither of which apply in this case. Your code has negligible memory\ncost. And if we truly cared about the ability to convert large volumes of\nnumbers at high speed, we would pre-compute a dict mapping every decimal number\nof interest to its Roman equivalent.</p>\n<p>If I were you, I would focus on optimizing this problem for simplicity of\nunderstanding and code readability. Your current code appears to be fine, and\none can definitely figure it out, but it still requires some puzzling over. The\nclassic way that I've seen people solve this problem more simply is to build up\nthe Roman numeral by subtracting away even multiples of each divisor in your\n<code>dict</code> mapping divisors to Roman symbols. The trick is to proceed from largest\ndivisor to smallest. Since Python 3 preserves order in dicts, we can\nachieve that simply by reversing the order in which the data is set up.\nThe basic idea is illustrated below.</p>\n<pre><code>def decimal_to_roman(num):\n # The Romans had "integers" too, so this seems like a more\n # accurate function name.\n\n # You should add a check here to validate that the given decimal\n # number falls within the supported ranged.\n\n # Relies on Python 3 having ordered dicts.\n divisors = {\n 1000: 'M',\n 900: 'CM',\n 500: 'D',\n 400: 'CD',\n 100: 'C',\n 90: 'XC',\n 50: 'L',\n 40: 'XL',\n 10: 'X',\n 9: 'IX',\n 5: 'V',\n 4: 'IV',\n 1: 'I',\n }\n\n # Build up the Roman numeral by subtracting multiples of\n # each divisor, proceeding from largest to smallest.\n roman = ''\n for div, sym in divisors.items():\n quotient = divmod(num, div)[0]\n roman += sym * quotient\n num -= div * quotient\n if num < 1:\n break\n return roman\n</code></pre>\n<p>When deciding on names for functions, variables, and so forth, aim for accuracy\nand clarity in situations where the additional context is needed for\nreadability. This is a case where slightly longer names are appropriate (for\nexample, <code>decimal_to_roman</code>, <code>divisors</code>, and <code>quotient</code>). But when the\nsurrounding context and nearby names provide sufficient clues, you can aim for\nbrevity to reduce the visual weight of the code -- which also helps with\nreadability, but from a different direction. For example, within the narrow\ncontext of this function, the short names like <code>num</code>, <code>div</code>, and <code>sym</code> are\neasily understood without giving them fully explicit names.</p>\n<p>Finally, how do you know your code is correct? If you're trying to learn, you\ncould consider writing the corresponding <code>roman_to_decimal()</code> function and then\nmake sure your converters can round-trip the data correctly. Another approach\nis to find one of the many Python functions floating around the internet and use\nit as your checker. Or you can install the\n<a href=\"https://github.com/zopefoundation/roman\" rel=\"nofollow noreferrer\">roman</a> Python package to check\neverything, as shown here:</p>\n<pre><code>import roman\n\nfor n in range(1, 4000):\n exp = roman.toRoman(n)\n got = decimal_to_roman(n)\n if exp != got:\n print(n, exp, got)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T23:40:48.890",
"Id": "256599",
"ParentId": "256586",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T19:02:44.933",
"Id": "256586",
"Score": "4",
"Tags": [
"python",
"performance",
"python-3.x"
],
"Title": "Converting Integers to roman between 1 and 1000"
}
|
256586
|
<p>A problem from Coderbyte. Find the longest word in a sentence after removing the punctuations and if two or more words are of same length return the first word</p>
<p>Below is my solution:</p>
<pre><code>def cleanWord(word):
# To remove punctuations
punctuations = ['!','.','\'','"',',','&']
new_word = ''
for c in word:
if c in punctuations:
continue
else:
new_word += c
return new_word
def LongestWord(sen):
words = sen.split(' ')
word_lengths = {}
# finding length of each word
for word in words:
clean_word = cleanWord(word)
if len(clean_word) not in word_lengths.keys():
word_lengths[len(clean_word)] = word
longest_word_length = max(word_lengths.keys())
longest_word = word_lengths[longest_word_length]
#print(word_lengths)
return longest_word
</code></pre>
|
[] |
[
{
"body": "<pre><code>def cleanWord(word):\n # To remove punctuations\n</code></pre>\n<p>The comment is a better name <code>without_punctuation</code>. Also you should be following snake case as per PEP-8.</p>\n<p>Much of your logic in the longest word function can be handled by <code>max</code> with a key function. The overall solution can be written like so.</p>\n<pre><code>def without_punctuation(text): \n translator = str.maketrans('','',string.punctuation) \n return text.translate(translator) \n \ndef longest_word(sentence): \n words = without_punctuation(sentence).split() \n return max(words,key=len)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T22:14:40.387",
"Id": "506621",
"Score": "0",
"body": "If the sentence is written like your code, i.e., without the standard space after commas (rather bad for someone pointing out PEP 8 :-), then you incorrectly combine words."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T21:57:16.947",
"Id": "256593",
"ParentId": "256590",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T21:13:19.117",
"Id": "256590",
"Score": "-1",
"Tags": [
"python",
"algorithm",
"python-3.x",
"strings"
],
"Title": "Finding longest word in a sentence"
}
|
256590
|
<p>I have recently been in a situation where multiple developers worked on a shared local git repository under the same Linux user¹. As one can imagine, it can easily become a bit annoying not to commit changes as someone else if you don't check the values of <code>git config user.name</code> and <code>git config user.email</code> carefully and then change them accordingly. The same problem might also arise if you happen to work on several projects on your local machine side-by-side where you have to use different "identities", e.g. some work-related and private projects. I decided to tackle this with a little "git extension" that allows you to view and change the committer identity with less of a hassle.</p>
<p>Enter <code>git user</code>. To get an idea of its intended use, have a look at the output of <code>git user -h</code>:</p>
<pre class="lang-none prettyprint-override"><code>git-user - Helps you to manage multiple users in a shared local repository
Subcommands
-----------
add, update, show, delete
Use git user <subcommand> --help to get more help
Examples
--------
# Add two test users
> git user add itsme "My Last" my.last@domain.tld --credential-username itsme
> git user add itsyou "Your Last" your.last@domain.tld
# activate the first user
> git user itsme
My Last <my.last@domain.tld>
# you can check this yourself with git config.name and git config user.email
# activate the second user
> git user itsyou
Your Last <your.last@domain.tld>
# use git user with no arguments to check which values are currently set
> git user
Your Last <your.last@domain.tld>
> git user show
itsme: My Last <my.last@domain.tld> (push as 'itsme')
itsyou: Your Last <your.last@domain.tld>
> git user delete itsyou --force
> git user show
itsme: My Last <my.last@domain.tld>
</code></pre>
<p>The code that makes this possible is as follows:</p>
<pre class="lang-python prettyprint-override"><code>#!/usr/bin/env python3
"""
... omitted for brevity, see help text in question ...
"""
import argparse
import json
import os
import sys
from collections import defaultdict
from subprocess import check_output, CalledProcessError, DEVNULL
DESCRIPTION = sys.modules[__name__].__doc__
__version__ = "0.2.0"
class UserbaseError(Exception):
"""Base class for userbase related exceptions"""
class UserDoesNotExist(UserbaseError):
"""Custom exception to indicate that a user does not exist"""
class UserDoesAlreadyExist(UserbaseError):
"""Custom exception to indicate that a user does already exist"""
class Userbase:
"""Abstraction of the underlying user storage file"""
DATA_KEYS = ("name", "email", "credential_username")
def __init__(self, users_file):
self._users_file = users_file
self._users = defaultdict(lambda: defaultdict(str))
self._load()
def _load(self):
if not os.path.isfile(self._users_file):
print("Creating default at '{}'.".format(self._users_file))
os.makedirs(os.path.dirname(self._users_file))
self.save()
with open(self._users_file, "r") as json_file:
self._users.update(json.load(json_file))
def save(self):
"""Dump the current userbase to file"""
with open(self._users_file, "w") as json_file:
json.dump(self._users, json_file)
def is_known(self, alias):
"""Check if an alias is part of the userbase"""
return alias in self._users
def get(self, alias):
"""Try to get user data for an alias
Parameters
----------
alias: str
access the data stored under this alias
Returns
-------
dict
the data associated with the alias. Keys are listed in
Userbase.DATA_KEYS
Raises
------
UserDoesNotExist
If the user is not part of the userbase
"""
if self.is_known(alias):
return self._users[alias]
raise UserDoesNotExist(
"User with alias '{}' unknown".format(alias)
)
def as_dict(self):
"""Access the userbase as a dict"""
return dict(self._users)
def update(self, alias, **kwargs):
"""Update the data stored under an alias
This function does not check whether the user exists or not. If it
exists, its data will simply be overwritten.
Parameters
----------
alias: str
update the data found under this alias
kwargs: dict
the script will look for the keys from Userbase.DATA_KEYS in the
kwargs in order to update the internal database
"""
for key in Userbase.DATA_KEYS:
new_value = kwargs[key]
if new_value is not None:
self._users[alias][key] = new_value
def delete(self, alias):
"""Delete a user from the userbase given its alias
Parameters
----------
alias: str
the alias to look for
Raises
------
UserDoesNotExist
you can probably guess when this is raised
"""
try:
del self._users[alias]
except KeyError:
raise UserDoesNotExist(
"User with alias '{}' unknown".format(alias)
)
try:
_USERS_FILE = os.environ["GITUSER_CONFIG"]
except KeyError:
_USERS_FILE = os.path.join(
os.path.expanduser("~"), ".config", "git-user", "users.json"
)
_USERS_FILE = os.path.abspath(_USERS_FILE)
_USERS = Userbase(_USERS_FILE)
def add(args):
"""Add a user to the userbase"""
if _USERS.is_known(args.alias):
raise UserDoesAlreadyExist(
"User with alias '{}' already exist. ".format(args.alias)
+ "Delete first or use 'update'"
)
kwargs = {name: getattr(args, name, "") for name in Userbase.DATA_KEYS}
_USERS.update(args.alias, **kwargs)
def update(args):
"""Interactive wrapper around Userbase.update"""
if not _USERS.is_known(args.alias):
raise UserDoesAlreadyExist(
"User with alias '{}' does not exist. ".format(args.alias)
+ "Add first using 'add'"
)
kwargs = {name: getattr(args, name, "") for name in Userbase.DATA_KEYS}
_USERS.update(args.alias, **kwargs)
def delete(args):
"""Interactivate wrapper around Userbase.delete"""
if _USERS.is_known(args.alias) and not args.force:
while True:
answer = input(
"Really delete user '{}'? [N/y] ".format(args.alias)
)
answer = answer.lower().strip()
if answer in ("yes", "y"):
break
if answer in ("no", "n", ""):
return
_USERS.delete(args.alias)
def show(args):
"""Show the data of one or all the users in the userbase"""
to_show = tuple(sorted(_USERS.as_dict().keys()))
if args.alias is not None:
to_show = (args.alias, )
if to_show:
for alias in to_show:
cfg = _USERS.get(alias)
msg = " {}: {name} <{email}>".format(alias, **cfg)
if "credential_username" in cfg.keys():
msg += " (push as '{credential_username}')".format(**cfg)
print(msg)
else:
print("No known aliases.")
def switch(args):
"""Switch to an other user from the userbase and/or show current config
Set args.quiet to True to avoid seeing the current config as console output
"""
if args.alias is not None:
cfg = _USERS.get(args.alias)
_git_config_name(cfg["name"])
_git_config_email(cfg["email"])
credential_username = cfg.get("credential_username", "")
try:
_git_config_credential_username(credential_username)
except CalledProcessError as ex:
if credential_username not in ("", None):
raise ex
if not args.quiet:
_show_git_config()
def _show_git_config():
try:
git_name = _git_config_name().strip().decode("utf8")
git_email = _git_config_email().strip().decode("utf8")
except CalledProcessError:
print(
"Currently there is no (default) user for this repository.\n"
"Select one using git user <alias> or manually with git config"
)
return
try:
git_cred_username = _git_config_credential_username().strip().decode("utf8")
print("{} <{}> (push as '{}')".format(git_name, git_email, git_cred_username))
return
except CalledProcessError:
# git config has a non-zero exit status if no value is set
pass
print("{} <{}>".format(git_name, git_email))
def _git_config_name(name=None):
args = ["git", "config", "user.name"]
if name is not None:
args.append(str(name))
return check_output(args)
def _git_config_email(email=None):
args = ["git", "config", "user.email"]
if email is not None:
args.append(str(email))
return check_output(args)
def _git_config_credential_username(username=None):
# remote_url = _git_get_remote_url(remote).strip().decode("utf8")
args = ["git", "config"]
if username == "":
args.extend(["--remove-section", "credential"])
else:
args.append("credential.username")
if username is not None:
args.append(username)
return check_output(args, stderr=DEVNULL)
def main():
"""CLI of the git user helper"""
parser = argparse.ArgumentParser(
description=DESCRIPTION, formatter_class=argparse.RawTextHelpFormatter)
# click might be an alternative here, but I want this to be as lightweight
# as possible
try:
command = sys.argv[1]
except IndexError:
command = "switch"
if command in ("add", "update", "delete", "show"):
subparsers = parser.add_subparsers()
add_subparser = subparsers.add_parser(
"add", description="Add name and email for an alias")
add_subparser.add_argument(
"alias", help="Alias used to access this user's name and email")
add_subparser.add_argument(
"name", help="This value gets passed to git config user.name",
default="")
add_subparser.add_argument(
"email", help="This value gets passed to git config user.email",
default="")
add_subparser.add_argument(
"--credential-username",
help="optional: push credential username",
default="")
add_subparser.set_defaults(command=add)
update_subparser = subparsers.add_parser(
"update", description="Update an alias")
update_subparser.add_argument(
"alias", help="Alias used to access this user's name and email")
update_subparser.add_argument(
"--name", help="This value gets passed to git config user.name",
default=None)
update_subparser.add_argument(
"--email", help="This value gets passed to git config user.email",
default=None)
update_subparser.add_argument(
"--credential-username",
help="optional: push credential username",
default=None)
update_subparser.set_defaults(command=update)
delete_subparser = subparsers.add_parser(
"delete", description="Delete name and email stored for an alias")
delete_subparser.add_argument(
"alias", help="Delete name, email and possibly credentials for this alias")
delete_subparser.add_argument(
"--force", action="store_true", help="Delete without interaction"
)
delete_subparser.set_defaults(command=delete)
show_subparser = subparsers.add_parser(
"show",
description="Show name and email associated with this alias")
show_subparser.add_argument("alias", nargs="?", default=None)
show_subparser.set_defaults(command=show)
else:
parser.add_argument(
"alias",
nargs="?",
default=None,
help="Use git config with name and email that belong to this alias")
parser.add_argument(
"--quiet", action="store_true",
help="Suppress confirmation output after setting the config"
)
parser.add_argument(
"--version", action="store_true",
help="show git and git-user version and exit"
)
parser.set_defaults(command=switch)
args = parser.parse_args()
if getattr(args, "version", False):
print("git-user version {}".format(__version__))
return
try:
args.command(args)
except (UserbaseError, CalledProcessError) as err:
print(err)
sys.exit(1)
# only save on proper exit
_USERS.save()
if __name__ == "__main__":
main()
</code></pre>
<p>To test it, copy and paste the file somewhere in your <code>$PATH</code> where git can pick it up, name it <code>git-user</code> and make it executable. A symlink with this name is also possible if you prefer to have the file with a <code>.py</code> extension.</p>
<h3>Notes to kind reviewers</h3>
<ul>
<li>Every kind of feedback is welcome. I'm also especially interested, how the script worked for you regarding usability. Was the help text actually, well, helpful?</li>
<li>As one of the comments tells, I knowingly ignored possibly useful packages like <code>click</code> in order to allow this to run on systems with no additional python packages.</li>
<li>Support for signature keys that would make it easier to sign your commits as well is on the TODO list, but not implemented yet.</li>
<li>The code was checked with <code>pylint</code> and <code>pycodestyle</code>, so it should be in a reasonable shape regarding code style.</li>
</ul>
<hr />
<p>¹ Whether or not this is a good idea might be arguable, but that's not the point here.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T12:31:26.463",
"Id": "507144",
"Score": "1",
"body": "I'm wondering why you didn't avoid the whole problem by adding the shared repository as a remote for the different developers, but I'm not gonna judge :D"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T08:36:17.167",
"Id": "507223",
"Score": "0",
"body": "@Vogel612 Yeah, that would be the most sensible choice. But unfortunately a few ideas/concepts from the SVN world are deeply stuck in the habits of some people ;-) And as of now, I have not been able to drive them off of them."
}
] |
[
{
"body": "<p>It's great I'd say, nothing really to complain except the suggestion to\nhandle missing files more gracefully:</p>\n<ul>\n<li>Run the script, <code>/home/ferada/.config/git-user/users.json</code> gets created successfully.</li>\n<li>Delete that file.</li>\n<li>Run the script again, get a crash.</li>\n</ul>\n<pre><code>0 codementor % python3 git-user.py\nCreating default at '/home/ferada/.config/git-user/users.json'.\nTraceback (most recent call last):\n File "git-user.py", line 134, in <module>\n _USERS = Userbase(_USERS_FILE)\n File "git-user.py", line 37, in __init__\n self._load()\n File "git-user.py", line 42, in _load\n os.makedirs(os.path.dirname(self._users_file))\n File "/usr/lib/python3.8/os.py", line 223, in makedirs\n mkdir(name, mode)\nFileExistsError: [Errno 17] File exists: '/home/ferada/.config/git-user'\n</code></pre>\n<p>The <code>os.makedirs</code> call needs an <code>exist_ok=True</code> parameter, then that\ngets handled.</p>\n<hr />\n<p>Maybe the argument parser construction should really be separated from\nthe <code>main</code> function, it's a distinct functionality and could very well\nbe tested separately.</p>\n<p><code>_git_config_name</code> and <code>_git_config_email</code> could always to <code>strip</code> and\n<code>decode</code>, that seems better than doing it on all but one call site\nanyway.</p>\n<p>The <code>--version</code> flag also has special handling in <code>argparse</code> which you\ncould use, c.f. <code>version=</code> for <code>add_argument</code>.</p>\n<p>On that note, I don't like that <code>--help</code> doesn't give me a full list of\nthe subcommands because it's construction is split in two parts. While\nreading about that topic of default subparsers (which I thought is how\nthis might be handled) it looks like that is fraught with peril.</p>\n<p>So, might I simply suggest that the possible subcommands are mentioned\nin the top-level <code>--help</code> output? Or you did already do that and\nomitted it as said in the help text. Well, at least you know your users\ndefinitely will want that help information.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T13:46:48.977",
"Id": "507684",
"Score": "1",
"body": "Thanks very much. Great find on that `os.makedirs` error! Re: your comment on the help text: the full help text is shown in the question. If what you are looking for is not in there, well, ... my fault I guess ;-) The \"two stage help text\" with `git user -h`, where the subcommands are shown (maybe I've missed some), and e.g. `git user add -h` is similar to how git handles this, see e.g. `git remote add -h`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T12:45:23.077",
"Id": "257065",
"ParentId": "256591",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "257065",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T21:41:31.197",
"Id": "256591",
"Score": "8",
"Tags": [
"python",
"python-3.x",
"console",
"git"
],
"Title": "git-user - Working on a shared local repository with multiple users made easier"
}
|
256591
|
<p><a href="https://leetcode.com/problems/sort-the-matrix-diagonally/" rel="nofollow noreferrer">https://leetcode.com/problems/sort-the-matrix-diagonally/</a></p>
<p><a href="https://i.stack.imgur.com/fAUac.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fAUac.png" alt="enter image description here" /></a></p>
<blockquote>
<p>A matrix diagonal is a diagonal line of cells starting from some cell
in either the topmost row or leftmost column and going in the
bottom-right direction until reaching the matrix's end. For example,
the matrix diagonal starting from mat[2][0], where mat is a 6 x 3
matrix, includes cells mat[2][0], mat<a href="https://i.stack.imgur.com/fAUac.png" rel="nofollow noreferrer">3</a>, and mat[4][2].</p>
<p>Given an m x n matrix mat of integers, sort each matrix diagonal in
ascending order and return the resulting matrix.</p>
</blockquote>
<p>my idea is to run as a BFS on the matrix. each cell visit top and right cells. to form a diagonal and sort it.</p>
<p>please review for performance. it took 30 mins to write the code. review this please as this is a coding interview.</p>
<pre><code>using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace ArrayQuestions
{
/// <summary>
/// https://leetcode.com/problems/sort-the-matrix-diagonally/
/// </summary>
[TestClass]
public class MatrixDiagonalSortTest
{
[TestMethod]
public void TestMethod1()
{
int[][] input = { new[] { 3, 3, 1, 1 }, new[] { 2, 2, 1, 2 }, new[] { 1, 1, 1, 2 } };
int[][] output = { new[] { 1, 1, 1, 1 }, new[] { 1, 2, 2, 2 }, new[] { 1, 2, 3, 3 } };
var res = DiagonalSort(input);
for (int r = 0; r < res.Length; r++)
{
CollectionAssert.AreEqual(output[r], res[r]);
}
}
public int[][] DiagonalSort(int[][] mat)
{
Queue<Cell> Q = new Queue<Cell>();
Q.Enqueue(new Cell(mat.Length-1, 0, mat[mat.Length-1][0]));
while (Q.Count > 0)
{
List<Cell> tempList = new List<Cell>();
int count = Q.Count;
for (int i = 0; i < count; i++)
{
var curr = Q.Dequeue();
tempList.Add(curr);
int newR = curr.r - 1;
int newC = curr.c;
if (newR >= 0)//go up
{
if (Q.FirstOrDefault(x => x.r == newR && x.c == newC) == null)
{
Q.Enqueue(new Cell(newR, newC, mat[newR][newC]));
}
}
newR = curr.r;
newC = curr.c + 1;
if (newC <= mat[0].Length - 1)//go right
{
if (Q.FirstOrDefault(x => x.r == newR && x.c == newC) == null)
{
Q.Enqueue(new Cell(newR, newC, mat[newR][newC]));
}
}
}
var listValues = new List<int>();
foreach (var item in tempList)
{
listValues.Add(item.v);
}
listValues.Sort();
for (int i = 0; i < tempList.Count; i++)
{
mat[tempList[i].r][tempList[i].c] = listValues[i];
}
}
return mat;
}
}
[DebuggerDisplay("r ={r}, c={c}, v={v}")]
public class Cell
{
public Cell(int r1, int c1, int v1)
{
r = r1;
c = c1;
v = v1;
}
public int r { get; set; }
public int c { get; set; }
public int v { get; set; }
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Few tips</p>\n<ol>\n<li>For code quality, consider to give variables/fields more understandeable names.</li>\n<li>For immutable <code>Cell</code> fields add <code>readonly</code>, it may affect the performance.</li>\n<li>If you know how many items will be put in the collection, construct it with capacity <code>new List<Cell>(count)</code>, <code>capacity</code> means initial size for the underlying storage not max items limit.</li>\n<li><code>FirstOrDefault == null</code> can be replaced with <code>!Any</code>.</li>\n<li>You may add items directly to <code>listValues</code> i guess, and optimize out <code>tempList</code> or vice-versa. Then Sort by field with Linq, or custom comparer, or implement <code>IComparable</code> for <code>Cell</code>.</li>\n<li><code>Cell</code> can be <code>struct</code>? If yes, you can try to take an advantage of stack allocations (for small amount of data) instead of heap using <code>Span<T></code>-related optimizations.</li>\n</ol>\n<p>For 5th tip, this code (as far as I got the idea)</p>\n<pre class=\"lang-cs prettyprint-override\"><code>var listValues = new List<int>();\nforeach (var item in tempList)\n{\n listValues.Add(item.v);\n}\nlistValues.Sort();\nfor (int i = 0; i < tempList.Count; i++)\n{\n mat[tempList[i].r][tempList[i].c] = listValues[i];\n}\n</code></pre>\n<p>Can be optimized as</p>\n<pre><code>int i = 0;\nforeach (var item in tempList.OrderBy(x => x.v))\n{\n mat[tempList[i].r][tempList[i].c] = item.v;\n i++;\n}\n</code></pre>\n<p><em>Btw, I've tested various optimizations from listed above and more but got only insignificant performance boost. The slowest point is here <code>FirstOrDefault(x => x.r == newR && x.c == newC)</code>. I have no idea how to improve it without moving the solution to different approach.</em></p>\n<p>Ok, let's do it.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public int[][] DiagonalSort(int[][] mat)\n{\n int width = mat[0].Length;\n int height = mat.Length;\n List<int> values = new List<int>(height);\n for (int j = 2 - height; j < width - 1; j++)\n {\n for (int i = 0; i < height; i++)\n {\n int offset = j + i;\n if (offset >= 0 && offset < width)\n values.Add(mat[i][offset]);\n }\n values.Sort();\n for (int i = 0, count = 0; i < height; i++)\n {\n int offset = j + i;\n if (offset >= 0 && offset < width)\n mat[i][offset] = values[count++];\n }\n values.Clear();\n }\n return mat;\n}\n</code></pre>\n<p>~15% faster than initial solution.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T21:26:11.447",
"Id": "507029",
"Score": "1",
"body": "thanks for taking the time!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T23:39:37.540",
"Id": "256598",
"ParentId": "256592",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "256598",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T21:52:57.987",
"Id": "256592",
"Score": "0",
"Tags": [
"c#",
"programming-challenge"
],
"Title": "LeetCode: Sort The Matrix Diagonally C#"
}
|
256592
|
<p>I want to create a network in which the links are formed based on a similarity metric defined as the Euclidean distance between the nodes. The distance is calculated using socio-demographic features of customers such as gender and age. The problem is the code takes 200 seconds to just create the network and as I am tuning my model and the code executes at least 100 times, the long execution time of this piece is making the whole code run slowly.</p>
<p>So, the nodes are in fact customers. I defined a class for them. They have two attributes gender (numerical; specified by number 0 or 1) and age (varies from 24 to 44) which are stored in a csv file. I have generated a sample csv file here :</p>
<pre><code>#number of customers
ncons = 5000
gender = [random.randint(0, 1) for i in range(ncons)]
age = [random.randint(22, 45) for i in range(ncons)]
customer_df = pd.DataFrame(
{'customer_gender': gender,
'customer_age': age
})
customer_df.to_csv('customer_df.csv', mode = 'w', index=False)
</code></pre>
<p>The Euclidean distance delta_ik is of the form <a href="https://i.stack.imgur.com/VXetZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VXetZ.png" alt="enter image description here" /></a><a href="https://econpapers.repec.org/article/eeetefoso/v_3a94_3ay_3a2015_3ai_3ac_3ap_3a269-285.htm" rel="nofollow noreferrer">following</a>. In the formula, <code> n</code> is the number of attributes (here n=2, age and gender). For customers <code> i</code> and <code> k</code>, <code> S_f,i - S_f,k</code> is the difference between attribute <code> f = 1,2</code> which is divided by the maximum range of attribute <code> f</code> for all the customers (<code>max d_f</code>). So the distance is the distance in the values of socio-demographic attributes, not geographical positions.</p>
<p>Then I define the similarity metric H_ik which creates a number between 0 and 1 from delta_ik as follow:<a href="https://i.stack.imgur.com/uXL1L.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uXL1L.png" alt="customer similarity" /></a>. Finally, For customers <code> i</code> and <code> k</code>, I generate a random number rho between 0 and 1. If rho is smaller than H_ik, the nodes are connected.</p>
<p>So, the code that keeps delta_ik in a matrix and then uses that to generate the network looks as below:</p>
<pre><code>import random
import pandas as pd
import time
import csv
import networkx as nx
import numpy as np
import math
#Read the csv file containing the part worth utilities of 184 consumers
def readCSVPWU():
global headers
global Attr
Attr = []
with open('customer_df.csv') as csvfile:
csvreader = csv.reader(csvfile,delimiter=',')
headers = next(csvreader) # skip the first row of the CSV file.
#CSV header cells are string and should be turned to a float number.
for i in range(len(headers)):
if headers[i].isnumeric():
headers[i] = float(headers[i])
for row in csvreader:
AttrS = row
Attr.append(AttrS)
#convert strings to float numbers
Attr = [[float(j) for j in i] for i in Attr]
#Return the CSV as a matrix with 17 columns and 184 rows
return Attr
#customer class
class Customer:
def __init__(self, PWU = None, Ut = None):
self.Ut = Ut
self.PWU = Attr[random.randint(0,len(Attr)-1)] # Pick random row from survey utility data
#Generate a network by connecting nodes based on their similarity metric
def Network_generation(cust_agent):
start_time = time.time() # track execution time
#we form links/connections between consumeragentsbasedontheirdegreeofsocio-demographic similarity.
global ncons
Gcons = nx.Graph()
#add nodes
[Gcons.add_node(i, data = cust_agent[i]) for i in range(ncons)]
#**********Compute the node to node distance
#Initialize Deltaik with zero's
Deltaik = [[0 for xi in range(ncons)] for yi in range(ncons)]
#For each attribute, find the maximum range of that attribute; for instance max age diff = max age - min age = 53-32=21
maxdiff = []
allval = []
#the last two columns of Attr keep income and age data
#Make a 2D numpy array to slice the last 2 columns (#THE ACTUAL CSV FILE HAS MORE THAN 2 COLUMNS)
np_Attr = np.array(Attr)
#Take the last two columns, income and age of the participants, respectively
socio = np_Attr[:, [len(Attr[0])-2, len(Attr[0])-1]]
#convert numpy array to a list of list
socio = socio.tolist()
#Max diff for each attribute
for f in range(len(socio[0])):
for node1 in Gcons.nodes():
#keep all values of an attribute to find the max range
allval.append((Gcons.nodes[node1]['data'].PWU[-2:][f]))
maxdiff.append((max(allval)-min(allval)))
allval = []
# THE SECOND MOST TIME CONSUMING PART ********************
for node1 in Gcons.nodes():
for node2 in Gcons.nodes():
tempdelta = 0
#for each feature (attribute)
for f in range(len(socio[0])):
Deltaik[node1][node2] = (Gcons.nodes[node1]['data'].PWU[-2:][f]-Gcons.nodes[node2]['data'].PWU[-2:][f])
#max difference
insidepar = (Deltaik[node1][node2] / maxdiff[f])**2
tempdelta += insidepar
Deltaik[node1][node2] = math.sqrt(tempdelta)
# THE END OF THE SECOND MOST TIME CONSUMING PART ********************
#Find maximum of a matrix
maxdel = max(map(max, Deltaik))
#Find the homopholic weight
import copy
Hik = copy.deepcopy(Deltaik)
for i in range(len(Deltaik)):
for j in range(len(Deltaik[0])):
Hik[i][j] =1 - (Deltaik[i][j]/maxdel)
#Define a dataframe to save Hik
dfHik = pd.DataFrame(columns = list(range(ncons) ),index = list(range(ncons) ))
temp_h = []
#For every consumer pair $i$ and $k$, a random number $\rho$ from a uniform distribution $U(0,1)$ is drawn and compared with $H_{i,k}$ . The two consumers are connected in the social network if $\rho$ is smaller than $H_{i,k}$~\cite{wolf2015changing}.
# THE MOST TIME CONSUMING PART ********************
for node1 in Gcons.nodes():
for node2 in Gcons.nodes():
#Add Hik to the dataframe
temp_h.append(Hik[node1][node2])
rho = np.random.uniform(0,1,1)
if node1 != node2:
if rho < Hik[node1][node2]:
Gcons.add_edge(node1, node2)
#Row idd for consumer idd keeps homophily with every other consumer
dfHik.loc[node1] = temp_h
temp_h = []
# nx.draw(Gcons, with_labels=True)
print("Simulation time: %.3f seconds" % (time.time() - start_time))
# THE END OF THE MOST TIME CONSUMING PART ********************
return Gcons
#%%
#number of customers
ncons = 5000
gender = [random.randint(0, 1) for i in range(ncons)]
age = [random.randint(22, 39) for i in range(ncons)]
customer_df = pd.DataFrame(
{'customer_gender': gender,
'customer_age': age
})
customer_df.to_csv('customer_df.csv', mode = 'w', index=False)
readCSVPWU()
customer_agent = dict(enumerate([Customer(PWU = [], Ut = []) for ij in range(ncons)])) # Ut=[]
G = Network_generation(customer_agent)
</code></pre>
<p>I realized that there are two nested loops that are more time consuming than others, but I am not sure how to write them more efficiently. I would tremendously appreciate if you could please give me some advice on the ways to decrease the elapsed time.</p>
<p>Thank you so much</p>
|
[] |
[
{
"body": "<p>Boy, those are huge numbers. 5000 Nodes results in an adjacency matrix with 25 million entries. But since <code>Deltaik(a,b) == Deltaik(b,a)</code>, you don't actually need to consider the whole cartesian product. In fact, your current code doubles the chance for an edge to be created because each pair of nodes <code>(a,b)</code> gets two chances: one for <code>(a,b)</code> and one for <code>(b,a)</code>. This would be the first improvement:</p>\n<p>Instead of the nested loop:</p>\n<pre><code>for node1 in Gcons.nodes:\n for node2 in Gcons.nodes:\n ...\n</code></pre>\n<p>Use <a href=\"https://docs.python.org/3/library/itertools.html#itertools.combinations\" rel=\"nofollow noreferrer\">itertools.combinations</a>:</p>\n<pre><code>for node1, node2 in itertools.combinations(Gcons.nodes, 2):\n ...\n</code></pre>\n<h3>Memory consupmtion</h3>\n<p>There will still be 12497500 combinations, so let's talk about memory consumption. You are creating huge temporary data structures (<code>Deltaik</code>, <code>Hik</code>) that are only iterated once and then discarded. I'd suggest the following datastructure:</p>\n<pre><code>delta_iks = []\n</code></pre>\n<p>That's really all you need. The reason is that <code>itertools.combinations</code> is insanely fast, and it will generate the combinations in the exact same order every time (as long as you don't modify the graph, of course). So whenever you need to iterate all edges, i.e. <code>(node1, node2)</code>, just generate them again. You also don't have to create a separate list of <code>Hik</code> because you can calculate it on the fly when you actually add the edges to the graph.</p>\n<h3>Runtime</h3>\n<p>12497500 combinations also means that the calculation of the distances will be executed that many times, so you should make sure that it is efficient.</p>\n<p>First of all, there are a lot of unnecessary dictionary accesses only to retrieve the customer instance of each node. You can access them more directly. Also, the <code>[-2:]</code> is unnecessary because PWU already has only 2 elements, but it generates a new sublist each time it is called.</p>\n<pre><code>for (node1, customer1), (node2, customer2) in itertools.combinations(Gcons.nodes.data('data'), 2):\n...\n customer1.PWU[f]...\n</code></pre>\n<pre><code>for f in range(len(socio[0])):\n</code></pre>\n<p>This is a red flag in python. What you really want to do in that loop is simultaneously iterate the features of customer1 and customer2 and the maxdiff of that feature. Since all of them are stored in the same order, this can be achieved using zip:</p>\n<pre><code>for c1_attr, c2_attr, maxdiff_attr in zip(customer1.PWU, customer2.PWU, maxdiff):\n tempdelta += ((c1_attr - c2_attr) / maxdiff_attr)**2\n</code></pre>\n<p>The complete first loop now looks like this (and completes in about 7 seconds on my computer):</p>\n<pre><code>delta_iks = []\nfor (_, customer1), (_, customer2) in itertools.combinations(Gcons.nodes.data('data'), 2):\n tempdelta = 0\n #for each feature (attribute)\n for c1_attr, c2_attr, maxdiff_attr in zip(customer1.PWU, customer2.PWU, maxdiff):\n tempdelta += ((c1_attr - c2_attr) / maxdiff_attr)**2\n delta_iks.append(math.sqrt(tempdelta))\nmax_delta_ik = max(delta_iks)\n</code></pre>\n<p>As you can see, we don't even use the nodes' names anymore. If we need to iterate all edges <code>(node1, node2)</code> with their corresponding <code>delta_ik</code>, we can simply do:</p>\n<pre><code>for (node1, node2), delta_ik in zip(itertools.combinations(Gcons.nodes, 2), delta_iks):\n ...\n</code></pre>\n<p>Now prepare the <code>Hik</code>. Note that this is a generator that will only generate each value when you iterate it. It's not a list because that would again use a lot of memory.</p>\n<pre><code>h_iks = (1-(delta_ik / max_delta_ik) for delta_ik in delta_iks)\n</code></pre>\n<p>One thing about <code>numpy.random.uniform</code> that I also didn't know before: generating one value at a time 12 million times is significantly slower (20 seconds on my machine) than telling <code>numpy</code> how many values you are going to need beforehand. So let's prepare the <code>rho</code>s now:</p>\n<pre><code>rhos = np.random.uniform(0,1,len(delta_iks))\n</code></pre>\n<p><code>networx.Graph</code> has a very convenient method for adding multiple edges: <code>add_edges_from</code>, which takes any iterable, e.g. a generator. So let's create yet another generator that yields all edges if a random <code>rho</code> is less than its <code>h_ik</code>:</p>\n<pre><code>edges = (edge for edge, h_ik, rho in zip(itertools.combinations(Gcons.nodes, 2), h_iks, rhos) if rho < h_ik)\n</code></pre>\n<p>Notice how <em>nothing</em> has been calculated yet, and the only significant amount of memory is used by the <code>delta_iks</code> list. Now add the edges to the graph (this takes about 8-9 seconds on my machine):</p>\n<pre><code>Gcons.add_edges_from(edges)\n</code></pre>\n<p>The complete <code>Network_generation</code> function:</p>\n<pre><code>#Generate a network by connecting nodes based on their similarity metric\ndef Network_generation(cust_agent):\n start_time = time.time() # track execution time\n\n #we form links/connections between consumeragentsbasedontheirdegreeofsocio-demographic similarity.\n global ncons\n Gcons = nx.Graph()\n #add nodes\n [Gcons.add_node(i, data = cust_agent[i]) for i in range(ncons)]\n #**********Compute the node to node distance\n #For each attribute, find the maximum range of that attribute; for instance max age diff = max age - min age = 53-32=21\n maxdiff = []\n allval = []\n #the last two columns of Attr keep income and age data\n #Make a 2D numpy array to slice the last 2 columns (#THE ACTUAL CSV FILE HAS MORE THAN 2 COLUMNS)\n np_Attr = np.array(Attr)\n #Take the last two columns, income and age of the participants, respectively\n socio = np_Attr[:, [len(Attr[0])-2, len(Attr[0])-1]]\n #convert numpy array to a list of list\n socio = socio.tolist()\n #Max diff for each attribute\n for f in range(len(socio[0])):\n for node1 in Gcons.nodes():\n #keep all values of an attribute to find the max range\n allval.append((Gcons.nodes[node1]['data'].PWU[-2:][f]))\n maxdiff.append((max(allval)-min(allval)))\n allval = []\n\n # THE SECOND MOST TIME CONSUMING PART ********************\n delta_iks = []\n for (_, customer1), (_, customer2) in itertools.combinations(Gcons.nodes.data('data'), 2):\n tempdelta = 0\n #for each feature (attribute)\n for c1_attr, c2_attr, maxdiff_attr in zip(customer1.PWU, customer2.PWU, maxdiff):\n tempdelta += ((c1_attr - c2_attr) / maxdiff_attr)**2\n delta_iks.append(math.sqrt(tempdelta))\n max_delta_ik = max(delta_iks)\n # THE END OF THE SECOND MOST TIME CONSUMING PART ********************\n\n h_iks = (1-(delta_ik / max_delta_ik) for delta_ik in delta_iks)\n rhos = np.random.uniform(0,1,len(delta_iks))\n edges = (edge for edge, h_ik, rho in zip(itertools.combinations(Gcons.nodes, 2), h_iks, rhos) if rho < h_ik)\n\n # THE MOST TIME CONSUMING PART ********************\n Gcons.add_edges_from(edges)\n # THE END OF THE MOST TIME CONSUMING PART ********************\n print("Simulation time: %.3f seconds" % (time.time() - start_time))\n return Gcons\n</code></pre>\n<p>This takes around 16 seconds on my computer. For reference, your original code took roughly 105 seconds on my computer.</p>\n<p>I haven't touched the part before "THE SECOND MOST TIME CONSUMING PART" because it doesn't significantly contribute to memory consumption and run time. It could still be improved, though.</p>\n<hr />\n<h2>Further improvements</h2>\n<h3>Memory</h3>\n<p>The <code>delta_iks</code> list takes up around 500MB of heap space.\nWhen an edge has been added to the graph, we don't need the corresponding <code>delta_ik</code> anymore, so we could theoratically remove it from the list. Unfortunately, python <code>list</code>s don't provide an efficient way to do so. But <code>collections.deque</code>s do.</p>\n<p>Make <code>delta_iks</code> a <code>deque</code>:</p>\n<pre><code># delta_iks = []\ndelta_iks = collections.deque()\n</code></pre>\n<p>Instead of defining <code>h_iks</code> with a generator expression, we'll make it a generator function that yields the same values, but additionally removes them from <code>delta_iks</code>. Note that now it has to be invoked with <code>()</code> in the <code>edges</code> generator:</p>\n<pre><code># h_iks = (1-(delta_ik / max_delta_ik) for delta_ik in delta_iks)\ndef h_iks():\n while delta_iks:\n yield(1-(delta_iks.popleft() / max_delta_ik))\n\nrhos = np.random.uniform(0,1,len(delta_iks))\n# edges = (edge for edge, h_ik, rho in zip(itertools.combinations(Gcons.nodes, 2), h_iks, rhos) if rho < h_ik)\nedges = (edge for edge, h_ik, rho in zip(itertools.combinations(Gcons.nodes, 2), h_iks(), rhos) if rho < h_ik)\n</code></pre>\n<p>The reason why you only save 400MB is that the empty <code>deque</code> is still about 100MB on the heap. Keep in mind, though, that the graph is significantly larger (somewhere in the region of 1.8GB), so it won't make that much of a difference.</p>\n<h3>Runtime</h3>\n<p>If I understood your code correctly, the <code>Hik</code> is the probability that an edge is created. If you only need it for that purpose, you could shave off some numerical calculations. Instead of</p>\n<pre><code>if rho < (1-(delta_iks / max_delta_ik))\n</code></pre>\n<p>You could test</p>\n<pre><code>if rho > (delta_iks / max_delta_ik)\n</code></pre>\n<p>And furthermore, instead of normalizing <code>delta_ik</code> and picking a <code>0 <= rho < 1</code>, you cold use the "raw" <code>delta_ik</code> and pick a <code>0 <= rho < max_delta_ik</code>:</p>\n<pre><code>\nrhos = np.random.uniform(0,max_delta_ik,len(delta_iks))\nedges = (edge for edge, delta_ik, rho in zip(itertools.combinations(Gcons.nodes, 2), delta_iks, rhos) if rho > delta_ik)\n</code></pre>\n<p>That, however, won't make a significant difference (3 seconds on my machine).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T13:39:52.337",
"Id": "507923",
"Score": "0",
"body": "Thanks a lot for such a comprehensive and wonderful answer. I am learning a lot from how you have been modifying the code, and I am really impressed by how much the time decreased. A question. Is there any way to save the values of `edge, h_ik, rho` in `edges = (edge for edge, h_ik, rho in zip(itertools.combinations(Gcons.nodes, 2), h_iks(), rhos) if rho < h_ik)` each time an edge is added to edges. It helps me to check the generated graph for a small case by comparing the value of the random rho for every edge with h_ik. Thank you so much."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T11:13:53.133",
"Id": "256713",
"ParentId": "256594",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-01T22:04:42.527",
"Id": "256594",
"Score": "2",
"Tags": [
"python",
"performance",
"object-oriented",
"time-limit-exceeded",
"numpy"
],
"Title": "Performance issue in python- network creation based on the Euclidean distance with nested for loops is too slow"
}
|
256594
|
<p>I have made the review changes based on feedback I have got from <a href="https://codereview.stackexchange.com/questions/256556/embedded-iot-local-data-storage-updated">here</a> which was based on the feedback I got from <a href="https://codereview.stackexchange.com/questions/256360/embedded-iot-local-data-storage-when-no-network-coverage">this</a> one. I am almost done and now looking for a final review with respect to any minor or obvious improvements/fixes that can be done quickly. In regard to supporting multiple instances, I have included that in Jira for the next release as I have to release this module on Friday for integration and testing. Before this, I want to test it properly for any corner cases.</p>
<p>Below is the header file.</p>
<pre><code>/*
* Bucket.h
*
* Created: 17/12/2020 12:57:45 PM
* Author: Vinay Divakar
*/
#ifndef BUCKET_H_
#define BUCKET_H_
#include <inttypes.h>
#include <stdio.h>
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#define BUCKET_MAX_FEEDS 32
#define BUCKET_LOG2_SIZE 5
#define BUCKET_SIZE (1u << BUCKET_LOG2_SIZE)
#define BUCKET_MASK (BUCKET_SIZE - 1)
//#define BUCKET_TIME() GetUnixTime();
typedef enum {
UINT16,
STRING
} cvalue_t;
// Used to register feeds to the bucket and for passing sensor data to the bucket
typedef struct {
const char* key; // The keys are initialized on boot
cvalue_t type; // Data type
void* value; // Value
uint32_t unixTime; // Timestamp
} cbucket_t;
bool BucketRegisterFeed(cbucket_t *feed);
int8_t BucketPut(const cbucket_t *data);
int8_t BucketGet( char *keyOut, char *dataOut, uint32_t *timestampOut);
//Debug functions
void DebugPrintRegistrationData(void);
void DebugPrintBucket(void);
void DebugPrintBucketTailToHead(void);
#endif /* BUCKET_H_ */
</code></pre>
<p>Below is the source code.</p>
<pre><code>/*
* Bucket.c
*
* Created: 17/12/2020 12:57:31 PM
* Author: Vinay Divakar
* Description: This module is used to accumulate data when
the network is down or unable to transmit data due to poor
signal quality. It currently supports uint16_t and string
data types. The bucket is designed to maximize the amount
of data that can be stored in a given amount of memory for
typical use. The feeds must be registered before it can be
written to or read from the bucket.
The BucketPut API writes the feed to the bucket.
E.g. 1: If the BucketPut sees that consecutive feeds written
have the same timestamp, then it writes the data as shown below.
This is done to save memory.
[Slot] [Data] [Slot] [Data] [Slot] [Data]...[Timestamp]
E.g. 2: If the BucketPut sees that consecutive feeds written have
different timestamps, then it writes the data as shown below.
[Slot] [Data] [Timestamp] [Slot] [Data] [Timestamp]-
[Slot] [Data] [Timestamp]
E.g. 3: If the BucketPut sees a mixture of above, then it writes
the data as shown below.
[Slot] [Data] [Slot] [Data] [Slot] [Data] [Timestamp] [Slot] [Data]-
[Timestamp] [Slot] [Data] [Slot] [Data] [Timestamp]
The BucketGet API reads the feed in the following format.
[Key] [Value] [Timestamp]
* Notes:
1. Module only supports UINT16_T and STRING data types.
*/
/*
*====================
* Includes
*====================
*/
#include "Bucket.h"
/*
*====================
* static/global vars
*====================
*/
const char *const cvaluetypes[] = {"UINT16", "STRING"};
// Stores the registered feed
static cbucket_t *registeredFeed[BUCKET_MAX_FEEDS];
static const uint8_t unixTimeSlot = 0xFF; //virtual time slot
// Bucket memory for edge storage and pointers to keep track or reads and writes
static uint8_t cBucketBuf[BUCKET_SIZE];
static uint8_t *cBucketBufHead = cBucketBuf;
static uint8_t *cBucketBufTail = cBucketBuf;
/*
*====================
* Static Fxns
*====================
*/
/****************************************************************
* Function Name : BucketGetRegisteredFeedSlot
* Description : Gets slot index of the registered feed
* Returns : slot index on OK, 0xFF on error
* Params @data: points to the feed struct
****************************************************************/
static uint8_t BucketGetRegisteredFeedSlot(const cbucket_t *data){
uint8_t slotIdx;
/* Check if the feed had been previously registered */
for(slotIdx = 0 ; slotIdx < BUCKET_MAX_FEEDS ; slotIdx++) {
//found it?
if(data == registeredFeed[slotIdx]){
//Get the slot index
return slotIdx;
}
}
return 0xFF;
}
/****************************************************************
* Function Name : BucketCheckDataAvailable
* Description : Checks for data in the bucket
* Returns : false on empty else true.
* Params None.
****************************************************************/
static bool BucketCheckDataAvailable(void){
return cBucketBufTail != cBucketBufHead;
}
/****************************************************************
* Function Name : BucketGetDataSize
* Description : Gets the size of the item
* Returns : false on error, !0 on OK
* Params @data :points to feed struct
****************************************************************/
static uint8_t BucketGetDataSize(const cbucket_t *data){
uint8_t dataSizeOut = false;
switch(data->type){
case UINT16:{
//Total data size = 2 bytes i.e. 16 bit unsigned
dataSizeOut = sizeof(uint16_t);
}
break;
case STRING:{
//Total data size = length of the string until null terminated. Now get the length of the string by looking upto '\0'
const uint8_t *bytePtr = data->value;
dataSizeOut = (uint8_t)strlen(bytePtr);
if(dataSizeOut >= UINT8_MAX){
printf("[BucketGetDataSize], invalid string length\r\n");
dataSizeOut = false;
}else{
//Include the '\0' to be written. This will be used to indicate the end of string while reading
dataSizeOut++;
}
}
break;
default:
printf("[BucketGetDataSize], invalid data type\r\n");
break;
}
return dataSizeOut;
}
/****************************************************************
* Function Name : RegisteredFeedFreeSlot
* Description : Gets first free slot(index) found, returns
* Returns : slot on success else 0xFF
* Params None.
****************************************************************/
static uint8_t RegisteredFeedFreeSlot(void) {
uint8_t slot;
//Check for slots sequentially, return index of first empty one (null pointer)
for(slot = 0; slot < BUCKET_MAX_FEEDS; slot++) {
if(registeredFeed[slot] == 0)
return slot;
}
//All slots full
return 0xFF;
}
/****************************************************************
* Function Name : BucketCircularBufferWriteHead
* Description : Writes to bucket from head
* Returns None.
* Params @offset: offset to start writing from
@size: data size
@data: ptr to data to be written
****************************************************************/
static void BucketCircularBufferWriteHead(int offset, size_t size, const void *data) {
const uint8_t *ptr = data; // convenience cast
unsigned head = cBucketBufHead - cBucketBuf;
for (head += offset; size; --size) {
cBucketBuf[head & BUCKET_MASK] = *ptr++;
++head;
}
cBucketBufHead = &cBucketBuf[head & BUCKET_MASK];
}
/****************************************************************
* Function Name : BucketCircularBufferReadHead
* Description : Reads from bucket from head
* Returns None.
* Params @offset: offset to start reading from
@size: data size
@data: ptr to buffer to populate
****************************************************************/
static void BucketCircularBufferReadHead(int offset, size_t size, void *data) {
uint8_t *ptr = data; // convenience cast
unsigned head = cBucketBufHead - cBucketBuf;
for (head += offset; size; --size) {
*ptr++ = cBucketBuf[head & BUCKET_MASK];
++head;
}
cBucketBufHead = &cBucketBuf[head & BUCKET_MASK];
}
/****************************************************************
* Function Name : BucketCircularBufferWriteTail
* Description : Writes to bucket from tail
* Returns None.
* Params @offset: offset to start writing from
@size: data size
@data: ptr to data to be written
****************************************************************/
static void BucketCircularBufferWriteTail(int offset, size_t size, const void *data) {
const uint8_t *ptr = data; // convenience cast
unsigned tail = cBucketBufTail - cBucketBuf;
for (tail += offset; size; --size) {
cBucketBuf[tail & BUCKET_MASK] = *ptr++;
++tail;
}
cBucketBufTail = &cBucketBuf[tail & BUCKET_MASK];
}
/****************************************************************
* Function Name : BucketCircularBufferReadTail
* Description : Reads from bucket from tail.
* Returns None.
* Params @offset: offset to start reading from
@size: data size
@data: ptr to buffer to pupulate
****************************************************************/
static void BucketCircularBufferReadTail(int offset, size_t size, void *data) {
uint8_t *ptr = data; // convenience cast
unsigned tail = cBucketBufTail - cBucketBuf;
for (tail += offset; size; --size) {
*ptr++ = cBucketBuf[tail & BUCKET_MASK];
++tail;
}
cBucketBufTail = &cBucketBuf[tail & BUCKET_MASK];
}
/****************************************************************
* Function Name : BucketGetTimeStamp
* Description : Gets the timestamp for the specific key
* Returns : true on OK, false on empty
* Params @timestamp: Gets the timestamp while write
****************************************************************/
static bool BucketPutGetTimeStamp(uint32_t *timestamp) {
if (!BucketCheckDataAvailable()) {
return false;
}
uint8_t ts;
uint32_t timestamp_copy;
const int sizes = sizeof(ts) + sizeof(timestamp_copy);
BucketCircularBufferReadHead(-sizes, sizeof(ts), &ts);
BucketCircularBufferReadHead(0, sizeof(timestamp_copy), &timestamp_copy);
if (ts == unixTimeSlot) {
*timestamp = timestamp_copy;
return true;
}
return false;
}
/****************************************************************
* Function Name : BucketGetTimestampForFeed
* Description : Gets the timestamp for the feed
* Returns : false on error, true on OK.
* Params @timestamp: feeds timestamp while read
****************************************************************/
static bool BucketGetTimestampForFeed(uint32_t *timestamp){
bool status = false;
uint8_t ts = 0;
*timestamp = 0;
uint32_t timestamp_copy = 0, dummyTimestamp = 0;
uint16_t shiftBackOffset = 0;
//Read the current element
BucketCircularBufferReadTail(0, sizeof(ts), &ts);
//Check if tail is pointing to the virtual time slot
if(ts == unixTimeSlot){//If so, read the timestamp
printf("[BucketGetTimestampForFeed], tail pointing to time slot, read it.\r\n");
uint8_t dummySlot = 0;
int sizes = 0;
sizes = sizeof(dummySlot);
BucketCircularBufferWriteTail(-sizes, sizeof(dummySlot), &dummySlot);//clear ts
BucketCircularBufferReadTail(0, sizeof(timestamp_copy), &timestamp_copy);//read timestamp
sizes = sizeof(timestamp_copy);
BucketCircularBufferWriteTail(-sizes, sizeof(timestamp_copy), &dummyTimestamp);//clear timestamp
*timestamp = timestamp_copy;
status = true;
}else{//timeslot not found?
//means the next byte is the slot index for the next feed which is not what we are looking for.
//Lets look beyond, it must be there! - if not, then there's something seriously wrong with the code
while(ts != unixTimeSlot){
shiftBackOffset++;
BucketCircularBufferReadTail(0, sizeof(ts), &ts);
//break out if buggy
if(shiftBackOffset >= UINT16_MAX){
printf("#####[BucketGetTimestampForFeed], Error, could not find the timeslot, seems like a bug in the code?\r\n");
return status;//error
}
}//while
const int sizes = sizeof(ts) + sizeof(timestamp_copy) + (shiftBackOffset);
BucketCircularBufferReadTail(0, sizeof(timestamp_copy), &timestamp_copy);
BucketCircularBufferReadTail(-sizes, 0, 0);
*timestamp = timestamp_copy;
status = true;
}
return status;
}
/****************************************************************
* Function Name : BucketGetReadData
* Description : Reads the key and value for that feed/slot.
* Returns : false error, true on success.
* Params @key: key to be populated(static).
@value: value read from the bucket.
****************************************************************/
static bool BucketGetReadData(char *key, char *value){
uint8_t slotIdx;
uint8_t dummyIdx = 0;
bool status = true;
BucketCircularBufferReadTail(0, sizeof(slotIdx), &slotIdx);
const int sizes = sizeof(slotIdx);
BucketCircularBufferWriteTail(-sizes, sizeof(slotIdx), &dummyIdx);
if(slotIdx > BUCKET_MAX_FEEDS){
printf("[BucketGetReadData], Error, Slot[%u] index is out of bounds\r\n", slotIdx);
return false;
}else{
printf("[BucketGetReadData], Slot[%d] = %p\r\n", slotIdx, (void *)registeredFeed[slotIdx]->key);
}
//Copy the key for the corresponding slot
strncpy(key, registeredFeed[slotIdx]->key, strlen(registeredFeed[slotIdx]->key));
//Read data based on type
switch(registeredFeed[slotIdx]->type){
case UINT16:{
uint16_t dataU16 = 0;
BucketCircularBufferReadTail(0, sizeof(dataU16), &dataU16);
printf("[BucketGetReadData] dataU16 = %hu [0x%X]\r\n", dataU16, dataU16);
sprintf(value, "%hu", dataU16); //convert the u16 into string
dataU16 = 0;
const int sizes = sizeof(dataU16);
BucketCircularBufferWriteTail(-sizes, sizeof(dataU16), &dataU16);
}
break;
case STRING:{
printf("[BucketGetReadData] dataStr = ");
uint8_t idx = 0, eos = 99, tmp = 0;
//Look for end of string
while(eos != '\0'){
BucketCircularBufferReadTail(0, sizeof(eos), &eos);
const int sizes = sizeof(tmp);
BucketCircularBufferWriteTail(-sizes, sizeof(tmp), &tmp);
printf("0x%x ", eos);
value[idx++] = eos;
}
printf("\r\n");
}
break;
default:
printf("[BucketGetReadData], Error, invalid read type Slot[%d]\r\n", slotIdx);
status = false;
break;
}
return status;
}
/*
*====================
* Fxns
*====================
*/
/****************************************************************
* Function Name : BucketRegisterFeed
* Description : Registers the feed
* Returns : false on error, true on OK
* Params @feed :Feed to register
****************************************************************/
bool BucketRegisterFeed(cbucket_t *feed) {
uint8_t slot = RegisteredFeedFreeSlot();
if (slot >= BUCKET_MAX_FEEDS){
return false;
} else{
registeredFeed[slot] = feed;
}
return true;
}
/****************************************************************
* Function Name : BucketPut
* Description : writes to the bucket
* Returns : true on success else negative..
* Params @data :points to struct to be written
****************************************************************/
int8_t BucketPut(const cbucket_t *data) {
uint8_t slot = 0;
uint8_t dataSize = 0;
uint8_t totalSpaceRequired = 0;
uint16_t remaining = 0;
uint32_t lastStoredTime = 0;
//Find the slot for this feed
slot = BucketGetRegisteredFeedSlot(data);
if(slot > BUCKET_MAX_FEEDS){
printf("[BucketPut], Error, feed not registered\r\n");
return -1;
}
//Get th size of the item and handle storing as appropriate
dataSize = BucketGetDataSize(data);
if(dataSize == false){
printf("[BucketPut], Error, invalid data type\r\n");
return -2;
}
//Get the amount space left in the bucket
remaining = (cBucketBufTail + BUCKET_SIZE - cBucketBufHead-1) % BUCKET_SIZE;
printf("[BucketPut], bucket size = %d remaining space = %hu dataSize = %u\r\n", (int)BUCKET_SIZE, remaining, dataSize);
//Get the timestamp from the unix time slot
bool found = BucketPutGetTimeStamp(&lastStoredTime);
if(found){//last stored timestamp found
printf("[BucketPut] Last stored timestamp[%" PRIu32"] found\r\n", lastStoredTime);
}
//Check timestamps
if(lastStoredTime == data->unixTime){
//If timestamp matches the current feed, write only data and slot idx
printf("[BucketPut], timestamps[%" PRIu32"] matched!\r\n",data->unixTime);
totalSpaceRequired = (uint8_t)(dataSize + sizeof(slot));
}else{
//If timestamps different or unavailable, account for a write including the new timestamp
printf("[BucketPut] Last stored timestamp[%" PRIu32"] is different from Current timestamp[%" PRIu32"]\r\n", lastStoredTime, data->unixTime);
totalSpaceRequired = (uint8_t)(dataSize + sizeof(slot) + sizeof(data->unixTime) + sizeof(unixTimeSlot));
}
//Proceed further only if enough space is available in the bucket
if(totalSpaceRequired > remaining) {
printf("[BucketPut], ALERT, no space available, space = %hu, required space = %hu\r\n", remaining, totalSpaceRequired);
return -3;
}else{
printf("[BucketPut], available space = %hu required space = %hu\r\n", remaining, totalSpaceRequired);
}
//If timestamp had matched, overwrite it with current feed data and append with timestamp.
if(lastStoredTime == data->unixTime){
int shiftOffset = sizeof(slot) + sizeof(data->unixTime);
//move the head backwards by size of time slot index + size of timestamp.
if(cBucketBuf + shiftOffset > cBucketBufHead){
//Wrap around to start of the bucket
shiftOffset -= BUCKET_SIZE;
}
cBucketBufHead -= shiftOffset;
}//timestamp matched!
//If we have reached here, means all checks have passed and its safe to write the item to the bucket
BucketCircularBufferWriteHead(0, sizeof(slot), &slot);
BucketCircularBufferWriteHead(0, dataSize, data->value);
BucketCircularBufferWriteHead(0, sizeof(unixTimeSlot), &unixTimeSlot);
BucketCircularBufferWriteHead(0, sizeof(data->unixTime), &(data->unixTime));
return true;
}
/****************************************************************
* Function Name : BucketGet
* Description :Gets the data
* Returns : true on success else negative..
* Params @keyOut :contains the key
@dataOut:contains the value
@timestampOut: contains the timestamp
****************************************************************/
int8_t BucketGet( char *keyOut, char *dataOut, uint32_t *timestampOut) {
//Check if theres anything in the bucket
printf("<==============================================================================>\r\n");
if(!BucketCheckDataAvailable()){
printf("[BucketGet], ALERT, Bucket is empty, no more data left to read.\r\n");
return -1;
}
//Read the key-value for the corresponding feed/slot
if(!BucketGetReadData(keyOut, dataOut)){
printf("[BucketGet], Error, bucket read failed\r\n");
return -2;
}
//Read the timestamp corresponding to this feed
if(!BucketGetTimestampForFeed(timestampOut)){
printf("[BucketGet], Error, feed timestamp read failed\r\n");
return -3;
}
//All good, dump the key-value and associated timestamp
printf("[Bucket Get] timestamp = %" PRIu32"\r\n",*timestampOut);
printf("[Bucket Get] key = %s\r\n", keyOut);
printf("[Bucket Get] value = %s\r\n", dataOut);
printf("<==============================================================================>\r\n");
return true;
}
/*
*====================
* Debug Utils
*====================
*/
/****************************************************************
* Function Name : PrintFeedValue
* Description :Prints feed data value via void pointer
and corrects for type FLOAT AND DOUBLE DONT PRINT ON WASPMOTE
BUT NO REASON TO BELIEVE THEY ARE WRONG
* Returns : None.
* Params @feed: Points to the feed to be printed
****************************************************************/
void PrintFeedValue(cbucket_t *feed) {
switch(feed->type){
case UINT16: printf("%d",*(uint16_t*)feed->value); break;
case STRING: printf("%s",(char*)feed->value); break;
default: printf("%s","UNSUPPORTED TYPE"); break;
}
}
/****************************************************************
* Function Name : _DebugPrintRegistrationData
* Description :Prints all registered feeds and their details
* Returns : None.
* Params None.
****************************************************************/
void DebugPrintRegistrationData(void) {
uint8_t slot;
printf("********************** Current Bucket Registration Data **************************\r\n");
printf("slot\taddress\tkey\ttype\tvalue\tunixtime\r\n");
for(slot = 0; slot<BUCKET_MAX_FEEDS; slot++) {
printf("%d\t", slot); // Print index
if (registeredFeed[slot] != NULL) {
printf("%p\t",(void *)registeredFeed[slot]->key); // Print structure address
printf("%s\t",registeredFeed[slot]->key); // Print key
printf("%s\t",cvaluetypes[registeredFeed[slot]->type]); // Print type
PrintFeedValue(registeredFeed[slot]); // Print value
printf("\t%" PRIu32"\r\n",registeredFeed[slot]->unixTime); // Print time
} else printf("--\t--\tEMPTY\t--\t--\r\n");
}
}
/****************************************************************
* Function Name : _DebugPrintBucket
* Description :Prints all bucket memory, even if empty
* Returns : None.
* Params None.
****************************************************************/
void DebugPrintBucket(void) {
uint16_t readIndex = 0;
printf("\r\n********************* BUCKET START ********************\r\n");
while(readIndex < BUCKET_SIZE) {
printf("0x%04X ", readIndex);
for (uint8_t column = 0; column < 16; column++) {
if(readIndex < BUCKET_SIZE)
printf("%02X ",cBucketBuf[readIndex]);
readIndex++;
//delayMicroseconds(78); // Wait for a byte to send at 115200 baud
//delay(0.1);
}
printf("\r\n");
}
printf("********************** BUCKET END *********************\r\n");
}
/****************************************************************
* Function Name : _DebugPrintBucket
* Description : Prints bucket memory that has data
* Returns : None.
* Params None.
****************************************************************/
void DebugPrintBucketTailToHead(void) {
uint8_t *cBucketBufHeadTemp = cBucketBufHead;
uint8_t *cBucketBufTailTemp = cBucketBufTail;
uint16_t index;
printf("\n*************** BUCKET START FROM TAIL ****************\n");
// Label and indent first line
if ((cBucketBufTailTemp - cBucketBuf) % 16 != 0) {
printf(" ");
for (index = (uint16_t)(cBucketBufTailTemp - cBucketBuf) % 16; index > 0; index--) {
printf(" ");
}
}
// Print rest of data
while(cBucketBufTailTemp != cBucketBufHeadTemp) { // Increment read address
if(cBucketBufTailTemp >= &cBucketBuf[BUCKET_SIZE])
cBucketBufTailTemp = cBucketBuf; // Handle wraparound
index = (uint16_t)(cBucketBufTailTemp - cBucketBuf); // Get current index in buffer
if (index % 16 == 0) printf("\n0x%04X ", cBucketBufTailTemp - cBucketBuf); // New line every 0x00n0
printf("%02X ", *cBucketBufTailTemp);
cBucketBufTailTemp++; // Print data in buffer
}
printf("\n***************** BUCKET END AT HEAD ******************\n");
}
</code></pre>
<p>The test code is the same as shared in the <a href="https://codereview.stackexchange.com/questions/256556/embedded-iot-local-data-storage-updated">previous</a> thread.</p>
|
[] |
[
{
"body": "<p>Since the previous review, the standard library includes in the header have swung from one extreme to the other, so I'll focus in on our objectives here.</p>\n<p>As a user of this library, I want to be able to <code>#include "Bucket.h"</code> without any preconditions, but with also without any unnecessary overhead. That means computational overhead (mainly from the number of transitive includes) and cognitive overhead (how much I need to understand).</p>\n<p>This means that <code>Bucket.h</code> needs to include definitions of <code>bool</code>, <code>int8_t</code> and <code>uint32_t</code>, so that the header can be parsed:</p>\n<pre><code>#include <stdbool.h>\n#include <stdint.h>\n</code></pre>\n<p>However, the other includes don't provide any value for the user of <code>Bucket.h</code>: they are needed for the implementation but not the interface. So these shouldn't be included from the header.</p>\n<p>There is <a href=\"https://include-what-you-use.org\" rel=\"nofollow noreferrer\">at least one tool</a> to help keep your headers in line with this principle of "include what you use".</p>\n<p>Along the lines of including only what the user needs in the public header, it seems from the test code that users don't need to know the details of the defined constants, so the header could be as simple as this:</p>\n<pre><code>#ifndef BUCKET_H_\n#define BUCKET_H_\n\n#include <stdbool.h>\n#include <stdint.h>\n\n// Used to register feeds to the bucket and for passing sensor data to\n// the bucket\ntypedef struct {\n const char* key;\n enum {\n UINT16,\n STRING\n } type;\n void* value;\n uint32_t unixTime;\n} cbucket_t;\n\n\nbool BucketRegisterFeed(const cbucket_t *feed);\nint8_t BucketPut(const cbucket_t *data);\nint8_t BucketGet(char *keyOut, char *dataOut, uint32_t *timestampOut);\n\n#ifdef BUCKET_DEBUG\nvoid DebugPrintRegistrationData(void);\nvoid DebugPrintBucket(void);\nvoid DebugPrintBucketTailToHead(void);\n#endif\n\n#endif /* BUCKET_H_ */\n</code></pre>\n<p>If the user could be isolated from the implementation details of <code>cbucket_t</code>, we could reduce the header even further, by forward-declaring <code>struct cbucket_t</code>. That would enable users to very quickly understand what facilities are available to them.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T08:49:56.370",
"Id": "506648",
"Score": "0",
"body": "As I'm only addressing one small point in this review, don't accept this - wait to see if you get some other reviews covering more of the code!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T07:27:16.507",
"Id": "506744",
"Score": "0",
"body": "\"However, the other includes don't provide any value for the user of Bucket.h: they are needed for the implementation but not the interface. So these shouldn't be included from the header.\" This is opinion-based. Many believe that all headers that the module uses should be in the h file to document all module dependencies."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T07:58:34.617",
"Id": "506746",
"Score": "0",
"body": "That's a new one to me @Lundin - I've not seen that proposed before. But something to consider and digest."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T08:01:25.200",
"Id": "506747",
"Score": "0",
"body": "I've had that debate on this site a couple of times. Generally, the user shouldn't have to poke through the C file to find out information that they need. So when someone is using your lib and get strange linker errors about missing files pointing inside your lib, they should only need to go to the top of the header to see which files that are needed. \"Aha, it does `#include \"foo.h\", then I must surely add foo.c to the linker\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T08:06:40.687",
"Id": "506748",
"Score": "1",
"body": "Still seems strange to me - I think it would be more useful to have a useful comment than having to infer the linker command from the headers included. But if that's what some prefer, it's good to be aware of. On common platforms, the only Standard header that implies linker flags is `<cmath>` implying `-lm`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T08:08:42.833",
"Id": "506749",
"Score": "0",
"body": "That's project-wide documentation though, there should be both. Nothing is more annoying than all that start time you spent with a new code base, trying to get it up and running, or when porting it to your favourite tool chain."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T01:19:21.333",
"Id": "506850",
"Score": "0",
"body": "If you're porting or linking, you would be looking at both the .h and the .c code, so putting everything in the .h file is a false economy that obfuscates the purpose of having a separate interface in the first place."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T08:49:07.837",
"Id": "256609",
"ParentId": "256602",
"Score": "2"
}
},
{
"body": "<p>Overall the code is well-written and easy to read. I found no major things to remark on, just details:</p>\n<ul>\n<li><p><code>cvaluetypes</code> is only used by the .c file and should be declared <code>static</code>, to achieve private encapsulation. It's good that you use <code>* const</code> for read-only pointer tables, since this typically makes them flash allocated on embedded systems, as opposed to RAM where they shouldn't be.</p>\n</li>\n<li><p>Minor remark: to avoid multiple returns from a function, it is best to make a habit of doing:</p>\n<pre><code> static uint8_t BucketGetRegisteredFeedSlot(const cbucket_t *data){\n uint8_t slotIdx = 0xFF;\n ...\n if(data == registeredFeed[slotIdx]){\n break;\n }\n return slotIdx;\n }\n</code></pre>\n</li>\n<li><p>There's a few cases of "magic numbers" like 99. These should be made named constants with #define or const.</p>\n</li>\n<li><p><code>unsigned head</code>, <code>const int</code> etc. You suddenly slip back to the native C types here and there. Stick with stdint.h or use <code>size_t</code> for sizes of types and arrays.</p>\n</li>\n<li><p>Strive to keep for loops as simple as possible. That is, always count upwards and avoid multiple iterators. For example you could as well do this:</p>\n<pre><code> uint16_t start = cBucketBufTail - cBucketBuf + offset;\n for(size_t i=start; i<size; i++)\n</code></pre>\n<p>There's many such needlessly complicated for loops in the code.</p>\n</li>\n<li><p>Avoid <code>strncpy</code>, it's a dangerous function since it is prone to mess up the null termination. And needlessly slow when you know the exact size in advance. So you could have used memcpy:</p>\n<pre><code> memcpy(key, registeredFeed[slotIdx]->key, strlen(registeredFeed[slotIdx]->key) + 1);\n</code></pre>\n<p>Although in this specific case, since you call <code>strlen</code> anyway, you should use neither of these functions including <code>strlen</code>. The correct function here is <code>strcpy</code>:</p>\n<pre><code> strcpy(key, registeredFeed[slotIdx]->key);\n</code></pre>\n</li>\n<li><p>Your error handling is inconsistent - some times you use <code>bool</code>, some times magic numbers -1, -2 etc. All of these function results should be replaced by a consistent error type used by the whole library, in the form of a <code>typedef enum {...} bucket_err_t;</code> Then document which functions that return which error codes, in what situations.</p>\n</li>\n<li><p>Comments containing the function documentation should be placed in the header, in case of public functions. Comments documenting private <code>static</code> functions obviously need to be in the .c file like you have though.</p>\n</li>\n<li><p>You forget const correctness in a few places like <code>void PrintFeedValue(cbucket_t *feed)</code> -> <code>const cbucket_t *</code>.</p>\n</li>\n<li><p>It's ok to use <code>uint8_t</code> as the string type, particularly in embedded systems. However please note that this might upset compilers when you call standard libs with that type. Therefore make a habit of casting to <code>char*</code> before calling <code>strlen</code> etc.</p>\n</li>\n</ul>\n<hr />\n<p>EDIT</p>\n<ul>\n<li>In case you have functions doing <code>return false</code> etc upon error and those functions also return values through parameter pointers, you must document what happens to those parameters in case of errors. Are they untouched in case of errors, are they set to some error code or known value, or are they to be considered as indeterminate values?</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T20:36:34.283",
"Id": "506830",
"Score": "0",
"body": "Could you please elaborate a bit on why \"strncpy\" would mess up the null termination? I thought the whole point of using strncpy was to stay safe while only copying the specified length of data."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T20:58:07.000",
"Id": "506832",
"Score": "0",
"body": "Is it because it ignores the '\\0' when copying the string?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T01:15:49.360",
"Id": "506849",
"Score": "0",
"body": "\"Always count upwards\" is not good advice, especially for embedded systems. Many processors have shorter/smaller/faster instructions for comparing or branching on zero than other values, so the general rule for efficient code is actually to count down rather than up."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T07:26:24.800",
"Id": "506877",
"Score": "0",
"body": "@Edward I am well aware. I am also well aware that most embedded systems compilers have been able to optimize such loops just fine for the past 20 years or so, rendering down-counting loops for the sake of efficiency a \"pre-mature optimization\" of the past. Instead focus on writing readable code and let the compiler worry about micro-optimizations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T07:34:11.643",
"Id": "506883",
"Score": "0",
"body": "\"*Avoid multiple returns from a function*\" is a debatable characteristic. To me, a single point of return can be desirable where there are resources to clean up, but in other functions, such as the one here, I would return early rather than introduce a variable in order to funnel to a single `return`. Some shops have a single-return rule; if so, then abide by that, of course."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T07:40:55.600",
"Id": "506886",
"Score": "1",
"body": "@TobySpeight Yep, why I put \"minor remark\" there since it's complicated. Lots of coding standards enforce a single return only. Personally I use the rule \"functions should only have a single return unless multiple returns make the code more readable\". In this case, it doesn't really matter since the functions are so short, but might as well make it a single return then, if there's no obvious reason to do otherwise."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T07:43:20.823",
"Id": "506888",
"Score": "0",
"body": "@TobySpeight But looking at something like `BucketGetTimestampForFeed` the single return from inside multiple compound statements is more questionable. One will immediately start to ask \"what about the `timestamp` in case of errors\" - something that must be covered by function documentation. Actually that's a very valid review remark, I'll add it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T07:43:51.793",
"Id": "506889",
"Score": "0",
"body": "I think I read more emphasis on \"best … habit\" than into \"minor remark\"!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T11:47:31.893",
"Id": "506903",
"Score": "0",
"body": "@Lundin: on counting up vs. counting down. Reality disagrees with you: https://gcc.godbolt.org/z/6rEPxj"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T11:58:02.673",
"Id": "506904",
"Score": "0",
"body": "@Edward You didn't initialize the variable in the up-counting example so that would be why... fix that bug and the loops turn almost identical save for a `subs` vs `cmp`. I can't tell if those single instructions make any performance difference."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T12:07:51.460",
"Id": "506905",
"Score": "0",
"body": "@Edward Also in this case I was able to get much better code when doing `array[i] = (array[i] & 1)*array[i]*array[i] + !(array[i] & 1)*array[i];`. Given that I got that one right, I'd be much more concerned about why I'd have to write icky manual code like that to get rid of the branch. It would suggest that the optimizer isn't quite fine-tuned for this port."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T12:09:57.667",
"Id": "506906",
"Score": "0",
"body": "@Lundin: *the optimizer isn't quite fine-tuned for this port* is exactly my point. https://gcc.godbolt.org/z/7oTYd7"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T12:12:32.293",
"Id": "506907",
"Score": "0",
"body": "@Edward The initial `add` isn't part of the loop. If you find yourself obfuscating the C code just to chase down that single instruction, well... As shown in the snippet above, there's _much_ better ways to manually shave performance, in case it needs shaving in the first place."
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T08:04:39.727",
"Id": "256669",
"ParentId": "256602",
"Score": "3"
}
},
{
"body": "<p>There is a bug in the BucketPut() function. The following logic does not account for handling the case when the bucket is empty and the timestamp to be written is 0 which could be the case sometimes. In this case, the head will shift backwards by 5 steps while wrapping around and start writing from there while it should have started to write from the start of the bucket.</p>\n<pre><code>//If timestamp had matched, overwrite it with current feed data and append with timestamp.\nif(lastStoredTime == data->unixTime){\n int shiftOffset = 0;\n //move the head backwards by size of time slot index + size of timestamp.\n if(cBucketBuf + shiftOffset > cBucketBufHead){\n //Wrap around to start of the bucket\n shiftOffset -= BUCKET_SIZE;\n }\n cBucketBufHead -= shiftOffset;\n}//timestamp matched!\n</code></pre>\n<p>I fixed the above by simply checking for a bucket empty case. If the bucket is empty, no need to shift the head. Below is the fix. I hope this does not break something else as it seems a simple change.</p>\n<pre><code>//If timestamp had matched, overwrite it with current feed data and append with timestamp.\nif(lastStoredTime == data->unixTime){\n int shiftOffset = 0;\n //Only offset if there is something in the bucket\n if(BucketCheckDataAvailable()){\n shiftOffset = sizeof(slot) + sizeof(data->unixTime); \n }\n //move the head backwards by size of time slot index + size of timestamp.\n if(cBucketBuf + shiftOffset > cBucketBufHead){\n //Wrap around to start of the bucket\n shiftOffset -= BUCKET_SIZE;\n }\n cBucketBufHead -= shiftOffset;\n}//timestamp matched!\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T23:51:09.253",
"Id": "256701",
"ParentId": "256602",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "256669",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T02:43:10.320",
"Id": "256602",
"Score": "1",
"Tags": [
"c",
"database",
"circular-list",
"embedded"
],
"Title": "Embedded IoT: local data storage (Second Update)"
}
|
256602
|
<p>This is my code:</p>
<pre class="lang-py prettyprint-override"><code>def add_to_destination_array(destination_arr, src1, iSrc1, src2, iSrc2):
temp_array_length = len(destination_arr)
while len(destination_arr) - temp_array_length < len(src1) + len(src2):
if iSrc1 < len(src1):
if iSrc2 == len(src2):
destination_arr.append(src1[iSrc1])
iSrc1 += 1
else:
if src1[iSrc1] <= src2[iSrc2]:
destination_arr.append(src1[iSrc1])
iSrc1 += 1
elif src2[iSrc2] <= src1[iSrc1]:
destination_arr.append(src2[iSrc2])
iSrc2 += 1
elif iSrc2 < len(src2):
if iSrc1 == len(src1):
destination_arr.append(src2[iSrc2])
iSrc2 += 1
else:
if src2[iSrc2] <= src1[iSrc1]:
destination_arr.append(src2[iSrc2])
iSrc2 += 1
elif src1[iSrc1] <= src2[iSrc2]:
destination_arr.append(src1[iSrc1])
iSrc1 += 1
def fancy_sort(array_to_sort):
destination_array = []
source1 = [array_to_sort[0]]
source2 = []
iSource1 = 0
iSource2 = 0
got_first_sublist = False
first_sublist_start = 0
second_sublist_start = 0
array_sorted = False
for i in range(1, len(array_to_sort)):
if len(source1) == 0:
source1.append(array_to_sort[i])
first_sublist_start = i
elif not got_first_sublist:
if source1[i-first_sublist_start-1] <= array_to_sort[i]:
# Add elements to the first sublist
source1.append(array_to_sort[i])
else:
# First sublist found, now we start finding the seconds sublist
source2.append(array_to_sort[i])
second_sublist_start = i
got_first_sublist = True
else:
if source2[i-second_sublist_start-1] <= array_to_sort[i]:
# Add elements to the second sublist
source2.append(array_to_sort[i])
else:
# Start adding elements to the destination_array
add_to_destination_array(destination_array, source1, iSource1, source2, iSource2)
# Reset the variables and start over
first_sublist_start = i
source1 = [array_to_sort[i]]
source2 = []
iSource1 = 0
iSource2 = 0
got_first_sublist = False
# If it didn't completely finish "sorting"
if len(source1) > 0:
if len(source1) == len(array_to_sort):
array_sorted = True
elif len(source2) > 0:
add_to_destination_array(destination_array, source1, iSource1, source2, iSource2)
else:
for i in source1:
destination_array.append(i)
# Call the function again to continue sorting
if not array_sorted:
return fancy_sort(destination_array)
return array_to_sort
sorting_array = [31, 72, 32, 10, 95, 50, 25, 18]
print(f"Before: {sorting_array}")
sorted_array = fancy_sort(sorting_array)
print(f"After: {sorted_array}")
</code></pre>
<p>I know it's not the best, but it still works. This algorithm is supposed to be similar to the merge sort, but it doesn't really split the array, and then merges them together. This algorith is supposed to find two already sorted sub-arrays (or sub-lists if you want to call it that), and then "merge" them into another array (called the destination array).</p>
<p>Here is the info I was given to make create this algorithm:</p>
<blockquote>
<p><strong>Algorithm in Plain English</strong><br />
A teacher is trying to alphabetize a collection of papers. She picks up the papers in her hand and, starting at the top of her stack, works her way down until she finds the first paper out of order. That sub-stack is sorted, and is set aside. She does the same thing to find the next sorted sub-stack. These two sub-stacks are then combined into a single sorted stack that she places on the table. She continues through the original stack in her hand, combining pairs of sorted sub-stacks and putting the results on top of the stack on the table. When she is finished, only the stack on the table remains. Now she picks up the stack on the table and again searches for sorted sub-stacks. When she finds a pair of these, they are combined and placed on the table again. This process continues until again all the papers are on the table. When she picks the stack up off of the table and everything is sorted (there is only one sorted sub-stack), then she is done!</p>
<p><strong>Detailed Description of the Algorithm</strong><br />
Start at the beginning of the array and continue until you discover the first element that is not in sorted order. This sub-array may consist of one element, or it may consist of hundreds. We will call this sub-array source1. Now, starting in the slot after source1, find the next sub-array. Again, this may consist of one element or hundreds. We will call this sub-array source2. Note that source1 and source2 are sorted individually. These two sub-arrays correspond to the small piles in the previous paragraph.</p>
<p>Now we will combine these two sub-arrays to form a single sorted sub-array. We will not do this in place. Instead, we will move them into a new sub-array called destination. Now since the two source arrays are sorted, we can assume that the smallest element in the two arrays is at the beginning of one of the two source arrays. In other words, it is at source1[0] or source2[0]. Therefore destination[0] must be filled with either source1[0] or source2[0]. If, for example, source2 has the lower of the two elements, then that element is moved to destination and the index of source2 (which we will call iSource2) is incremented by one. This process is continued until each element from source1 and source2 is moved into destination.</p>
<p>Once the first two sorted sub-arrays are moved to the destination array, then the next two sub-arrays are identified and combined into the destination array. This process continues until each element in the source array is moved into the destination array. Here, we can say that we have completed one pass of the source array.</p>
<p>Note that the sort is not finished yet. We have not sorted the array when we have completed just one pass. The only thing that a single pass accomplishes is to double the size of the sorted sub-arrays. We have to do many passes until the entire destination array becomes a single sorted sub-array. At that point, we can say that the array is sorted.</p>
<p><a href="https://i.stack.imgur.com/mitT4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mitT4.png" alt="enter image description here" /></a></p>
</blockquote>
<p>I am really wanting to go down to just using the <code>array_to_sort</code> and <code>destination_array</code> and then just use the indices for the other stuff instead of the two different source arrays.</p>
<p><a href="https://repl.it/@CodedGenius/MySortingAlgorithm" rel="nofollow noreferrer">Here</a> is a working example.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T07:06:24.850",
"Id": "506646",
"Score": "0",
"body": "Welcome to CodeReview@SE. Leaving \"runs\" intact during *merge sort* has been called [natural](https://en.m.wikipedia.org/wiki/Merge_sort#Natural_merge_sort)."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T04:49:39.833",
"Id": "256605",
"Score": "1",
"Tags": [
"python",
"performance",
"algorithm",
"sorting"
],
"Title": "Making This \"Fancy\" Sort Algorithm a Little Better"
}
|
256605
|
<pre><code>import pandas as pd
import pandas_read_xml as pdx
from lxml import etree
url2='http:'
url='http:'
tree=etree.parse(url)
st=etree.tostring(tree.getroot())
# The list "all_leaves" includes every node and leaf in the tree
from io import StringIO, BytesIO
#st above is encoded as binary
all_leaves=[]
events = ("start", "end")
# "start" are the xml tags start
# "end" are the xml tags with "</"
parent='root' #root of the xml tree
context = etree.iterparse(BytesIO(st), events=events)
for n, actel in enumerate(context):
if actel[0]=='end': #this marks the end of a node
parent = all_leaves[n-1][1] #use previous parent
all_leaves.append([actel[0],parent,actel[1].tag])
#append the action, parent and tag
else:
all_leaves.append([actel[0],parent,actel[1].tag])
if actel[0]=='start': #the current become parent since this
#algorithm is depth first
parent = actel[1].tag
# "leaves" includes only the first row of each table
leaves=[]
for entry in all_leaves:
if (entry not in leaves) and (entry[0]=='start'):
leaves.append(entry)
# These are the names of the tables
nf_nodes=[]
for entry in leaves[2:]:#ignore the first two:
nf_nodes.append(entry[1])
nf_nodes=list(set(nf_nodes))
# The dictionary "all_dic" has keys labeled as the node
# above each set of leaves (i.e. DataFrames) with value equal to the corresponding
# DataFrame or leav
all_dic={}
for l in nf_nodes:
all_dic[l]=pdx.read_xml(url, ['DRFAssessments',l])
</code></pre>
<p>I have the following code below that reads and parses xml files. The following code takes about 10:30 seconds to run. I wanted to see if there were any suggestions or any edits that could be made to the code to increase the speed. The code is used to parse the xml file before it is uploaded to a MYSQL database. It also parses 20 tables if that is any useful</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T10:45:40.777",
"Id": "506656",
"Score": "0",
"body": "Welcome to Code Review! It would be helpful to know the context of the question, since a lot of posts are about parsing XML and increasing its speed. What specifically are you parsing and could you edit the title to match that? Furthermore, it would likely also help to have (a shortened) sample input file so that readers can actually try the code. Hope you get some good answers!"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T05:14:06.723",
"Id": "256606",
"Score": "1",
"Tags": [
"python-3.x",
"sql",
"parsing",
"xml",
"depth-first-search"
],
"Title": "Improving speed of parsing XML file"
}
|
256606
|
<p>This is my second project since I started with Python, this time I learned a little bit of SQL that is so useful and beautifully simple.</p>
<p>Starting idea: Generate a program that will store information in <code>DataBase</code>(SQL).
Goal: Learn SQL basics and expand my knowledge in Python.
After project thoughts: The more basic it look the most difficult to find the BUG in the code. Spent 1 week finding a bug to finish the project and it was a variable repeated in two <code>for loops</code>.</p>
<p>Code purpose: During this time in the world I've seen a lot of paper used to do this job while at the same time they use a computer or tablet to charge you or book you in. What if we get rid of the paper and we only use digital?
This is supposed to be used by the employee not the user. Any confirmed case will be searched and this will allow you to send an email to all the people that were in the same place at the same time or +1 hour.</p>
<p>Really happy I hope yous like it, I know it needs <strong>Validation of User Input</strong> I tried to focus more on the PEP8 and mixture between Python and SQL.</p>
<p>Will appreciate any recommendations. Thank you.</p>
<p>Code:</p>
<pre><code>import sqlite3
import datetime
import time
import smtplib
import imghdr
from email.message import EmailMessage
conn = sqlite3.connect('covid.db')
c = conn.cursor()
notify_group = list()
def enter_data():
def create_table():
c.execute('''CREATE TABLE IF NOT EXISTS
covidTrack(
name TEXT,
email TEXT,
ph_number INTEGER,
datestamp TEXT,
keyword TEXT)''')
i_name = str(input('Please insert FULL NAME : \n ...'))
i_email = str(input('Please insert EMAIL : \n ...'))
i_number = int(input('Please insert PHONE NUMBER : \n ...'))
print('Your data has been saved for acelerated contact, thank you. \n')
time.sleep(1)
def data_entry():
date, keyword = dynamic_data_entry()
c.execute('''INSERT INTO covidTrack
VALUES(?, ?, ?, ?, ?)''', (i_name, i_email, i_number, date, keyword))
conn.commit()
def dynamic_data_entry():
keyword = 'nameofvenue'
date = str(datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'))
return date, keyword
conn.commit()
def read_from_db():
c.execute('''SELECT * FROM covidTrack''')
conn.commit()
create_table()
data_entry()
read_from_db()
menu()
def data_search():
x = input('''Select desired search: \n
Search by FULL NAME. \n
Search by DATE AND TIME (EXTREMELY PRECISE NOT RECOMMENDED.). \n
Exit.
~
''')
if x.lower() == 'full name':
specify_name = input('Please insert full name. \n ')
select_query = c.execute('''SELECT * FROM covidTrack WHERE NAME ==(?) ''', (specify_name,))
for row in c.fetchall():
print('\n')
print('Name:', row[0])
print('Email:', row[1])
print('Phone Number:', row[2])
print('Date and Time:', row[3])
print('Venue:', row[4])
print('\n')
c.execute('''SELECT *
FROM covidTrack
WHERE datestamp >= ?
AND datestamp <= datetime(?, '+1 hours') ''', (row[3],row[3]))
print('Matching Results: \n ')
for row2 in c.fetchall():
print(row2)
notify_group.append(row2[1])
print('\n')
add_people = input('Would you like to notify this group?Y/N')
if add_people.lower() == 'y':
SendMail()
print('All the people in this search has been advised.')
if add_people.lower() == 'n':
menu()
if x.lower() == 'date and time':
specify_datestamp = input('''Please insert full date as shown.
\n
Please follow this format...
\n
YYYY-MM-DD HH:MM:SS ''')
c.execute('''SELECT * FROM covidTrack WHERE datestamp == ? ''', (specify_datestamp,))
for row in c.fetchall():
print('\nName:', row[0])
print('Email:', row[1])
print('Phone Number:', row[2])
print('Date and Time:', row[3])
print('Venue:', row[4])
print('\n')
d = row[3]
c.execute('''SELECT *
FROM covidTrack
WHERE datestamp >= ?
AND datestamp <= datetime(?, '+1 hours') ''',(d,d))
print('Matching Results: \n')
for row2 in c.fetchall():
print(row2[0:4])
menu()
if x.lower() == 'exit':
exit()
def SendMail():
msg = EmailMessage()
msg['Subject'] = 'covidTrack notification.'
msg['From'] = '#############'
msg['To'] = notify_group
msg.set_content('It has been confirmed that you were a close contact in. Please contact us as soon as possible.')
print(notify_group)
with open('covidTrackNotification.png', 'rb') as f:
file_data = f.read()
file_type = imghdr.what(f.name)
file_name = f.name
msg.add_attachment(file_data, maintype='image', subtype=file_type, filename=file_name)
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
smtp.login('###########', '#######')
smtp.send_message(msg)
def menu():
choose_funtion = input('''Please choose action: \n
A TO ENTER DATA. \n
B TO SEARCH DATA. \n
EXIT \n ''')
if choose_funtion.lower() == 'a':
print('You choose enter data.')
enter_data()
if choose_funtion.lower() == 'b':
print('You choose search data.')
data_search()
if choose_funtion.lower() == 'exit':
exit()
menu()
c.close()
conn.close()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T12:51:41.053",
"Id": "506779",
"Score": "1",
"body": "I would use the connection inside a context handler using the `with` statement, e.g. like here: https://www.sqlitetutorial.net/sqlite-python/sqlite-python-select/"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T10:53:01.450",
"Id": "256613",
"Score": "2",
"Tags": [
"python",
"sqlite"
],
"Title": "Covid Tracker + Notify people = Ideal for small coffee place or similar"
}
|
256613
|
<p>I am simply implementing a filter function for one my forms. I'd like to hear some reviews where I can improve in my code or my functionality :)</p>
<p><strong>Summary</strong></p>
<p>I have 1 textbox and 2 comboboxes (See image below):</p>
<p><a href="https://i.stack.imgur.com/VMIjL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VMIjL.png" alt="enter image description here" /></a></p>
<p><strong>Category options</strong></p>
<p><a href="https://i.stack.imgur.com/EeZyy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EeZyy.png" alt="enter image description here" /></a></p>
<p><strong>Status options</strong></p>
<p><a href="https://i.stack.imgur.com/lT8V2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lT8V2.png" alt="enter image description here" /></a></p>
<p><strong>Code</strong></p>
<pre><code>public MainView()
{
InitializeComponent();
categoryText.SelectedIndex = 0;
statusText.SelectedIndex = 0;
RefreshData();
}
List<ConcessionModel> concessionList = new List<ConcessionModel>();
public void RefreshData()
{
DataAccess db = new DataAccess();
concessionList = db.LoadConcessionLog();
dataGrid.DataSource = concessionList;
dataGrid.Columns["Id"].Visible = false;
dataGrid.Columns["PersonCompletingID"].Visible = false;
}
private void searchBtn_Click(object sender, EventArgs e)
{
dataGrid.DataSource = Filter(productText.Text, categoryText.Text, statusText.Text);
}
private List<ConcessionModel> Filter(string product, string category, string status)
{
if (category == "All" && status != "All")
{
return concessionList
.Where(x => x.Product
.IndexOf(product, StringComparison.InvariantCultureIgnoreCase) >= 0 && x.Status
.IndexOf(status, StringComparison.InvariantCultureIgnoreCase) >= 0)
.ToList();
}
else if (category != "All" && status == "All")
{
return concessionList
.Where(x => x.Product
.IndexOf(product, StringComparison.InvariantCultureIgnoreCase) >= 0 && x.Category
.IndexOf(category, StringComparison.InvariantCultureIgnoreCase) >= 0)
.ToList();
}
else if(category == "All" && status == "All")
{
return concessionList
.Where(x => x.Product
.IndexOf(product, StringComparison.InvariantCultureIgnoreCase) >= 0).ToList();
}
else
{
return concessionList
.Where(x => x.Product
.IndexOf(product, StringComparison.InvariantCultureIgnoreCase) >= 0 && x.Category
.IndexOf(category, StringComparison.InvariantCultureIgnoreCase) >= 0 && x.Status
.IndexOf(status, StringComparison.InvariantCultureIgnoreCase) >= 0)
.ToList();
}
}
public void ClearConcessionFilter()
{
productText.Clear();
categoryText.SelectedIndex = 0;
statusText.SelectedIndex = 0;
dataGrid.DataSource = concessionList;
}
</code></pre>
<p><strong>ConcessionModel</strong></p>
<pre><code>public class ConcessionModel
{
public int Id { get; set; }
[DisplayName("Date Created")]
public DateTime DateCreated { get; set; }
public int PersonCompletingID { get; set; }
public string Product { get; set; }
[DisplayName("Batch Number")]
public string BatchNumber { get; set; }
[DisplayName("Quantity Affected")]
public string QuantityAffected { get; set; }
[DisplayName("Reason For Concession")]
public string ReasonForConcession { get; set; }
public string Category { get; set; }
public string Status { get; set; }
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T12:48:39.440",
"Id": "506664",
"Score": "0",
"body": "Can you please share with us the class definition of the `ConcessionModel`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T12:52:53.390",
"Id": "506665",
"Score": "1",
"body": "@PeterCsala No problem, give me 1 minute."
}
] |
[
{
"body": "<p>Let me focus on the <code>Filter</code> method.</p>\n<ul>\n<li>There are a lot of repetitions in that method, which makes your code\n<ul>\n<li>harder to maintain\n<ul>\n<li>for example: replacing <code>IndexOf</code> to <code>Equals</code></li>\n<li>or by changing the <code>StringComparison</code> option to another</li>\n</ul>\n</li>\n<li>and more error-prone\n<ul>\n<li>for example: it is easy to misspell the <code>All</code> at one of the occurrences.</li>\n</ul>\n</li>\n</ul>\n</li>\n</ul>\n<p>There are a couple of useful techniques that can make your code less error-prone and easier to change:</p>\n<ul>\n<li>Using constants, like: <code>const string all = "All";</code></li>\n<li>Using single return, like: <code>return concessionList.Where(predicate).ToList();</code></li>\n<li>Extracting common logic, like:</li>\n</ul>\n<pre><code>static bool IsPresent(string source, string target)\n => source.IndexOf(target, StringComparison.InvariantCultureIgnoreCase) >= 0;\n</code></pre>\n<ul>\n<li>Using default values instead of fallback,\n<ul>\n<li>like: <code>predicate</code> can have default value instead of relying on a\nfinal <code>else</code> block.</li>\n</ul>\n</li>\n</ul>\n<p>With these in our hand the <code>Filter</code> method could be rewritten like this:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>private List<ConcessionModel> Filter(string product, string category, string status)\n{\n const string all = "All";\n\n static bool IsPresent(string source, string target) \n => source.IndexOf(target, StringComparison.InvariantCultureIgnoreCase) >= 0;\n\n Func<ConcessionModel, bool> predicate = model =>\n IsPresent(model.Product, product) &&\n IsPresent(model.Category, category) && \n IsPresent(model.Status, status);\n\n if (category == all && status != all)\n {\n predicate = model =>\n IsPresent(model.Product, product) &&\n IsPresent(model.Status, status);\n }\n else if (category != all && status == all)\n {\n predicate = model =>\n IsPresent(model.Product, product) &&\n IsPresent(model.Category, category);\n }\n else if (category == all && status == all)\n {\n predicate = model =>\n IsPresent(model.Product, product);\n }\n \n return concessionList.Where(predicate).ToList();\n}\n</code></pre>\n<ul>\n<li><code>predicate</code>: I've defined a function variable (<code>Func<TInput, TOutput></code>)\n<ul>\n<li>It receives a <code>ConcessionModel</code> (as <code>TInput</code>)</li>\n<li>and will return with a <code>bool</code> (as <code>TOutput</code>).</li>\n</ul>\n</li>\n<li>So, I have defined a function which implementation varies based on the input parameters.</li>\n<li>We use this function as a filter condition (<code>Where</code>) against the data source (<code>concessionList</code>)\n<ul>\n<li>Here I have used the short form, but could be written like this:\n<ul>\n<li><code>return concessionList.Where(model => predicate(model)).ToList();</code></li>\n</ul>\n</li>\n</ul>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T13:45:38.593",
"Id": "506668",
"Score": "0",
"body": "The `Func<ConcessionModel, bool> predicate = model` is not something I have seen before, are you able to explain please to what is going in? :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T14:04:11.340",
"Id": "506670",
"Score": "0",
"body": "@LV98 I've extended my answer, please check it again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T15:02:47.523",
"Id": "506672",
"Score": "0",
"body": "Quick question.. let's say I had a boolean value in my Model called `Archived`. New parameter will be added in the Filter as `bool archived`, but the `IsPresent` will show an error that it cannot convert from `bool to string`. How would you alter the current code you have?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T15:13:27.913",
"Id": "506673",
"Score": "1",
"body": "@LV98 `IsPresent` was designed for string comparison. If you want to filter via an additional bool variable then you can do something like this: `predicate = model => IsPresent(model.Product, product) && model.Archived == archived`. Does it answer your question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T15:43:23.197",
"Id": "506678",
"Score": "0",
"body": "Ah I see... Thank you"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T13:15:56.537",
"Id": "256616",
"ParentId": "256615",
"Score": "5"
}
},
{
"body": "<p>This approach is IMHO a bad idea. Already your code is barely maintainable and contains numerous copy-pasted sections.</p>\n<p>You should pass a "filter" (a custom class) to <code>LoadConcessionLog()</code> (bad method name, BTW) and let the <code>IQueryable</code> handle the various filters (I'm assuming you use Entity Framework), along the lines of <a href=\"https://codereview.stackexchange.com/a/167507/10582\">this answer</a> (or one of the other answers on that page). Let your query apply the necessary filters, so the data that is returned from the DB is already limited.</p>\n<hr />\n<p>If you're using Dapper, then you can still apply similar logic. You can either construct the <code>WHERE</code> clause in code, or you could write an SQL query that has a <code>WHERE</code> clause that <a href=\"https://stackoverflow.com/a/2329692/648075\">takes this into account</a>.</p>\n<p>If you take the second approach, you could have a query with a WHERE like this;</p>\n<pre><code>WHERE 1 = 1\n AND (@Category IS NULL OR Category = @Category)\n AND (@Status IS NULL OR Status = @Status)\n</code></pre>\n<p>You then pass for instance <code>new { Category = category, Status = status }</code> where <code>category</code> and <code>status</code> are <code>string</code>s which could contain a value or be <code>null</code>.</p>\n<hr />\n<p>The main ideas are:</p>\n<ul>\n<li>let your database do the filtering</li>\n<li>write your code in an extendible way, where adding a new filter doesn't require you to copy-paste blocks of logic.</li>\n</ul>\n<p>Consider for instance that you need to add a third filter. In your current code you need to rethink all the <code>if</code>/<code>else</code> logic, you need to add this third filter to each scenario, plus you need to take into account new combinations,... It is a nightmare to maintain. Whereas if you apply my logic, you simply need to add a property to your filter class, you need to adapt the <code>WHERE</code> clause, you need to pass the new filter in your Dapper call, and that is all.</p>\n<p>And you might think: well, isn't this overkill when I only need two filters? Perhaps. But the advantage is you learn skills that you can later apply in bigger projects.</p>\n<hr />\n<p>It is also odd that you use <code>IndexOf</code> when comparing <code>Category</code> or <code>Status</code>; I'd expect those comparisons to necessitate an "equals". What if you get a new status called "Reopened": now that also matches "Open" in your logic.</p>\n<p>Also, consider normalizing your database. "Category" could be a table of its own, and its ID would then be a foreign key in your Products table. Same for "Status", although that might also be an <code>enum</code>. ("Category" could be an <code>enum</code> as well, of course.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T13:42:52.780",
"Id": "506667",
"Score": "0",
"body": "I am using dapper instead of Entity, sorry should of mentioned."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T15:22:22.203",
"Id": "506674",
"Score": "0",
"body": "@LV98 I have added a section WRT Dapper as well."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T13:21:49.593",
"Id": "256617",
"ParentId": "256615",
"Score": "2"
}
},
{
"body": "<p>Here is another simpler way of doing the filter :</p>\n<pre><code>private bool EqualsOrSource(string source, string target, bool required)\n{ \n var result = target == "All" && !required ? source : target;\n\n return source.Equals(result, StringComparison.InvariantCultureIgnoreCase);\n}\n\nprivate List<ConcessionModel> Filter(string product, string category, string status)\n{\n return concessionList\n .Where(x => EqualsOrSource(x.Product, product, true) // required\n && EqualsOrSource(x.Category, category) // optional \n && EqualsOrSource(x.Status, status) // optional \n ).ToList();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T22:45:55.050",
"Id": "256648",
"ParentId": "256615",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "256616",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T12:39:15.930",
"Id": "256615",
"Score": "2",
"Tags": [
"c#"
],
"Title": "Filter functionality Project using C#"
}
|
256615
|
<p>The question comes from <a href="//stackoverflow.com/q/66436802/how-to-separate-a-list-of-serial-numbers-into-multiple-lists-with-matched-prefix/66437748?noredirect=1#comment117453961_66437748">How to separate a list of serial numbers into multiple lists with matched prefix?</a> on Stack Overflow.</p>
<p>Input:</p>
<blockquote>
<pre><code>sn = ['bike-001', 'bike-002', 'car/001', 'bus/for/001', 'car/002', 'bus/for/002']
</code></pre>
</blockquote>
<p>Intended output:</p>
<blockquote>
<pre><code># string with same prefix will be in the same list, e.g.:
sn1 = ['bike-001', 'bike-002']
sn2 = ['car/001', 'car/002']
sn3 = ['bus/for/001', 'bus/for/002']
</code></pre>
</blockquote>
<p>The original thread already had a brilliant answer using <code>.startswith(<sub_str>)</code>, however I still want to use <code>regex</code> to solve the question.</p>
<p>Here's what I've tried: I use <code>re.sub()</code> to get the prefix and <code>re.search()</code> to get the 3-digits serial number. I'd like to know if there is a better way (like using one-time <code>regex</code> function) to get the solution.</p>
<pre><code>import re
sn = ['bike-001', 'bike-002', 'car/001', 'bus/for/001', 'car/002', 'bus/for/002']
sn_dict = {}
for item in sn:
category = re.sub(r'\d{3}', "", item)
number = re.search(r'\d{3}', item).group()
if category not in sn_dict.keys():
sn_dict[category] = []
sn_dict[category].append(category + number)
</code></pre>
<p>After running the script we will have the following <code>sn_dict</code>:</p>
<pre class="lang-py prettyprint-override"><code>{
'bike-': ['bike-001', 'bike-002'],
'car/': ['car/001', 'car/002'],
'bus/for/': ['bus/for/001', 'bus/for/002']
}
</code></pre>
|
[] |
[
{
"body": "<p>In terms of what we accept, it might be worth anchoring the digit-string to the end of the <code>item</code> with <code>$</code>.</p>\n<p>The code looks to be reimplementing quite a lot of <a href=\"https://docs.python.org/3/library/itertools.html#itertools.groupby\" rel=\"nofollow noreferrer\"><code>itertools.groupby</code></a>. Assuming we don't care about order, we could easily re-write to build off that by sorting the input and passing a suitable <code>key</code> function.</p>\n<p>Alternatively, write a more general <code>split_to()</code> function that accepts a <code>key</code> function in a similar manner to <code>groupby</code>, so we can separate the general mechanism from the particular instance we have here.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T15:12:53.357",
"Id": "256623",
"ParentId": "256619",
"Score": "2"
}
},
{
"body": "<p>You can do this with <code>re.findall</code>. Instead of iterating over each string, you can combine all the serial numbers into one string and use <code>regex</code> to find all the matches (this implementation assumes there are no spaces in the serial number).</p>\n<pre><code>import re\n\nstring_list = ['bike-001', 'bike-002', 'car/001', 'bus/for/001', 'car/002', 'bus/for/002']\nstring = ' '.join(string_list)\nmatches = re.findall(r"([^0-9])", string)\nnumbers = re.findall(r"([0-9]{3})", string)\nprefixes = ''.join(c for c in matches).split()\nresult_dict = {}\nfor prefix, number in zip(prefixes, numbers):\n if prefix not in result_dict.keys():\n result_dict[prefix] = []\n result_dict[prefix].append(prefix + number)\n</code></pre>\n<p>The first <code>re.findall</code> searches for any string that is <em>not</em> a number. The second finds <em>any</em> succession of three numbers. The next line combines the characters in <code>matches</code>, and since we denoted that we separated each serial number by <code>' '</code>, we can split using the same value. Then, we use the same code present in your question to populate the result dictionary.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T15:28:54.813",
"Id": "256624",
"ParentId": "256619",
"Score": "4"
}
},
{
"body": "<p>As an alternative solution, you can avoid concatenating and recombining strings and instead just match against the prefix and add to dict directly from there.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import re\n\nstring_list = ['bike-001', 'bike-002', 'car/001', 'bus/for/001', 'car/002', 'bus/for/002']\nresult_dic = {}\nfor item in string_list:\n prefix = re.match("([^0-9]+)", item).group()\n if prefix not in result_dic:\n result_dic[prefix] = []\n result_dic[prefix].append(item)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T00:30:36.720",
"Id": "256654",
"ParentId": "256619",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "256624",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T14:00:52.553",
"Id": "256619",
"Score": "4",
"Tags": [
"python",
"regex"
],
"Title": "use regex to separate a list of serial numbers into multiple lists with matched prefix"
}
|
256619
|
<p>Right now I have a snake game that is working but I need a way to make my code look better and work better.</p>
<p>A method I named <code>GameSense</code> is very long and I need a way to make it more object-oriented. I want to use enums.</p>
<p><em>This is what my teacher sent back to me:</em></p>
<blockquote>
<p>The game is very nice and nicely working tail! The test you have also follows the right idea but uses an <code>UpdatePosition</code> method that you have not implemented. I'm also thinking about your class pixel - you do not use it for anything in the rest of the game. You should use it instead of e.g. <code>berryx</code>, <code>berryy</code>. What I am trying to access is more use of object orientation and division into methods, and not a single long method like <code>GameSense</code> right now. Also want to see you use enum / bool instead of strings for e.g. the variables <code>movement</code> and <code>buttonpressed</code>. However, I'm glad you got an interface on a corner</p>
</blockquote>
<p>As you can see… I feel pretty suck right now.<br />
What do I need to do here in order to make the program be more object-oriented?</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace Snake
{
/// <summary>
/// Start class, everything goes from here.
/// Made by Karwan!
/// </summary>
public class Starter : InterF
{
public static object Key { get; private set; }
/// <summary>
/// Main method.
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
//Making the text green and also given a player
//options to chose from.
Console.ForegroundColor = ConsoleColor.Green;
bool loopC = true;
while (loopC)
{
string mystring = null; Console.WriteLine("Welcome to Snake.\nPress S+Enter to start or press Q+Enter to exit.");
mystring = Console.ReadLine();
switch (mystring)
{
case "Q":
Environment.Exit(0);
break;
case "S":
Console.WriteLine("Starting game!");
System.Threading.Thread.Sleep(4000);
loopC = false;
break;
default:
Console.WriteLine("Invalid Entry.. Try again.");
break;
}
}
//Call for GameSense if
//they want to play.
GameSense();
}
/// <summary>
/// Game object!
/// </summary>
public static void GameSense()
{
//Game console height/width.
Console.WindowHeight = 30;
Console.WindowWidth = 70;
int screenwidth = Console.WindowWidth;
int screenheight = Console.WindowHeight;
Random randomnummer = new Random();
//Lenght of tail == current score.
int score = 2;
int gameover = 0;
//Gather positions from pixel class.
pixel positions = new pixel();
positions.xpos = screenwidth / 2;
positions.ypos = screenheight / 2;
positions.Black = ConsoleColor.Red;
string movement = "RIGHT";
//Position manegment.
List<int> xpos = new List<int>();
List<int> ypos = new List<int>();
int berryx = randomnummer.Next(0, screenwidth);
int berryy = randomnummer.Next(0, screenheight);
//Time manegment.
DateTime time1 = DateTime.Now;
DateTime time2 = DateTime.Now;
string buttonpressed = "no";
//Draw world from GameWorld.cs.
GameWorld.DrawBorder(screenwidth, screenheight);
while (true)
{
GameWorld.ClearConsole(screenwidth, screenheight);
if (positions.xpos == screenwidth - 1 || positions.xpos == 0 || positions.ypos == screenheight - 1 || positions.ypos == 0)
{
gameover = 1;
}
Console.ForegroundColor = ConsoleColor.Green;
if (berryx == positions.xpos && berryy == positions.ypos)
{
score++;
berryx = randomnummer.Next(1, screenwidth - 2);
berryy = randomnummer.Next(1, screenheight - 2);
}
for (int i = 0; i < xpos.Count(); i++)
{
Console.SetCursorPosition(xpos[i], ypos[i]);
Console.Write("*");
if (xpos[i] == positions.xpos && ypos[i] == positions.ypos)
{
gameover = 1;
}
}
if (gameover == 1)
{
break;
}
Console.SetCursorPosition(positions.xpos, positions.ypos);
Console.ForegroundColor = positions.Black;
Console.Write("*");
//Food color & position.
Console.SetCursorPosition(berryx, berryy);
Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write("*");
Console.CursorVisible = false;
time1 = DateTime.Now;
buttonpressed = "no";
while (true)
{
time2 = DateTime.Now;
if (time2.Subtract(time1).TotalMilliseconds > 500) { break; }
if (Console.KeyAvailable)
{
ConsoleKeyInfo info = Console.ReadKey(true);
//Connecting the buttons to the x/y movments.
if (info.Key.Equals(ConsoleKey.UpArrow) && movement != "DOWN" && buttonpressed == "no")
{
movement = "UP";
buttonpressed = "yes";
}
if (info.Key.Equals(ConsoleKey.DownArrow) && movement != "UP" && buttonpressed == "no")
{
movement = "DOWN";
buttonpressed = "yes";
}
if (info.Key.Equals(ConsoleKey.LeftArrow) && movement != "RIGHT" && buttonpressed == "no")
{
movement = "LEFT";
buttonpressed = "yes";
}
if (info.Key.Equals(ConsoleKey.RightArrow) && movement != "LEFT" && buttonpressed == "no")
{
movement = "RIGHT";
buttonpressed = "yes";
}
}
}
//Giving the connections value
//to change x/y to make the movment happen.
xpos.Add(positions.xpos);
ypos.Add(positions.ypos);
switch (movement)
{
case "UP":
positions.ypos--;
break;
case "DOWN":
positions.ypos++;
break;
case "LEFT":
positions.xpos--;
break;
case "RIGHT":
positions.xpos++;
break;
}
if (xpos.Count() > score)
{
xpos.RemoveAt(0);
ypos.RemoveAt(0);
}
}
Console.SetCursorPosition(screenwidth / 5, screenheight / 2);
Console.WriteLine("Game over, Score: " + score);
Console.SetCursorPosition(screenwidth / 5, screenheight / 2 + 1);
System.Threading.Thread.Sleep(1000);
restart();
}
/// <summary>
/// Restarter.
/// </summary>
public static void restart()
{
string Over = null; Console.WriteLine("\nWould you like to start over? Y/N");
bool O = true;
while (O)
{
Over = Console.ReadLine();
switch (Over)
{
case "Y":
Console.WriteLine("\nRestarting!");
System.Threading.Thread.Sleep(2000);
break;
case "N":
Console.WriteLine("\nThank you for playing!");
Environment.Exit(0);
break;
default:
Console.WriteLine("Invalid Entry.. Try again.");
break;
}
}
}
/// <summary>
/// Set/get pixel position.
/// </summary>
public class pixel
{
public int xpos { get; set; }
public int ypos { get; set; }
public ConsoleColor Black { get; set; }
}
}
}
</code></pre>
<p>My test class</p>
<pre><code>using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
using Snake;
using System;
using System.Collections.Generic;
using System.Text;
using static Snake.Starter;
namespace Snake.Tests
{
[TestClass()]
public class StarterTests
{
/// <summary>
/// Testing the movment.
/// </summary>
[TestMethod()]
public void test()
{
var pos = new pixel();
pos.xpos = 10;
pos.ypos = 10;
// this is the operation:
UpdatePosition(pos, "UP");
// check the results
NUnit.Framework.Assert.That(pos.xpos, Is.EqualTo(10));
NUnit.Framework.Assert.That(pos.ypos, Is.EqualTo(9));
}
/// <summary>
/// Updating pixel class.
/// </summary>
/// <param name="pos"></param>
/// <param name="v"></param>
private void UpdatePosition(pixel pos, string v)
{
throw new NotImplementedException();
}
}
}
</code></pre>
<p>This is just the gameworld:</p>
<pre><code>using System;
using System.Linq;
public class GameWorld
{
/// <summary>
/// Clear console for snake.
/// </summary>
/// <param name="screenwidth"></param>
/// <param name="screenheight"></param>
public static void ClearConsole(int screenwidth, int screenheight)
{
var blackLine = string.Join("", new byte[screenwidth - 2].Select(b => " ").ToArray());
Console.ForegroundColor = ConsoleColor.Black;
for (int i = 1; i < screenheight - 1; i++)
{
Console.SetCursorPosition(1, i);
Console.Write(blackLine);
}
}
/// <summary>
/// Draw boared.
/// </summary>
/// <param name="screenwidth"></param>
/// <param name="screenheight"></param>
public static void DrawBorder(int screenwidth, int screenheight)
{
var horizontalBar = string.Join("", new byte[screenwidth].Select(b => "■").ToArray());
Console.SetCursorPosition(0, 0);
Console.Write(horizontalBar);
Console.SetCursorPosition(0, screenheight - 1);
Console.Write(horizontalBar);
for (int i = 0; i < screenheight; i++)
{
Console.SetCursorPosition(0, i);
Console.Write("■");
Console.SetCursorPosition(screenwidth - 1, i);
Console.Write("■");
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T22:27:26.500",
"Id": "506835",
"Score": "0",
"body": "A small tip: `switch (mystring.ToUpper())` and `switch (Over.ToUpper())` will allow input in lower case."
}
] |
[
{
"body": "<p><strong>OOP - Grouping data that belongs together</strong></p>\n<blockquote>\n<p>I'm also thinking about your class pixel - you do not use it for anything in the rest of the game. You should use it instead of e.g. berryx, berryy.</p>\n</blockquote>\n<p>You are storing X and Y positions in unrelated lists:</p>\n<pre><code>List<int> xpos = new List<int>();\nList<int> ypos = new List<int>();\nint berryx = randomnummer.Next(0, screenwidth);\nint berryy = randomnummer.Next(0, screenheight);\n</code></pre>\n<p>But earlier, you were grouping a position (i.e. an XY coordinate) in a single object:</p>\n<pre><code>pixel positions = new pixel();\npositions.xpos = screenwidth / 2;\npositions.ypos = screenheight / 2;\n</code></pre>\n<p>Your teacher is essentially telling you to do the same thing for all X and Y coordinates.</p>\n<p>I'm going to introduce a new class here called <code>Position</code>. It's like your <code>Pixel</code> class, but without specifying a color. The goal of the <code>Position</code> class is to represent a single (X,Y) coordinate:</p>\n<pre><code>public class Position\n{\n public int X { get; set; }\n public int Y { get; set; }\n}\n</code></pre>\n<p>Now that you have this class, you can start using it in all places where you are currently using separate X and Y values:</p>\n<pre><code>// Instead of:\n\nList<int> xpos = new List<int>();\nList<int> ypos = new List<int>(); \n\n// Use:\n\nList<Position> positions = new List<Position>(); \n\n// Instead of:\n\nint berryx = randomnummer.Next(0, screenwidth);\nint berryy = randomnummer.Next(0, screenheight);\n\n// Use:\n\nPosition berryPosition = new Position()\n{\n X = randomnummer.Next(0, screenwidth),\n Y = randomnummer.Next(0, screenheight)\n}; \n</code></pre>\n<p>Note also that the <code>Pixel</code> class can be adjusted to reuse this <code>Position</code>:</p>\n<pre><code>public class Pixel\n{\n public Position Position { get; set; }\n public ConsoleColor Color { get; set; }\n}\n</code></pre>\n<p>I'm going to leave the further adjustments (i.e. how you access this data later on) as an exercise for you. It's no different from how you were accessing your <code>Pixel</code> data already.</p>\n<hr />\n<p><strong>OOP - Class methods</strong></p>\n<p>Other than storing data values, classes can have methods. Class methods are great for housing any logic that belongs to the object.</p>\n<p>For example, berries should be able to decide how they generate their position. Right now, you're just using a total random, but that could change over time. For example, berries might not want to spawn on borders, or next to their previous position.<br />\nWhatever the reason, the main takeaway here is that it'd be practical to have the berry contain the "berry position generating logic".</p>\n<p>To keep things simple, we're going to assume that the same berry doesn't change position when it is eaten, but rather that you always make a <code>new Berry</code> (hint!) whenever the previous one gets eaten. Therefore, the position of the new berry can be decided in the class constructor.</p>\n<p>I'm going to <em>not</em> do something we could do. Try and spot it. I'll correct it later.</p>\n<pre><code>public class Berry\n{\n public int X { get; set; }\n public int Y { get; set; }\n\n public Berry(int screenWidth, int screenHeight)\n {\n var rand = new Random();\n this.X = GenerateX(rand, screenwidth);\n this.Y = GenerateY(rand, screenHeight);\n }\n\n private int GenerateX(Random rand, int screenWidth)\n {\n return rand.Next(0, screenWidth); \n }\n\n private int GenerateY(Random rand, int screenHeight)\n {\n return rand.Next(0, screenHeight); \n }\n}\n</code></pre>\n<p>Did you spot the thing we could improve? Think back to the previous section.</p>\n<p>We created a <code>Position</code> class specifically to represent XY coordinates. We should be <strong>reusing</strong> that logic here!</p>\n<pre><code>public class Berry\n{\n public Position Position { get; private set; }\n\n public Berry(int screenWidth, int screenHeight)\n {\n var rand = new Random();\n this.Position = GeneratePosition(rand, screenWidth, screenHeight);\n }\n\n private int GeneratePosition(Random rand, int screenWidth, int screenHeight)\n {\n return new Position()\n {\n X = rand.Next(0, screenWidth),\n Y = rand.Next(0, screenHeight)\n }; \n }\n}\n</code></pre>\n<p>There's another berry-specific piece of logic in your code: drawing it on the screen. Berries have their own color. This belongs to the <code>Berry</code> class.</p>\n<p><em>Note that I'm omitting the <code>Berry</code> code from the previous snippet to keep it focused, but these should of course be merged together in the real code.</em></p>\n<pre><code>public class Berry\n{\n // ...\n\n public ConsoleColor Color = ConsoleColor.Cyan;\n\n public void Draw()\n {\n Console.SetCursorPosition(this.Position.X, this.Position.Y);\n Console.ForegroundColor = this.Color;\n Console.Write("*");\n Console.CursorVisible = false;\n }\n}\n</code></pre>\n<p>Notice how we've relied on the fact that the <code>Berry</code> object already knows its position and its color, so we were able to write our code to just fetch that information.</p>\n<p>This opens the door to a neat little improvement. Just like we randomize the berry's position, why not randomize its color? If you look back at the <code>Draw()</code> logic, you'll see that it just uses the color in <code>this.Color</code>. So if we change the value of <code>this.Color</code>, the printed character will change color (without us needing the change the <code>Draw()</code> method itself).</p>\n<p>I'm going to limit the possible range of colors to a list that we pre-select. That's better than a wild random. Also, take note of <a href=\"https://stackoverflow.com/questions/17456788/how-to-randomly-pick-one-of-known-console-colors-for-text/35516250\">this StackOverflow answer</a> with many solutions on how to randomly select a color.</p>\n<p>This is the combined logic of everything we discussed:</p>\n<pre><code>public class Berry\n{\n public Position Position { get; private set; }\n public ConsoleColor Color { get; private set; }\n\n private readonly ConsoleColor[] _allowedColors = new ConsoleColor[]\n {\n ConsoleColor.Cyan, ConsoleColor.Yellow, ConsoleColor.Red, ConsoleColor.Green\n };\n\n public Berry(int screenWidth, int screenHeight)\n {\n var rand = new Random();\n this.Position = GeneratePosition(rand, screenWidth, screenHeight);\n this.Color = GenerateColor(rand);\n }\n\n private int GeneratePosition(Random rand, int screenWidth, int screenHeight)\n {\n return new Position()\n {\n X = rand.Next(0, screenWidth),\n Y = rand.Next(0, screenHeight)\n }; \n }\n\n private ConsoleColor GenerateColor(Random rand)\n {\n return _allowedColors.ElementAt(random.Next(_allowedColors .Length));\n }\n\n public void Draw()\n {\n Console.SetCursorPosition(this.Position.X, this.Position.Y);\n Console.ForegroundColor = this.Color;\n Console.Write("*");\n Console.CursorVisible = false;\n }\n}\n</code></pre>\n<p>This is an object-oriented berry. Now, your game logic has to <em>minimally</em> interact with the berry:</p>\n<pre><code>var berry = new Berry(Console.WindowWidth, Console.WindowHeight);\n\nberry.Draw();\n</code></pre>\n<p><strong>Everything else is contained in the <code>Berry</code> class</strong>. Hint: that's why they call this kind of coding style "encapsulation". The berry logic is contained in the <code>Berry</code> class and hidden from sight so the rest of the codebase doesn't get distracted by it.</p>\n<hr />\n<p><strong>Magic strings</strong></p>\n<blockquote>\n<p>Also want to see you use enum / bool instead of strings for e.g. the variables <code>movement</code> and <code>buttonpressed</code>.</p>\n</blockquote>\n<p>Strings are nice and readable, but they are also not very memory efficient (compared to other data types), and they allow for a lot of ambiguity, e.g. how <code>"right"</code> and <code>"Right"</code> are two different values.</p>\n<p>You should use data types that match what you're trying to do.</p>\n<p><code>buttonpressed</code> is clearly a boolean value. The easiest way to think of a boolean is to think of a light switch. It only has two possible positions. Whether that's "yes/no", "on/off", "true/false", "alive/dead", ... is semantical and not relevant. In C#, you just use <code>true</code> and <code>false</code></p>\n<pre><code>bool buttonPressed = false;\n\nif(buttonPressed)\n Console.WriteLine("This WON'T be printed because it's false");\n\nbuttonPressed = true;\n\nif(buttonPressed)\n Console.WriteLine("This WILL be printed because it's true");\n</code></pre>\n<p>I suspect your teacher will have given you study material about data types such as booleans, so I suggest you revise that material.</p>\n<p><code>movement</code> is different. Here, you're not dealing with something that is easily expressed using a known data type. You're dealing with a closed list of a few options, so an <code>enum</code> is appropriate here.</p>\n<pre><code>public enum Direction { Up, Down, Left, Right }\n</code></pre>\n<p>The intention of your code will remain the same, but you'll be using better data types that better suit your needs:</p>\n<pre><code>//Connecting the buttons to the x/y movments. \nif (info.Key.Equals(ConsoleKey.UpArrow) && movement != Direction.Down && !buttonpressed)\n{\n movement = Direction.Up;\n buttonpressed = true;\n}\nif (info.Key.Equals(ConsoleKey.DownArrow) && movement != Direction.Up && !buttonpressed)\n{\n movement = Direction.Down;\n buttonpressed = true;\n}\nif (info.Key.Equals(ConsoleKey.LeftArrow) && movement != Direction.Right && !buttonpressed)\n{\n movement = Direction.Left;\n buttonpressed = true;\n}\nif (info.Key.Equals(ConsoleKey.RightArrow) && movement != Direction.Left && !buttonpressed)\n{\n movement = Direction.Right;\n buttonpressed = true;\n}\n</code></pre>\n<p>I left <code>buttonpressed</code> in for now, to show you the syntax. However, you don't actually need it here. If you had used <code>if else</code> instead of <code>if</code>, you would've automatically been sure that only <em>one</em> possible outcome would be reached, and not multiple.</p>\n<pre><code>if (info.Key.Equals(ConsoleKey.UpArrow) && movement != Direction.Down)\n{\n movement = Direction.Up;\n}\nelse if (info.Key.Equals(ConsoleKey.DownArrow) && movement != Direction.Up)\n{\n movement = Direction.Down;\n}\nelse if (info.Key.Equals(ConsoleKey.LeftArrow) && movement != Direction.Right)\n{\n movement = Direction.Left;\n}\nelse if (info.Key.Equals(ConsoleKey.RightArrow) && movement != Direction.Left)\n{\n movement = Direction.Right;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T02:02:32.253",
"Id": "506852",
"Score": "0",
"body": "Hey.. I still have a lot of problems with my code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T15:25:49.763",
"Id": "256683",
"ParentId": "256622",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "256683",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T14:56:30.613",
"Id": "256622",
"Score": "0",
"Tags": [
"c#",
"object-oriented",
"game",
"snake-game"
],
"Title": "Object-oriented Snake game"
}
|
256622
|
<p>I just implemented my <code>memcpy</code> function without any previous lookup.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void * copy ( void * destination, const void * source, size_t num )
{
if ((destination != NULL) && (source != NULL))
{
unsigned int *dst = destination;
const unsigned int *src = source;
unsigned int blocks = num/sizeof(unsigned int);
unsigned int left = num%sizeof(unsigned int);
while(blocks--){
*dst++ = *src++;
}
if (left){
unsigned char *cdst = (unsigned char *)dst;
const unsigned char *csrc = (const unsigned char *)src;
while(left--)
*cdst++ = *csrc++;
}
}
return destination;
}
</code></pre>
<p>When looking at other memcpy implementations I find some differences:</p>
<ol>
<li>unaligned address not handled</li>
<li>use of <strong>long</strong> instead <strong>unsigned int</strong></li>
</ol>
<p>Now what I didn't understand is point number 2. As far I know <strong>int</strong> will always be CPU WORD size i.e for 16bit it will be 2bytes and 32bit it will be 4bytes. But for long it must be 32bit minimum.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T20:30:49.223",
"Id": "506709",
"Score": "0",
"body": "Welcome to the Code Review Community. We review working code and provide suggestions on how to improve that code. We don't explain code or usage so both points 1 and 2 are borderline off-topic. We will review the `memcpy` function you wrote."
}
] |
[
{
"body": "<p><strong>Alignment</strong></p>\n<p><code>unsigned int *dst = destination;</code> fails when <code>destination</code> is not aligned for <code>unsigned</code>. Same for <code>src</code>. (OP seems be somewhat aware of this given "unaligned address not handled")</p>\n<p><strong>Aliasing</strong></p>\n<p>Possible strict aliasing violation. See <a href=\"https://stackoverflow.com/a/98702/2410359\">What is the strict aliasing rule?</a></p>\n<p><strong>Fails when buffers overlap</strong></p>\n<p>Without <code>restrict</code>, buffer may overlap and code does not well handle overlaps in both directions.</p>\n<p>Recommend to use <code>restrict</code> like <code>memcpy()</code>.</p>\n<pre><code>void *memcpy(void * restrict s1, const void * restrict s2, size_t n);\n</code></pre>\n<p><strong>CPU WORD size</strong></p>\n<p>"I know int will always be CPU WORD size" discounts 8-bits CPUs (common in embedded code). On those, an <code>int</code> is at least 16-bit, not 8-bit.</p>\n<p>The low-level copy size is typically related to the CPU word size, but much of this is implementation dependent.</p>\n<p>Usually <code>unsigned</code> is good or best, but one would need to profile the implementation to know for sure.</p>\n<p><strong>Minor: Unneeded code</strong></p>\n<p>Test of <code>left</code> not unneeded as later <code>while(left--)</code> does the job.</p>\n<pre><code>// if (left)\n</code></pre>\n<p><strong><code>NULL</code> Testing</strong></p>\n<p>Common to <em>not</em> test for null-ness. <code>memcpy()</code> is not require to do so, nor is it required to not test <code>NULL</code>. What should be done depends on overall coding goals, so it is up to you.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T08:27:58.860",
"Id": "506753",
"Score": "0",
"body": "The strict aliasing remark means that a library memcpy can never be compiled with standard compliant settings. The whole rule about effective type even points at memcpy, so that one can obviously not be applied to memcpy's internals."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T22:15:05.293",
"Id": "256646",
"ParentId": "256628",
"Score": "3"
}
},
{
"body": "<h1>Use <code>size_t</code> consistently</h1>\n<p>Since <code>num</code> is of type <code>size_t</code>, make sure you use this for all other sizes, counts and indices related to this.</p>\n<h1>Unnecessary <code>if(left)</code></h1>\n<p>It is not necessary to check for <code>left</code> being non-zero, the <code>while()</code> loop inside the <code>if</code>-block will perform that check as well.</p>\n<h1>Don't check for <code>NULL</code> pointers</h1>\n<p>I would avoid the checks for <code>NULL</code> pointers. It should be up to the caller to ensure valid parameters are passed to your function. If you are worried about this, I recommend using <code>assert()</code> statements instead:</p>\n<pre><code>void *copy(void *destination, const void *source, size_t num)\n{\n assert(destination != NULL);\n assert(source != NULL);\n ...\n}\n</code></pre>\n<p>This way, a proper error message will be printed in debug builds. In release builds (with <code>-DNDEBUG</code>), the <code>assert()</code> statements will not do anything. If a <code>NULL</code>-pointer is passed, the program will get a segmentation fault. That's arguably better than this function silently ignoring the problem, as that can lead to the program continuing to run with possibly worse consequences.</p>\n<h1>Unaligned addresses</h1>\n<p>Indeed you are not handling pointers that are not aligned to <code>int</code>'s requirements. This means that if you use this function on a CPU architecture that does not allow unaligned access, your program will probably crash with a bus error or something similar.</p>\n<h1>Word size</h1>\n<p>It's hard to say what the best way to copy a large block of memory is. On some CPUs, an <code>int</code> might be the perfect size, but on others it might not. Try using a <code>long</code> or even a <code>long long</code>, and measure the time it takes on your machine. Remember that on other machines the results might be different.</p>\n<p>On x86, using SSE or AVX registers might be even more efficient than using a regular integer, but some CPUs also have special instructions to handle copying large amounts of data, regardless of register size. However, if you want your code to be portable you probably shouldn't use these techniques.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T09:18:05.730",
"Id": "506762",
"Score": "0",
"body": "`long` or `long long` will make the code extremely slow on low-end embedded systems."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T11:26:53.827",
"Id": "506772",
"Score": "0",
"body": "@Lundin Why? The only reason I can think of is you have a register-starved CPU, and the compiler doesn't optimize the copy and spills to temporary storage unnecessarily. Otherwise, the compiler would have to generate multiple load instructions, but that's actually perfectly fine here, because basically that's just equivalent to a bit of loop unrolling."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T11:35:23.257",
"Id": "506773",
"Score": "1",
"body": "Because `long` is at least 32 bit and if used on a CPU with less than 32 bits data instructions, you'll get slow code. In case of 8-bit CPU, you will get _very_ slow code. And yes, those are typically \"register-starved\" in general, so you can end up using the stack as a go-between."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T19:14:31.490",
"Id": "506825",
"Score": "0",
"body": "I tried this on godbolt (see https://godbolt.org/z/qxcrT7). GCC generates quite efficient code for the MSP430 and Atmel processors, but those have lots of registers. However, the code generted for the MOS6502 by cc65 look terrible (https://godbolt.org/z/8EM5na), both for the `long int` and `char` version."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T07:30:35.040",
"Id": "506882",
"Score": "0",
"body": "The AVR code looks rather terrible too. Should look about as bad on PIC, HC08, STM8, 8051, Z80 and others. Most things called MSP430 are 16 bitters, so I'd expect those to fare much better."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T22:20:22.940",
"Id": "256647",
"ParentId": "256628",
"Score": "0"
}
},
{
"body": "<p>Unfortunately, this function is quite naively written to the point where you would be much better off with a plain byte-by-byte loop:</p>\n<pre><code>for(size_t i=0; i<size; i++)\n{\n src[i] = dst[i];\n}\n</code></pre>\n<p>Benchmark and disassemble! If you can't beat the above performance with your own version, then you shouldn't be writing your own version.</p>\n<ul>\n<li><p>As pointed out by other reviews, you have a major bug in the form of misaligned access at the beginning of the copy, you only seem to handle misalignment at the end.</p>\n</li>\n<li><p>There is also strict aliasing violations. In fact strict aliasing means that <code>memcpy</code> cannot be efficiently implemented in standard C - you must compile with something like <code>gcc -fno-strict-aliasing</code> or the compiler might go haywire. Many of the traditional embedded systems compiles don't abuse strict aliasing, but gcc has a history of doing so and it is getting increasingly popular.</p>\n</li>\n<li><p><code>restrict</code> qualifying the pointers will help fixing pointer aliasing hiccups and maybe optimize the code a tiny bit. This is standard lib memcpy:</p>\n<pre><code> void *memcpy(void * restrict s1,\n const void * restrict s2,\n size_t n);\n</code></pre>\n</li>\n<li><p>Rolling out your own <code>memcpy</code> probably means it should be <code>static inline</code> and placed in a header, or otherwise it will by definition always be much slower than standard lib one.</p>\n</li>\n<li><p>You need to minimize the amount of branches. The only branches that should exist in this function if any are the ones correcting for misaligned addresses in the beginning and the end of the data. Branches are very bad since they are likely the major bottlenecks here - if the CPU can't utilize data and instruction cache, then the whole algorithm is pointless since it is then almost certainly far worse than the previously mentioned for loop, at least on all high end CPUs. Even on mid- to low-end CPUs with no cache have instruction pipelining and might benefit from no branches.</p>\n<p>In particular the checks against NULL are just pointless bloat that shouldn't exist in a library function but get carried out by the caller, if at all needed.</p>\n</li>\n<li><p><code>unsigned int</code> is not guaranteed to be the fastest aligned type supported - it is true on 16 to 32 bit systems but not on 64 bit systems. The correct type to use in this case for maximum portability is <code>uint_fast16_t</code>. That one covers all systems with alignment requirements from 16 to 64 bit systems.</p>\n<p>However, 16 bit systems with alignment requirements are somewhat rare, I think a few oddball ones have it, but many 16 bitters don't, so consider if you actually need portability to those that do. Otherwise <code>uint_fast32_t</code> would work. Similarly, portability to 64 bitters might be irrelevant if you only target embedded systems.</p>\n<p><strong>IMPORTANT:</strong> Most 8 and 16 bit systems have no alignment requirements and there's no obvious benefit of doing 16 bit word-sized copies on 8 bit systems. On such systems, these kind of "aligned chunk" memcpy implementations are just slow bloat - a plain byte-by-byte <code>for</code> loop would be much faster there. If you mean to target such systems, you will have to roll out a completely different implementation.</p>\n</li>\n<li><p>Avoid <code>/</code> and <code>%</code> unless you have reason to believe that the compile can optimize them away. Division is very CPU-intense particularly on low-end systems. In this case you shouldn't need it, the "number of chunks" calculation isn't adding anything meaningful information for the algorithm. This is a typical case of "write code so that the programmer understands what's going on", which is normally a good thing, but not when writing library quality code. Instead simply check for the end address when iterating.</p>\n</li>\n<li><p><code>copy</code> is a bad function name since various library functions with that name have existed over the years.</p>\n</li>\n<li><p>Don't include library headers that you don't use.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T09:12:50.663",
"Id": "256675",
"ParentId": "256628",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T18:00:28.260",
"Id": "256628",
"Score": "1",
"Tags": [
"c",
"reinventing-the-wheel"
],
"Title": "c - memcopy for embedded system"
}
|
256628
|
<p>I am trying to create a dictionary with a file containing text based on a matched pattern. Lines containing key_str should become keys and subsequent lines not matching key_str should become values and get associated with keys in the dictionary. so i have below code working: But I need help and getting the</p>
<ol>
<li>best practices and design pattern in my case</li>
<li>Performance in case my file is in GB</li>
<li>Alternate/different approaches without using any modules but just raw logic. don't want to use collections for example. for using python module I can ask a different question but here I just want to get to raw logic approaches.</li>
</ol>
<p>File: <code>file2dict.result-soa1</code></p>
<pre><code>ml1
/var
/home
cpuml2
/var
/home
</code></pre>
<p>Output</p>
<pre><code>my_dict: {ml1: ['/var','/home'], cpuml2: ['/var','/home']}
</code></pre>
<p>Code:</p>
<pre><code>import os
homedir = os.environ.get('HOME')
key_str = "ml"
my_dict = {}
val_list = []
key = ''
with open(homedir + '/backup/file2dict.result-soa1') as file2dict:
for line in file2dict:
words = line.split()
for aWord in words:
if key_str in aWord:
if key:
my_dict[key] = val_list
val_list = []
key = aWord
else:
key = aWord
else:
val_list.append(aWord)
my_dict[key] = val_list
print(my_dict)
</code></pre>
|
[] |
[
{
"body": "<p>Your code is off to a good start, but here are some suggestions either\nfor modest improvements or ways to simplify and clarify things.</p>\n<p>The built-in <a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"nofollow noreferrer\">pathlib</a> library\nis often the easiest and most robust way to work with file paths.</p>\n<p>Scripts with hard-coded file paths tend to be inflexible. For example,\nto review your code I had to edit it right out of the gate, because\nmy computer lacks your directory structure. During your own development and\ndebugging of a script, you might not want to operate on the real\nfile every time (using a tiny replica is often easier). All of\nwhich is to say that you are better off using default paths with\nthe option of command-line overrides. This adjustment also positions\nyou well for the future: if the needs of a script increase, you\ncan easily add support for more command-line arguments or options.</p>\n<p>I would encourage you to embrace the time-tested best-practice of putting\nnearly all substantive code inside of function or class definitions. It's an\neasy change to make and the greater isolation tends to increase flexibility.\nFor example, in the suggested edits below, which still stick pretty closely to\nyour original code, the algorithmic complexity of parsing has been extracted\ninto a narrowly tailored function that knows nothing about the program's larger\nconcerns. It doesn't have to know about paths, file reading, etc. Instead, it\ntakes any iterable containing lines of relevant data. That makes it easier to debug\nand test, because you can call it separately with just a list of strings.</p>\n<p>The edits below also provide a short illustration of how even fairly brief\ncomments can add context and help the reader understand both purpose and the\ngeneral logic. Some of the comments are like organizational sign posts: for\nexample, "Setup" or "Parse". They make it easier to scan code visually to get\nyour bearings. Other comments can help a reader by explain the gist of the\nalgorithm intuitively (for example, the two comments in the inner loop). Notice\nthat the comments do not mimic the code; rather, they help to organize it and\nthrow additional light on it.</p>\n<p>At a minimum, I would encourage you to adopt consistent variable naming\nconventions. Sometimes you follow the practice of appending data-type suffixes\nto names; other times not. That's not a practice I've ever found valuable, but\nopinions differ. Naming variables, functions, and classes is difficult because\nthere are often competing priorities: clarity, brevity, ease of typing, ease of\nreading, need to compare/contrast similar things, and so forth. In the edits\nbelow, some of the names below are conventional. For example, unless I need to\nhave multiple files open at once, I always use <code>fh</code> for "file handle". Same\nthing for <code>args</code> in a <code>main()</code> function. Other names are fairly explicit and\nhuman-readable: <code>default</code>, <code>file_name</code>, <code>file_path</code>, <code>line</code>, and <code>word</code> are\nexamples in this bucket. And other names are less strong: for example, <code>data</code>\nand <code>vals</code>. In some contexts, a generic name is appropriate (for example, a\ngeneral-purpose function that performs a general operation on some input). In\nyour case, I suspect that more substantive names exist, but only you know them.</p>\n<pre><code>from sys import argv\nfrom pathlib import Path\n\ndef main(args):\n # Get file path to the input data file.\n default = 'backup/file2dict.result-soa1'\n file_name = args[0] if args else default\n file_path = Path.home() / file_name\n\n # Parse.\n with open(file_path) as fh:\n data = parse_data(fh)\n\n # Report.\n print(data)\n\ndef parse_data(lines):\n # Setup.\n data = {}\n vals = []\n key = None\n marker = 'ml'\n\n # Parse.\n for line in lines:\n for word in line.split():\n if marker in word:\n # Store current VALS; and setup new KEY and VALS.\n if key:\n data[key] = vals\n vals = []\n key = word\n else:\n # Or just store with current VALS.\n vals.append(word)\n\n # Wrap-up and return.\n data[key] = vals\n return data\n\nif __name__ == '__main__':\n main(argv[1:])\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T20:48:14.343",
"Id": "256639",
"ParentId": "256629",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T18:26:59.013",
"Id": "256629",
"Score": "1",
"Tags": [
"python",
"python-3.x"
],
"Title": "Forming a dynamic dictionary based on searched key and values pair using RAW logic and not modules of python"
}
|
256629
|
<p>I created a function <code>yes.seq</code> that takes two arguments, a pattern <code>pat</code> and data <code>dat</code>, the function looks for the presence of a pattern in the data and in the same sequence.</p>
<p>For example:</p>
<pre><code>dat <- letters[1:10]
dat
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"
pat <- c('a',"c","g")
yes.seq(pat = pat,dat = dat)
[1] TRUE
</code></pre>
<p>because this sequence is in the pattern and in the same order.</p>
<p><code>"a"</code> "b" <code>"c"</code> "d" "e" "f" <code>"g"</code> "h" "i" "j"</p>
<p>If, for example, we reverse the pattern, then we get FALSE:</p>
<pre><code>yes.seq(pat = pat,dat = **rev(dat)** )
[1] FALSE
</code></pre>
<p>Here is my function:</p>
<pre><code>yes.seq <- function(pat , dat){
lv <- rep(F,length(pat))
k <- 1
for(i in 1:length(dat)){
if(dat[i] == pat[k])
{
lv[k] <- TRUE
k <- k+1
}
if(k==length(pat)+1) break
}
return( all(lv) )
}
</code></pre>
<p>I am not satisfied with the speed of this function. Can you help me with that?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T08:31:42.620",
"Id": "506754",
"Score": "0",
"body": "can you add example data on which the function doesn't perform well?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-28T23:08:02.910",
"Id": "510277",
"Score": "0",
"body": "Cross-posted on SO: [Match all elements of a pattern with a vector and in the same order](https://stackoverflow.com/questions/66446800/match-all-elements-of-a-pattern-with-a-vector-and-in-the-same-order). Please read [Is it OK to cross post here and in SO?](https://codereview.meta.stackexchange.com/questions/10498/is-it-ok-to-cross-post-here-and-in-so) \"No, it's not ok. Yes, it would be bad manners.\""
}
] |
[
{
"body": "<p>Here is a vectorized version:</p>\n<pre><code>yes.seq <- function(dat, pat) {\n paste(dat[dat %in% pat], collapse = "") == paste(pat, collapse = "")\n}\n\nyes.seq(dat, pat)\n# [1] TRUE\nyes.seq(dat, rev(pat))\n# [1] FALSE\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T22:22:35.573",
"Id": "256699",
"ParentId": "256631",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "256699",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T19:06:50.363",
"Id": "256631",
"Score": "0",
"Tags": [
"performance",
"r"
],
"Title": "Speed up a function that checks for a sequence"
}
|
256631
|
<p>I have been building a weather app that changes the background colour depending on the weather temperature and description.</p>
<p>This is the code I have to get it to work.</p>
<pre><code>const body = document.querySelector('body');
const colorList = [
{weather: 'Clear', color1: '#7AE7C7', color2: '#72C1E1'},
{weather: 'Clouds', color1: '#F981BB', color2: '#7F7E84'},
{weather: 'Drizzle', color1: '#b2c9c8', color2: '#698b8b'},
{weather: 'Fog', color1: '#C5B2A6', color2: '#7F7E84'},
{weather: 'Rain', color1: '#504AC4', color2: '#59AED1'},
{weather: 'Snow', color1: '#bfc9cf', color2: '#77BDE0'},
{weather: 'Thunderstorm', color1: '#314F71', color2: '#4A4176'},
{weather: 'Tornado', color1: '#939393', color2: '#e47977c5'}
]
const colorList2 = [
{color1: '#C94926', color2: '#BB9F34'},
{color1: '#89a1dd', color2: '#E4E5E7' }
]
if(weather.list[0].main.temp < 5 && weather.list[0].weather[0].main == 'Clear') {
body.style.backgroundImage = `linear-gradient(to bottom right,
${colorList2[1].color1}, ${colorList2[1].color2})`;
} else if(weather.list[0].main.temp > 15 && weather.list[0].weather[0].main == 'Clear'){
body.style.backgroundImage = `linear-gradient(to bottom right,
${colorList2[0].color1}, ${colorList2[0].color2})`;
} else {
colorList.forEach(color => {
if(color.weather == weather.list[0].weather[0].main) {
body.style.backgroundImage = `linear-gradient(to bottom right,
${color.color1}, ${color.color2})`;
}
</code></pre>
<p>Is there a more efficient way of doing the same thing? Are forEach loops overkills? Should I use if else statements? Should I be doing it at all in JavaScript?</p>
<p>Many thanks in advance.</p>
|
[] |
[
{
"body": "<p>First, your weather color list is unique by <code>weather</code> key, and you're querying the color based on it. I'd suggest turning this into an object of colors keyed by weather condition. This way, it's easier to locate the colors by condition than using a loop. You also gain one extra advantage: you can add your special cases of Clear in the same object, just keyed with a unique key value.</p>\n<p>Next, you'll want to assign those properties into variables. Long property accesses are hard to read.</p>\n<p>Now you'll want to split your logic. In your code, you're mixing color selection logic with background setting logic in a conditional. It's always important to figure out what thing is actually conditional from what can be extracted off of it. In this case, only <code>color1</code> and <code>color2</code> are conditional, not the setting of the background.</p>\n<p>Here's how I'd do it.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const colorsByCondition = {\n Clear: {\n color1: '#7AE7C7',\n color2: '#72C1E1'\n },\n // Special forms of Clear\n Clear5: {\n color1: '#89a1dd',\n color2: '#E4E5E7'\n },\n Clear15: {\n color1: '#C94926',\n color2: '#BB9F34'\n },\n // Other conditions\n Clouds: {\n color1: '#F981BB',\n color2: '#7F7E84'\n },\n // and so on...\n}\n\n// Assign to variables\n// const weather = weather.list[0]\n// const temp = weather.main.temp\n// const conditions = weather.weather[0].main\n\n// Assuming these values represent our weather\nconst temp = 6\nconst conditions = 'Clear'\n\n// Find the right colors\nconst { color1, color2 } = temp < 5 && conditions == 'Clear'\n ? colorsByCondition.Clear5\n : temp > 15 && conditions == 'Clear'\n ? colorsByCondition.Clear15\n : colorsByCondition[conditions]\n\n// Apply to the body\ndocument.body.style.backgroundImage = `linear-gradient(to bottom right, ${color1}, ${color2})`</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T17:58:15.813",
"Id": "506815",
"Score": "0",
"body": "Thank you, your help is very much appreciated!\n\nYes, I did feel like having an extra list titled 'colorList2' was a bit messy. Your way seems much better and cleaner."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T20:37:43.337",
"Id": "256638",
"ParentId": "256633",
"Score": "2"
}
},
{
"body": "<h2>Use CSS for Style</h2>\n<p>You are trying to add styles by JavaScript. Doing so makes your JavaScript mix logic and styles together. I would suggests split styles into CSS.</p>\n<p>For example, your Javascript:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>{weather: 'Clear', color1: '#7AE7C7', color2: '#72C1E1'},\n/* ... */\n{color1: '#C94926', color2: '#BB9F34'},\n/* ... */\nbody.style.backgroundImage = `linear-gradient(to bottom right, ${color.color1}, ${color.color2})`;\n</code></pre>\n<p>You may convert it to CSS like</p>\n<pre class=\"lang-css prettyprint-override\"><code>.weather-clear { --color-start: #7AE7C7; --color-end: #72C1E1; }\n/* ... */\n.weather-clear.weather-cold { --color-start: #C94926; --color-end: #BB9F34; }\n/* ... */\nbody { background-image: linear-gradient(to bottom right, var(--color-start), var(--color-end)); }\n</code></pre>\n<p>And you only need to set the className on body to make specified color applied.</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>const body = document.body;\nbody.classList.add('weather-' + weather.list[0].weather[0].main.toLowerCase());\nif (weather.list[0].main.temp < 5) body.classList.add('weather-cold');\nif (weather.list[0].main.temp > 15) body.classList.add('weather-hot');\n</code></pre>\n<p>Put all together:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"false\" 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 body = document.body;\nconst temp = 18, main = 'Clear';\nbody.classList.add('weather-' + main.toLowerCase());\nif (temp < 5) body.classList.add('weather-cold');\nif (temp > 15) body.classList.add('weather-hot');</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.weather-clear { --color-start: #7AE7C7; --color-end: #72C1E1; }\n.weather-clouds { --color-start: #F981BB; --color-end: #7F7E84; }\n.weather-drizzle { --color-start: #b2c9c8; --color-end: #698b8b; }\n.weather-fog { --color-start: #C5B2A6; --color-end: #7F7E84; }\n.weather-rain { --color-start: #504AC4; --color-end: #59AED1; }\n.weather-snow { --color-start: #bfc9cf; --color-end: #77BDE0; }\n.weather-thunderstorm { --color-start: #314F71; --color-end: #4A4176; }\n.weather-tornado { --color-start: #939393; --color-end: #e47977c5; }\n.weather-clear.weather-cold { --color-start: #C94926; --color-end: #BB9F34; }\n.weather-clear.weather-hot { --color-start: #89a1dd; --color-end: #E4E5E7; }\n\nbody { background-image: linear-gradient(to bottom right, var(--color-start), var(--color-end)); }\nbody { height: 100vh; box-sizing: border-box; margin: 0; }</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>[Note] If you are targeting to support older browsers (without CSS var support): Remove CSS variables, use <code>linear-gradient</code> directly in <code>.weather-clear</code> and so.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T15:58:07.983",
"Id": "506997",
"Score": "0",
"body": "Thank you.\n\nCould this be done using SASS? And if so, what would be the better option; CSS variables or SASS variables?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T03:08:27.687",
"Id": "256661",
"ParentId": "256633",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T19:39:38.050",
"Id": "256633",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Weather App - is my code efficient?"
}
|
256633
|
<p>I'm just learning the ropes to programming, so bear with me here. I wanted a simple command-line program to quickly convert decimal numbers into either binary or hexadecimal. This is what I came up with, but I know it can be improved.</p>
<pre><code>while True:
while True:
conv_type = input("Hexadecimal or Binary?: ").lower()
if "b" not in conv_type and "h" not in conv_type:
print("Invalid Input")
continue
else:
break
while True:
try:
dec_num = int(input("Decimal Number: "))
except ValueError:
print("Invalid Input")
continue
break
if "h" in conv_type:
print(" ", dec_num, "=", hex(dec_num), "in hexadecimal")
if "b" in conv_type:
print(" ", dec_num, "=", bin(dec_num).replace("0b", ""), "in binary")
</code></pre>
<p>How would you improve this? I feel a bit weird using three <code>while True</code> loops in the same program, but I couldn't think of a better solution on the fly. Any feedback is greatly appreciated!</p>
|
[] |
[
{
"body": "<p>User input validation is annoying, right? My instinct is to ask fewer\nquestions. Does the user really need to ask for hex or binary? For example, we\ncould just print both conversions. And if it's a command-line script, couldn't\nthe decimal number come directly from the command line? Or even a bunch of\ndecimal numbers and our script could convert them all.</p>\n<p>But if we retain your current approach, the repetitiveness of the validation\nsuggests the need to move code into functions and to create a single function\nto handle all <code>input()</code> calls. At a minimum, that function needs a user-prompt\nand a function (or callable) that will convert the value and raise an error if\nit's invalid. For example, to validate conversion type, we need to lowercase\nthe input and then make sure it contains a <code>b</code> or <code>h</code>. While we're at it, we\ncould simplify downstream logic by defining constants for <code>conv_type</code>.\nSubsequent code can use strict equality to drive logic (rather than\nlooser <code>in</code> checks). And in this case, the constant can also serve as a label\nwhen printing.</p>\n<p>A consolidated approach to getting user input allows you to address\nanother issue: how does the user quit the program? However you\ndecide to handle that, it's handy to be able to do it in one place\nrather than multiple.</p>\n<p>If you strip off the <code>0b</code> prefix for binary shouldn't you do the same for hex?\nIf so, that simplifies the logic, because we can extract the things that vary\ninto a data structure (<code>converters</code>) and then use that structure to drive the\nlogic. The result is that most of the "algorithm" in the <code>main()</code> function\nfades away and we end up with very little conditional branching. Instead, it\njust marches step by step, calling utility functions or accessing data\nstructures directly. Instead, the algorithmic complexity is delegated to\nsmaller and more narrowly focused utility functions that are easier to think\nabout in isolation.</p>\n<pre><code>import sys\n\nHEX = 'hexadecimal'\nBIN = 'binary'\n\ndef main(args):\n # Set up conversion functions and prefixes.\n converters = {\n HEX: (hex, '0x'),\n BIN: (bin, '0b'),\n }\n\n # Perform conversions.\n while True:\n # Get validated input. Since int() will raise if given\n # a bad input, we get that validation for free.\n conv_type = get_user_input('Hexadecimal or binary', is_conv_type)\n dec_num = get_user_input('Decimal number', int)\n\n # Convert.\n func, prefix = converters[conv_type]\n converted = func(dec_num).replace(prefix, '')\n\n # Report.\n print(f' {converted} = in {conv_type}')\n\ndef get_user_input(prompt, validate):\n while True:\n # Get input and provide a way for user to quit easily.\n reply = input(prompt + ': ').lower().strip()\n if not reply:\n sys.exit()\n\n # Return valid converted input or nag the user.\n try:\n return validate(reply)\n except ValueError as e:\n print(f'Invalid input: {reply}')\n\ndef is_conv_type(reply):\n # Takes user input. Returns HEX or BIN if valid.\n reply = reply.lower()\n for conv_type in (HEX, BIN):\n if conv_type[0] in reply:\n return conv_type\n raise ValueError()\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T21:46:54.720",
"Id": "256642",
"ParentId": "256634",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T19:51:50.160",
"Id": "256634",
"Score": "2",
"Tags": [
"python",
"python-3.x"
],
"Title": "command-line binary/hex conversion program in python"
}
|
256634
|
<p>This is a follow up for <a href="https://codereview.stackexchange.com/questions/256565/c-fast-fourier-transform">C++ Fast Fourier transform</a> . I did end up changing the algorithm slightly to reduce the memory usage.</p>
<pre><code>#include <vector>
#include <iostream>
#include <complex>
#include <cmath>
#include <algorithm>
#define N 1048576 // Problem size, must be a power of 2
#define PI 3.14159265358979323846
typedef std::vector<std::complex<double>> complexVec;
/*
Calculates the N'th roots of unity.
*/
complexVec rootsOfUnityCalculator() {
complexVec table;
table.resize(N);
for (size_t k = 0; k < N; k++) {
table[k] = std::complex<double>(std::cos(-2.0 * PI * k / N), std::sin(-2.0 * PI * k / N));
}
return table;
}
/*
Permutes an input vector of size length - a power of 2 - according
to the bit reversal permutation.
TESTED: SUCCESS
*/
void bitReversal(complexVec& input) {
std::vector<size_t> permutation;
permutation.resize(N);
permutation[0] = 0;
size_t k = 2;
// Calculating the permutation according to recursive relation
while (k <= N) {
for (size_t j = 0; j < k / 2; j++) {
permutation[j] *= 2; // permutation_k(j) = 2 * permutation_(k/2)(j)
permutation[j + k / 2] = permutation[j] + 1; // permutation_k(j + k/2) = 2 * permutation_(k/2)(j) + 1
}
k *= 2;
}
// Permute the input
for (size_t j = 0; j < N; j++) {
if (j < permutation[j]) {
std::swap(input[j], input[ permutation[j] ]);
}
}
}
void unorderedFFT(complexVec& input, const complexVec& table) {
size_t k = 2;
while (k <= N) {
for (size_t r = 0; r < N / k; r++) {
for (size_t j = 0; j < k / 2; j++) {
std::complex<double> plusMinus = input[r * k + j + k / 2] * table[N / k * j]; // omega_k^j = (omega_N^(N/k))^j = omega_N^(Nj/k)
input[r * k + j + k / 2] = input[r * k + j] - plusMinus;
input[r * k + j] += plusMinus;
}
}
k *= 2;
}
}
/*
Calculates the FFT
TESTED: SUCCESS
*/
void FFT(complexVec& input, const complexVec& table) {
bitReversal(input);
unorderedFFT(input, table);
}
// Prints array of N complex numbers
void printArray(complexVec& array) {
for (size_t k = 0; k < N - 1; k++) {
std::cout << array[k] << ", ";
}
std::cout << array[N - 1] << std::endl;
}
int main() {
complexVec input;
input.resize(N);
// Initialize the input to all 0, 1, ..., N
for (size_t k = 0; k < N; k++) {
input[k] = std::complex<double>(k, 0.0);
}
const complexVec table = rootsOfUnityCalculator();
FFT(input, table);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T21:35:35.003",
"Id": "506716",
"Score": "0",
"body": "@RainerP. That is probably it, thank you. Apparantly the stack is physically different from the heap and much smaller. I do not know yet whether switching to std::vector makes it better yet, I get some weird runtime error I am still trying to resolve."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T21:50:39.450",
"Id": "506719",
"Score": "0",
"body": "@RainerP. Good idea, I have done so."
}
] |
[
{
"body": "<h1>Profiling results</h1>\n<p>Using the profiler in Visual Studio, on my machine (Intel Haswell, 4770K) I get a breakdown roughly like this:</p>\n<ul>\n<li><code>unorderedFFT</code> 107ms</li>\n<li><code>rootsOfUnityCalculator</code> 21ms</li>\n<li><code>bitReversal</code> 17ms</li>\n</ul>\n<p>So let's improve all of those.</p>\n<h1>Roots of unity</h1>\n<p>The N'th roots of unity in the complex plane is a set of equally spaced points on the unit circle. Their coordinates can be calculated using sine and cosine, but an alternative is starting at <code>1 + 0i</code> and successively applying a small vector rotation to it (alternative view: the first non-trivial root is calculated, and then iteratively raised to the powers of 0, 1, 2 .. N-1). That way, only one pair of sin/cos is necessary (by the way, <code>std::polar</code> can be used to replace such a sin/cos pair with simpler code). A downside is that it may be less precise. It tends to be OK, but it will perturb the results slightly.</p>\n<p>For example, like this:</p>\n<pre><code>complexVec rootsOfUnityCalculator() {\n complexVec table;\n table.resize(N);\n\n auto step = std::polar(1.0, -2.0 * PI / N);\n std::complex<double> root = 1.0;\n for (std::size_t k = 0; k < N; k++) {\n table[k] = root;\n root *= step;\n }\n\n return table;\n}\n</code></pre>\n<p>With this, the time it takes has gone down to 7.5ms, so a factor of 2.3, which is certainly significant. This could be done even faster than that by unrolling the loop and removing the dependency between the copies of the loop body, for example if unrolling by 2 then there would be a separate <code>root1</code> and <code>root2</code> that are each multiplied by <code>stepSquared</code> so that their calculations are independent (improving instruction-level parallelism). Doing that reduced the time to 6ms.</p>\n<h1>Bit-reversal permutation</h1>\n<p>This is a well-studied permutation, because it is of practical interest, namely this exact application. Various more efficient techniques are known, including some variants of "increment a reversed integer". If an integer <code>i</code> and its reverse <code>rev</code> are both available, calculating the next values for both of them is efficiently possible.</p>\n<p>Of course <code>i</code> can just be incremented. <code>rev</code> needs some more work, but there is hope: the XOR of an integer and its successor is a "nice mask" consisting of a contiguous range of ones and a contiguous range of zeroes, with no "mess". This results from how, in the increment, the carry goes through the trailing ones, flipping each of them, then finally the first zero that is found is also flipped and the carry is "absorbed" by that zero - so the bits the flipped start at the least significant bit and form a contiguous range. That is relevant because a "nice mask" can be reversed by shifting it, and then XORing <code>rev</code> by it results in a "bit-reversed increment". A variant of that trick is using a trailing-zero-count instruction to find how long the contiguous range of flipped bits is, and then basing a mask directly on that. Let's go with that:</p>\n<pre><code>void bitReversal(complexVec& input) {\n std::size_t maskLen = std::countr_zero(unsigned(N));\n\n // Permute the input\n for (std::size_t j = 0, rev = 0; j < N; j++) {\n if (j < rev)\n std::swap(input[j], input[rev]);\n std::size_t maskLen = std::countr_zero(j + 1) + 1;\n rev ^= N - (N >> maskLen);\n }\n}\n</code></pre>\n<p>This uses the very new <code>std::countr_zero</code> from the <code><bit></code> header, a C++20 feature. There are other ways to write that too, for example <code>_tzcnt_u64</code>. <code>unsigned(N)</code> is a bit unfortunate, but required for <code>countr_zero</code>, which refuses to work on signed types. Preferably this would be avoided by making <code>N</code> a constant of type <code>size_t</code> instead of <code>#define</code>-ing it, which I recommend anyway.</p>\n<p>Using this trick, <code>bitReversal</code> has gone down from taking 17ms to 14ms (additionally, the memory used by the <code>permutation</code> vector is saved). It's a bit better, but nothing as great as improving the calculation of the roots of unity.</p>\n<p>This is not the best way to do it. The <code>if</code> corresponds to a badly-predicted branch, and the memory access pattern is semi-random. There are various useful papers about the technique I used here and further improvements, for example <a href=\"https://arxiv.org/pdf/1708.01873.pdf\" rel=\"nofollow noreferrer\">practically efficient methods for performing bit-reversed permutation in C++11 on the x86-64 architecture</a>.</p>\n<h1>The actual FFT</h1>\n<p>The real meat of the algorithm. Since you asked in the previous question not to bother with suggestions for different algorithms, I won't. However, I can still suggest a performance improvement: use <a href=\"https://en.wikipedia.org/wiki/SSE3\" rel=\"nofollow noreferrer\">SSE3</a>. SSE2 is actually sufficient, but SSE3 adds the <code>ADDSUBPD</code> instruction which is handy for complex multiplication:</p>\n<pre><code>__m128d multiplyComplex(__m128d A, __m128d B)\n{\n __m128d ARealReal = _mm_shuffle_pd(A, A, 0);\n __m128d AImagImag = _mm_shuffle_pd(A, A, 3);\n __m128d BRealImag = B;\n __m128d BImagReal = _mm_shuffle_pd(B, B, 1);\n return _mm_addsub_pd(_mm_mul_pd(ARealReal, BRealImag), _mm_mul_pd(AImagImag, BImagReal));\n}\n</code></pre>\n<p>Which could be used like this:</p>\n<pre><code>void unorderedFFT2(complexVec& input, const complexVec& table) {\n std::size_t k = 2;\n\n while (k <= N) {\n for (std::size_t r = 0; r < N / k; r++) {\n for (std::size_t j = 0; j < k / 2; j++) {\n __m128d input0 = _mm_loadu_pd((double*)&input[r * k + j + k / 2]);\n __m128d input1 = _mm_loadu_pd((double*)&input[r * k + j]);\n __m128d twiddle = _mm_loadu_pd((double*)&table[N / k * j]);\n __m128d product = multiplyComplex(input0, twiddle);\n _mm_storeu_pd((double*)&input[r * k + j + k / 2], _mm_sub_pd(input1, product));\n _mm_storeu_pd((double*)&input[r * k + j], _mm_add_pd(input1, product));\n }\n }\n\n k *= 2;\n }\n}\n</code></pre>\n<p>Casting those pointers looks scary, but it seems to be allowed according to the <a href=\"https://en.cppreference.com/w/cpp/numeric/complex\" rel=\"nofollow noreferrer\">paragraph about Array Oriented Access</a> of <code>std::complex</code>. <code>reinterpret_cast</code> could be used if you dislike C-style casts.</p>\n<p>Admittedly, using SSE is not very <a href=\"/questions/tagged/beginner\" class=\"post-tag\" title=\"show questions tagged 'beginner'\" rel=\"tag\">beginner</a>-friendly. But it does help significantly, the time of <code>unorderedFFT</code> went down to 70ms, the biggest improvement in absolute terms.</p>\n<p>Using intrinsic functions like this requires including the relevant header, for example <code>#include <tmmintrin.h></code> (or newer) in this case. Depending on the compiler, it may also require passing certain command line options (GCC and Clang need that, MSVC does not).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T14:56:04.110",
"Id": "506920",
"Score": "0",
"body": "Amazing answer! But could you please explain, why \" A downside is that it may be less precise.\" is likely to happen here? Shouldn't the rotation here be well-conditioned even within an iterative scheme? I'd guess, the usage of the built-in sin/cos routines might be questioned at all as soon as accuracy is very relevant too (see their common \"real life\" discrepancies for instance between 32 and 64bit environments...)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T15:29:51.363",
"Id": "506922",
"Score": "2",
"body": "@Secundi yes the accuracy isn't bad, but it's still not as precise as direct computation. Mainly, the angles go a bit off towards the end, in this example the angle of the last item is off for me by about 1 part in 1E8. For direct computation it's only off by about 1 part in 1E15"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T01:11:36.463",
"Id": "256655",
"ParentId": "256637",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "256655",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T20:37:24.497",
"Id": "256637",
"Score": "1",
"Tags": [
"c++",
"performance",
"beginner"
],
"Title": "C++ Fast Fourier transform attempt 2"
}
|
256637
|
<p><strong>Dice "Game"</strong></p>
<p>So, just started python a weeks time ago, so I'm looking for feedback/critique on things i can do to improve my code. I wrote a little user/pc dice rolling game. Any feedback at all is appreciated!</p>
<pre><code>
def dice(n: int) -> tuple:
"""
Simple function to roll 'n' number of dices.
Returns numbers of each roll and a total.
:param n: number of dices to roll
:return: dices_numbers, total
"""
numbers = []
total = 0
for dices in range(n):
number = random.randint(1, 6)
numbers.append(number)
total += number
dices_numbers = ", ".join(map(str, numbers))
return dices_numbers, total
def dice_check(user_total: int = 0, pc_total: int = 0) -> None:
"""
Function to check whether user or pc won dice roll.
:param user_total: user's total roll
:param pc_total: pc's total roll
:return: None
"""
if user_total > pc_total:
print("Congratulations! You won")
elif user_total < pc_total:
print("Sorry, BOT wins!")
else:
print("Tie!")
number_of_dices = ""
user_roll = ""
pc_roll = ""
while True:
number_of_dices = int(input("How many dices would you like to roll?"
" (0 to quit) >"))
if number_of_dices == 0:
break
else:
user_roll = dice(number_of_dices)
pc_roll = dice(number_of_dices)
print(f"You: Roll: {user_roll[0]}, a total of: {user_roll[1]}")
print(f"BOT: Roll: {pc_roll[0]}, a total of: {pc_roll[1]}")
dice_check(user_roll[1], pc_roll[1])
</code></pre>
|
[] |
[
{
"body": "<p>I'm pretty new as well, but I like to create an exception whenever I try to convert user input to an integer. Something like this-</p>\n<pre><code>while True:\n try:\n number_of_dices = int(input("How many dices would you like to roll?"\n " (0 to quit) >"))\n except ValueError:\n print("Please enter a number.")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T21:39:00.507",
"Id": "506717",
"Score": "0",
"body": "Will add that! thanks for the input :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T21:35:49.280",
"Id": "256641",
"ParentId": "256640",
"Score": "1"
}
},
{
"body": "<p>You're on the right path in putting most of your code inside of functions.\nI encourage you to go the full distance and make it your standard habit.\nThe code below does that by creating a <code>main()</code> function.</p>\n<p>Python has a built-in <code>sum()</code> function, so your <code>dice()</code> and <code>dice_check()</code>\nfunctions are probably doing more work than they need to. That's not a big\ndeal. Sometimes when you are learning, doing things the <em>hard way</em> can be\neducational. In any case, the edited code below will illustrate how <code>sum()</code>\ncould simplify the situation.</p>\n<p>The <code>dice()</code> function can be shortened substantially using a tuple\ncomprehension, if you want. You could also consider simplifying all downstream\ncode by bundling the dice roll and their sum into a small object. In this\nexample, something very simple like a <code>namedtuple</code> might be a good choice.\nNotice how this change simplifies the return type of <code>dice()</code> and also cleans\nup code that has to use its return value. Notice also that this decision has\nthe unanticipated benefit of allowing us to directly compare the <code>user</code> and\n<code>pc</code> dice rolls to determine the winner. This works because the <code>total</code>\nattribute is placed first within the <code>namedtuple</code>.</p>\n<p>You already have a good suggestion to add some validation to the user input. By\nshifting the collection of user input to its own function, you can keep\n<code>main()</code> focused on overall program orchestration. A general guideline is to\nkeep detailed computation out of a script's <code>main()</code>. That function is almost always\nthe hardest to test in more complex programs, so you should get into the habit\nof keeping it algorithmically simple. That thinking is behind the\n<code>get_result()</code> function: let some other piece of code determine the winner and\nhandle the grubby task of assembling whatever message should be printed.</p>\n<p>For brevity in this example, I dropped most of the printing (you should enhance\nas needed) and the docstrings (its a good idea to retain them in the real\nprogram).</p>\n<pre><code>import random\nimport sys\nfrom collections import namedtuple\n\nRoll = namedtuple('Roll', 'total roll')\n\ndef main(args):\n while True:\n # Get N of dice from user or quit.\n n = get_user_input()\n if not n:\n break\n # Roll dice.\n user = dice(n)\n pc = dice(n)\n # Report.\n msg = get_result(user, pc)\n print(msg)\n\ndef get_user_input() -> int:\n while True:\n prompt = 'How many dice would you like to roll? '\n reply = input(prompt).strip()\n try:\n return int(reply) if reply else 0\n except (ValueError, TypeError):\n pass\n\ndef dice(n: int) -> Roll:\n roll = tuple(random.randint(1, 6) for _ in range(n))\n return Roll(sum(roll), roll)\n\ndef get_result(user, pc) -> str:\n winner = (\n 'You' if user > pc else\n 'Bot' if pc > user else\n 'Tie'\n )\n return f'Winner: {winner} {user} {pc}'\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T23:02:00.033",
"Id": "256649",
"ParentId": "256640",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "256649",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T21:10:58.723",
"Id": "256640",
"Score": "4",
"Tags": [
"python"
],
"Title": "Python beginner looking for feedback on simple dice game"
}
|
256640
|
<p>I wanted to know if i have used abstraction and encapsulation effectively here, and if not where can i improve thank you. (follow up from my unworking previous version)</p>
<p>MAIN</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Voting_System
{
class Program
{
static void Main(string[] args)
{
// Puts each party into a list of Party and display Name + Votes
Console.WriteLine("Type the name of the file your data is in with the .txt extension : ");
string data = Console.ReadLine();
// Make list of party classes to hold all parties from data.txt file
List<Party> partys = FindData(data);
// Ask user for thresh hold and also calculate total votes
Console.WriteLine("What is the threshold for partys (%) (round number) ?");
int threshHold = Convert.ToInt32(Console.ReadLine());
// Calcutions for Dhon't method
var votesAndSeats = GetSumVotesAndSeats(data);
DisplayPercentageVotes(partys, threshHold, votesAndSeats.Item1);
CalculateDhondt(partys, votesAndSeats.Item2);
DisplayWinningParties(partys);
Console.ReadKey();
}
// takes input of the name of the data file and outputs the required data
private static List<Party> FindData(string exactpath)
{
// Store values in a list of string
List<string> file = File.ReadAllLines(exactpath).ToList();
List<Party> partys = new List<Party>();
foreach (string line in file.Skip(3))
{
string[] items = line.Split(',');
Party p = new Party(items[0], Convert.ToInt32(items[1]), items.Skip(2).ToArray());
partys.Add(p);
}
return partys;
}
// Print out all partys that have seats and there properties to console
private static void DisplayWinningParties(List<Party> partys)
{
foreach (Party p in partys)
{
if (p.SeatsAmount > 0)
{
Console.WriteLine(p);
}
}
}
// Find total votes for all parties and number of seats to be allocated
private static (int,int) GetSumVotesAndSeats(string exactpath)
{
List<string> file = File.ReadAllLines(exactpath).ToList();
int totalElectionVotes = Convert.ToInt32(file[2]);
int numOfSeatAllocation = Convert.ToInt32(file[1]);
return (totalElectionVotes, numOfSeatAllocation);
}
// Displays percent of votes for each party that meets the threshold
private static void DisplayPercentageVotes(List<Party> partys, int threshold, int totalvotes)
{
Console.WriteLine($"Parties that meet the {threshold}% threshold :");
foreach (Party p in partys.ToList())
{
if (p.PercentOfVotes(totalvotes) > threshold)
{
Console.WriteLine($"{p.Name} has {Math.Round(p.PercentOfVotes(totalvotes), 2)}" +
$" % of total votes.");
}
else
{
partys.Remove(p);
}
}
}
// Method to do the main calculations of the Dhon't method
private static void CalculateDhondt(List<Party> partys, int seatsCount)
{
// Find intial party with highest votes
Party biggestVote = partys.Aggregate((v1, v2) => v1.Votes > v2.Votes ? v1 : v2);
biggestVote.SeatsAmount += 1;
biggestVote.DivideParty();
// Keep looping through partys and applying dhond't method until all seats are taken
int totalSeatsCount = 0;
while (totalSeatsCount != seatsCount)
{
// If we havent reached desired seats count reset the total seats variable
totalSeatsCount = 0;
Party biggestVotes = partys.Aggregate((v1, v2) => v1.NewVotes > v2.NewVotes ? v1 : v2);
Console.WriteLine(biggestVotes);
biggestVotes.SeatsAmount += 1;
biggestVotes.DivideParty();
foreach (Party p in partys)
{
totalSeatsCount += p.SeatsAmount;
}
}
Console.WriteLine($"\n{seatsCount} seats allocated :");
}
}
}
</code></pre>
<p>PARTY CLASS</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Voting_System
{
class Party
{
// Fields
private string _name = "unknown";
private int _votes;
private string[] _seatsCodeValues;
private int _newVotes;
private int _seatsAmount;
// Properties
public string Name
{
get { return _name; }
private set { _name = value; }
}
public int Votes
{
get { return _votes; }
private set { _votes = value; }
}
public string[] SeatsCodeValues
{
get { return _seatsCodeValues; }
private set { _seatsCodeValues = value; }
}
public int NewVotes
{
get { return _newVotes; }
private set { _newVotes = value; }
}
public int SeatsAmount
{
get { return _seatsAmount; }
set { _seatsAmount = value; }
}
// Constructor for party class
public Party(string name, int votes, string[] seatsCodeValues)
{
Name = name;
Votes = votes;
NewVotes = votes;
SeatsCodeValues = seatsCodeValues;
}
// Returns percentage of votes for your party
public double PercentOfVotes(double totalVotes) => (Votes / totalVotes) * 100;
// When ever you print the object of this class return this
public override string ToString()
{
return $"Name: {Name}, Votes: {Votes}, {SeatsAmount} " +
$"Seats Values : {string.Join(",", SeatsCodeValues.Take(SeatsAmount))}";
}
// Applies Dhond't method of division
public void DivideParty()
{
NewVotes = Votes / (1 + SeatsAmount);
}
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T08:27:13.307",
"Id": "506752",
"Score": "1",
"body": "Please mention in your post that this question is a follow-up of [your previous one](https://codereview.stackexchange.com/questions/256309/c-code-for-dhondt-voting-method-uk-parliament)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T10:42:37.543",
"Id": "506768",
"Score": "0",
"body": "@PeterCsala i have now."
}
] |
[
{
"body": "<p>Quick remarks:</p>\n<ul>\n<li><p>Whenever I create a <code>Console</code> app, the first thing I do is add a <code>Runner</code> class with a <code>public void Execute()</code> method, and then call that from the <code>Main()</code> of the <code>Program</code> class. And then the whole logic is in that <code>Runner</code> class.</p>\n</li>\n<li><p>Your <code>Program</code> class is 100+ lines long, and contains various methods. Each of them does something fairly specific, but I'd actually move some of them to their own class (e;g. the ones that read the file data).</p>\n</li>\n<li><p>Follow the Microsoft guidelines WRT naming. For instance <code>exactpath</code> is a compound word, and thus should be <code>exactPath</code>. You also should not use non-alphanumeric characters, e.g. the underscore in <code>Voting_System</code>.</p>\n</li>\n<li><p>Use descriptive names. <code>exactPath</code> strikes me as odd: is there an <code>inexactPath</code>? <code>data</code> in <code>string data = Console.ReadLine();</code> is wrong on so many levels: it is too generic a name and doesn't describe what it is. <code>FindData</code> is too generic a method name.</p>\n</li>\n<li><p><code>Console.WriteLine("Type the name of the file your data is in with the .txt extension : ");</code> seems to require the user to type a file <em><strong>name</strong></em>, but it is clear you expect a <em><strong>path</strong></em>. That is a major difference.</p>\n</li>\n<li><p>Comments should be sparse and should tell me why, not what. For instance <code>// Store values in a list of string</code> doesn't tell me anything your code hasn't already told me. Same for <code>// Constructor for party class</code> and most other comments.</p>\n</li>\n<li><p>Use proper English. <code>partys</code> is wrong, it's <code>parties</code>.</p>\n</li>\n<li><p>Do not needlessly abbreviate. While the "p" in <code>foreach (Party p in partys)</code> isn't that bad and the context gives me enough information, it still would be better to just use the word <code>party</code>.</p>\n</li>\n<li><p><code>DisplayPercentageVotes</code> does more than what its name says: it also alters the contents of <code>partys</code>. Thus it should be two methods.</p>\n</li>\n<li><p>Why does <code>Party</code> have these "old style" getter/setters?</p>\n</li>\n<li><p>Many of your <code>foreach</code> loops could be replaced with LINQ calls.</p>\n</li>\n<li><p>You don't check the user input. You don't check whether the user-provided file path exists, you don't check whether the contents of the file are structured properly,...</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T14:57:24.163",
"Id": "506788",
"Score": "0",
"body": "I appreciate the help but alot of the stuff likemlinq and error handling wasnt expected by us,as this is our first project in our c# module"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T15:13:31.407",
"Id": "506791",
"Score": "0",
"body": "What do you mean by make a class for just the read file data? and when you say old style getters and setters should i do something like public string Name { get; private set; } instead? would this still meet encapsulation and abstraction pillars?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T16:31:20.313",
"Id": "506801",
"Score": "0",
"body": "An alternative way of doing encapsulation is https://dotnettutorials.net/lesson/encapsulation-csharp/ , but honestly, I haven't seen such code in \"real life\" in ages. If your teacher requires you to write it that way (with private fields etc.), you'll need to do it, but it isn't a coding style you see often these days (except for WPF and Unity etc.)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T17:04:20.910",
"Id": "506808",
"Score": "0",
"body": "Ok thanks,also can you explain why i would need to make a class for the file handling code segments?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T17:15:53.873",
"Id": "506809",
"Score": "0",
"body": "It's what I would do, for a simple reason: I don't like long class files where I need to scroll from method to method. Sometimes that is inevitable, but as much as possible I try to move specific logic to its own class file. Reading a file and converting its contents to a list of custom objects is something I'd move to its own class, for instance."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T11:24:19.743",
"Id": "256678",
"ParentId": "256643",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T21:50:12.760",
"Id": "256643",
"Score": "0",
"Tags": [
"c#",
"object-oriented"
],
"Title": "Making a Dhond't system in C# by reading from a data file"
}
|
256643
|
<p>I have written the following code to achieve the following:</p>
<ol>
<li>Regularly scrape all live matches on the betting site oddsportal.com</li>
<li>Pull odds data into data frame</li>
<li>Evaluate data frame for two odd providers (Asianodds, Pinnacle) and compare actual data against pre-defined patterns</li>
<li>Send a telegram message if a pattern was identified</li>
<li>Save scraped links in JSON file, so that they do not become scraped again</li>
</ol>
<p>My code still has the following issues, that I am hoping this review may help with:</p>
<ul>
<li>Performance: Currently it takes 1-2m per game to scrape and analyse it. How can this be achieved faster/more efficiently?</li>
<li>At times when there are many matches running simultaneously, the script cannot scrape all matches before a cronjob starts up the next script and they clash. How can I make selenium check if there is already an instance running and wait for that one to finish?</li>
</ul>
<p>'''</p>
<pre><code>#!/Library/Frameworks/Python.framework/Versions/3.8/bin/python3
import pandas as pd
import numpy as np
from bs4 import BeautifulSoup
from multiprocessing import Process
#from DbManager import DatabaseManager
import json
import re
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
import datetime
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support import expected_conditions as EC
import requests
import cProfile
o_u_types= [1.50,1.75,2.00,2.25,2.50,2.75,3.00,3.25,3.50]
raw_time=str(datetime.datetime.now())
current_date= raw_time[0:10]
bookmakers=['Asianodds','Pinnacle']
countries=['England','Japan','France','Germany', 'India', 'Chile', 'Italy','Turkey', 'Czech Republic', 'Spain', 'Colombia','Poland','Belgium','Romania','Paraguay',
'Portugal', 'Netherlands','Cyprus','Mexico','Brazil','Uruguay','Serbia','Slovenia','Slovakia','Sweden', 'Norway','USA','Estonia']
limited_league_countries=['England','Germany','Italy','Spain']
leagues=['National League','Championship','League One','2. Bundesliga','3. Liga','Regionalliga West','Regionalliga Sudwest','Serie A','Serie B','LaLiga','LaLiga2']
base_url='https://api.telegram.org/bot'
bot_token='xxxx'
chat_id='-xxxx'
global TYPE_ODDS
TYPE_ODDS = 'OPENING' # you can change to 'OPENING' if you want to collect opening odds, any other value will make the program collect CLOSING odds
link='https://www.oddsportal.com/inplay-odds/live-now/soccer/'
class Oddsportal:
def ReadScrapedLinks(self):
#with open("Modules/Config/scraped.json") as file:
with open("Config/scraped.json") as file:
data = json.load(file)
return data["scraped"]
def SaveScrapedMatch(self, link):
# with open("Modules/Config/scraped.json") as oldfile:
with open("Config/scraped.json") as oldfile:
data = json.load(oldfile)
data["scraped"].append(link)
# with open("Modules/Config/scraped.json", "w+") as newfile:
with open("Config/scraped.json", "w+") as newfile:
json.dump(data, newfile, indent=4)
def filter_list(self,links):
scraped_links=self.ReadScrapedLinks()
self.scraped_links=[]
for link in links:
if link in scraped_links:
continue
self.filtered_links.append(link)
def FindByCSSAndAttribute(self,mobject, css, attribute):
try:
return mobject.find_element_by_css_selector(css).get_attribute(attribute)
except:
return False
def WaitForObjects(self,type, string):
return WebDriverWait(self.driver, 5).until(EC.presence_of_all_elements_located((type, string)))
def fi(self,a):
try:
self.driver.find_element_by_xpath(a).text
except:
return False
def ffi(self,a):
if self.fi(a) != False :
return self.driver.find_element_by_xpath(a).text
def fffi(self,a):
if TYPE_ODDS == 'OPENING':
try:
return get_opening_odd(a)
except:
return self.ffi(a)
else:
return(self.ffi(a))
def fi2(self,a):
try:
self.driver.find_element_by_xpath(a).click()
except:
return False
def ffi2(self,a):
if self.fi2(a) != False :
fi2(a)
return(True)
else:
return(None)
def __init__(self):
mobile_emulation = {
"deviceMetrics": {"width": 360, "height": 640, "pixelRatio": 3.0},
"userAgent": "Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 5 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19"}
chrome_options = Options()
chrome_options.add_experimental_option(
"mobileEmulation", mobile_emulation)
# chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")
#Initialize chrome driver
self.driver = webdriver.Chrome(ChromeDriverManager().install())
executor_url = self.driver.command_executor._url
session_id = self.driver.session_id
self.driver.get(executor_url)
print (session_id)
print (executor_url)
res = requests.get(executor_url)
print(res)
def matchcollector(self, link):
self.driver.get(link)
live_matches=WebDriverWait(self.driver, 10).until(
EC.presence_of_all_elements_located((By.CSS_SELECTOR, '.minutes-anim')))
print(f'There are currently {len(live_matches)} matches live.')
#Collect all matches
all_matches = self.WaitForObjects(By.CLASS_NAME, "name.table-participant")
self.all_links=[]
for match_link in all_matches:
#Get match link
link = self.FindByCSSAndAttribute(match_link, 'a', 'href')
try:
in_play_addendum=link.split('/')[-2]
#Remove in play addendum
modified_link=link.replace(in_play_addendum,"")
self.all_links.append(modified_link)
except:
continue
scraped_links=self.ReadScrapedLinks()
self.filtered_links = []
#Remove already scraped links
for link in self.all_links:
if link in scraped_links:
continue
self.filtered_links.append(link)
print(f'Of all matches, {len(self.filtered_links)} have not yet been checked.')
def openmatch(self,match):
try:
self.driver.get(match)
time.sleep(1)
self.driver.maximize_window()
except:
return False
def getodds(self):
master_df= pd.DataFrame()
for link in self.filtered_links:
self.openmatch(link)
country= self.ffi('//*[@id="breadcrumb"]/a[3]')
if country in countries:
league= self.ffi('//*[@id="breadcrumb"]/a[4]')
if country in limited_league_countries:
if league not in leagues:
continue
else: pass
else: pass
match = self.ffi('//*[@id="col-content"]/h1')
game_message_string=f'Checking {match}'
game_method= '/sendMessage?chat_id={}&text="{}"'.format(chat_id,game_message_string)
game_telegram_url= base_url + bot_token + game_method
requests.get(game_telegram_url)
final_score = self.ffi('//*[@id="event-status"]')
date = self.ffi('//*[@id="col-content"]/p[1]') # Date and time
game_df= pd.DataFrame()
for i in o_u_types:
url_appendix="#over-under;2;{};0".format(i)
o_u_type= i
o_u_match_url= str(link)+str(url_appendix)
print(o_u_match_url)
self.loadoddpage(o_u_match_url)
for x in range(1,28):
L=[]
for j in range(1,15): # only first 10 bookmakers displayed
Book = self.ffi('//*[@id="odds-data-table"]/div[{}]/table/tbody/tr[{}]/td[1]/div/a[2]'.format(x,j)) # first bookmaker name
if Book in bookmakers:
#Fix difference for Pin in live
if Book=='Asianodds':
Over = self.fffi('//*[@id="odds-data-table"]/div[{}]/table/tbody/tr[{}]/td[3]/div'.format(x,j)) # first home odd
Under = self.fffi('//*[@id="odds-data-table"]/div[{}]/table/tbody/tr[{}]/td[4]/div'.format(x,j)) # first away odd
elif Book=='Pinnacle':
Over = self.fffi('//*[@id="odds-data-table"]/div[{}]/table/tbody/tr[{}]/td[3]/div'.format(x,j))
Under = self.fffi('//*[@id="odds-data-table"]/div[{}]/table/tbody/tr[{}]/td[4]/div'.format(x,j)) # first away odd
if Over==None:
Over = self.fffi('//*[@id="odds-data-table"]/div[{}]/table/tbody/tr[{}]/td[3]/a'.format(x,j)) # first home odd
else:
continue
if Under==None:
Under = self.fffi('//*[@id="odds-data-table"]/div[{}]/table/tbody/tr[{}]/td[4]/a'.format(x,j)) # first away odd
else:
continue
print(match, country, league, Book,Over,Under, date, final_score, link, '/ 500 ')
L = L + [(match, country, league, Book ,Over,Under, date, final_score, link)]
data_df = pd.DataFrame(L)
try:
data_df.columns = ['TeamsRaw', 'Country', 'League', 'Bookmaker', 'Over', 'Under', 'DateRaw' ,'ScoreRaw','Link']
except:
print('Function crashed, probable reason : no games scraped (empty season)')
##################### FINALLY WE CLEAN THE DATA AND SAVE IT ##########################
'''Now we simply need to split team names, transform date, split score'''
#Filter out Bookmakers
# (a) Split team names
data_df["Home_id"] = [re.split(' - ',y)[0] for y in data_df["TeamsRaw"]]
data_df["Away_id"] = [re.split(' - ',y)[1] for y in data_df["TeamsRaw"]]
# (b) Transform date
data_df["Date"] = [re.split(', ',y)[1] for y in data_df["DateRaw"]]
data_df["Over_{}".format(i)]=Over
data_df["Under_{}".format(i)]=Under
master_df=pd.concat([master_df,data_df])
game_df=pd.concat([game_df,data_df])
else:
print('Match not in a relevant country. Blacklisting it.')
self.SaveScrapedMatch(link)
continue
try:
#Setup Logic Operators
game_df.drop_duplicates(keep='first',inplace=True)
game_df = game_df.groupby(['TeamsRaw','Bookmaker'], as_index=False).first()
if len(game_df.index)==2:
for i in o_u_types:
try:
asian_over = game_df.at[0, f"Over_{i}"]
asian_under = game_df.at[0, f"Under_{i}"]
pin_over = game_df.at[1, f"Over_{i}"]
pin_under = game_df.at[1, f"Under_{i}"]
if asian_over > pin_over:
game_df[f"overdominant_{i}"] = "AsianDominant"
elif asian_over < pin_over:
game_df[f"overdominant_{i}"] = "PinDominant"
else:
game_df[f"overdominant_{i}"] = "Parity"
if asian_under > pin_under:
game_df[f"underdominant_{i}"] = "AsianDominant"
elif asian_under < pin_under:
game_df[f"underdominant_{i}"] = "PinDominant"
else:
game_df[f"underdominant_{i}"] = "Parity"
except:
game_df[f"overdominant_{i}"] ='n/a'
game_df[f"underdominant_{i}"] = "n/a"
continue
check_row= game_df.drop([1])
check_row_match= check_row.TeamsRaw.values
check_row_country= check_row.Country.values
check_row_league= check_row.League.values
print(check_row)
king_m5= check_row[(check_row['underdominant_2.25']=='AsianDominant') & (check_row['underdominant_2.5']=='AsianDominant')
& ((check_row['underdominant_1.5']=='Parity') | (check_row['underdominant_1.5']=='n/a'))
& ((check_row['underdominant_1.75']=='Parity') | (check_row['underdominant_1.75']=='n/a'))
& ((check_row['underdominant_2.0']=='Parity') | (check_row['underdominant_2.0']=='n/a'))
& ((check_row['underdominant_2.75']=='Parity') | (check_row['underdominant_2.75']=='n/a'))
& ((check_row['underdominant_3.0']=='Parity') | (check_row['underdominant_3.0']=='n/a'))
& ((check_row['underdominant_3.25']=='Parity') | (check_row['underdominant_3.25']=='n/a'))
& ((check_row['underdominant_3.5']=='Parity') | (check_row['underdominant_3.5']=='n/a'))
& ((check_row['overdominant_1.5']=='Parity') | (check_row['overdominant_1.5']=='n/a'))
& ((check_row['overdominant_1.75']=='Parity') | (check_row['overdominant_1.75']=='n/a'))
& ((check_row['overdominant_2.0']=='Parity') | (check_row['overdominant_2.0']=='n/a'))
& ((check_row['overdominant_2.25']=='Parity') | (check_row['overdominant_2.25']=='n/a'))
& ((check_row['overdominant_2.5']=='Parity') | (check_row['overdominant_2.5']=='n/a'))
& ((check_row['overdominant_2.75']=='Parity') | (check_row['overdominant_2.75']=='n/a'))
& ((check_row['overdominant_3.0']=='Parity') | (check_row['overdominant_3.0']=='n/a'))
& ((check_row['overdominant_3.25']=='Parity') | (check_row['overdominant_3.25']=='n/a'))
& ((check_row['overdominant_3.5']=='Parity') | (check_row['overdominant_3.5']=='n/a'))
]
if not king_m5.empty:
print(f'King M5 pattern found in {check_row_match}')
message_string=f' M5-U1,5 ⚠️ in {check_row_country}, {check_row_league}, {check_row_match}'
method= '/sendMessage?chat_id={}&text="{}"'.format(chat_id,message_string)
telegram_url= base_url + bot_token + method
print(telegram_url)
requests.get(telegram_url)
else:
print (f'Match {check_row_match} does not contain a king M5 pattern.')
else:
print('Match does not contain both bookmakers. Blacklisting it.')
self.SaveScrapedMatch(link)
continue
self.SaveScrapedMatch(link)
except:
self.SaveScrapedMatch(link)
continue
def main():
op=Oddsportal()
op.matchcollector(link)
op.checklink()
op.getodds()
if __name__== "__main__":
#p1 = Process(target=main)
#p1.start()
cProfile.run('main()', filename='report.txt', sort=-1)
</code></pre>
<p>'''</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T22:11:48.227",
"Id": "256645",
"Score": "1",
"Tags": [
"python",
"selenium"
],
"Title": "Selenium Webscraper for Odd data analyses"
}
|
256645
|
<p>The problem I'm solving is a more complex version of pairing up opening and closing brackets.<br />
Instead of matching only on <code>([{}])</code>, I additionally need to match arbitrary opening sequences of arbitrary length to closing sequences of arbitrary length, such as <code>'('</code> which is mapped to <code>')'</code>.<br />
While only the top-level matches should be returned, the matches should still account for the inner ones. This means that with a simple parenthesis mapping, <code>((f))</code> should match only on the first opening bracket and the final closing bracket.</p>
<p>Motivation:<br />
For parsing a grammar in a custom parser, I need to discern between bracket literals, which are surrounded by apostrophes and brackets on the grammar level, which are normal brackets. The goal is to return a list of all top-level matches that are found. A match is represented as a 4-tuple of the range that the opening and closing sequences span.<br />
For a motivating example, evaluating the expression <code>id '(' [FArgs] ')' ['::' FunType] '{' VarDecl* Stmt+ '}'</code> with a mapping of <code>{'(': ')', '[': ']', '{': '}', "'('": "')'", "'['": "']'", "'{'": "'}'"}</code> should yield the following list:</p>
<pre><code>[(3, 6, 15, 18), (19, 20, 32, 33), (34, 37, 53, 56)]
</code></pre>
<p>My starting point was <a href="https://codereview.stackexchange.com/questions/180567/checking-for-balanced-brackets-in-python">this code review on checking for balanced brackets in Python
</a>, which I adapted to suit the additional requirements:</p>
<ul>
<li>Match arbitrary opening and closing sequences of length >= 1</li>
<li>Collect tuples of the ranges at which the sequences are found.</li>
</ul>
<p>Armed with Python 3.9, this is my code:</p>
<pre><code>def get_top_level_matching_pairs(expression: str, mapping: dict[str, str]) \
-> list[tuple[int, int, int, int]]:
"""
Returns all top-level matches of opening sequences to closing sequences.
Each match is represented as a 4-tuple of the range that the opening and closing sequences span.
>>>get_top_level_matching_pairs("(a) op (b) cl", {'(': ')', 'op': 'cl'})
[(0, 1, 2, 3), (4, 6, 11, 13)]
"""
def head_starts_with_one_from(match_targets: Union[KeysView[str], ValuesView[str]]) -> Optional[str]:
# Check whether the expression, from index i, starts with one of the provided keys or values.
# Return the first match found, none otherwise.
return next(filter(lambda m: expression.startswith(m, i), match_targets), None)
res = []
queue = [] # functions as a stack to keep track of the opened pairs.
start_index = None
start_match = None
i = 0
while i < len(expression):
if open := head_starts_with_one_from(mapping.keys()):
if start_index is None:
start_index = i
start_match = open
queue.append(mapping[open]) # Store the closing counterpart for easy comparisons
i += len(open)
continue
if close := head_starts_with_one_from(mapping.values()):
try:
if (stack_head := queue.pop()) == close:
if not queue: # This closing token closes a top-level opening sequence, so add the result
res.append((start_index, start_index + len(start_match), i, i + len(close)))
start_index = None
start_match = None
i += len(close)
continue
# raise mismatched opening and closing characters.
except IndexError:
# raise closing sequence without an opening. (uses stack_head variable)
i += 1
return res
</code></pre>
<p>My questions:</p>
<ol>
<li>Should I put the preconditions in the docstring for the function or should I verify them in the code? The preconditions are: strings in the mapping are not empty and no mapping string can be a subset of another.</li>
<li>Is the <code>head_starts_with_one_from</code> nested function justified as a nested function? It allows for some neat <a href="https://docs.python.org/3/whatsnew/3.8.html#assignment-expressions" rel="nofollow noreferrer">walrus expressions</a> on the <code>if open</code> and <code>if close</code> lines.</li>
<li>Is there a better way to iterate over the expression, given that you need to match a varying range (here: 1 or 3 characters) of the expression at once and sometimes skip over part of it?</li>
</ol>
<p>Of course, additional comments are more than welcome.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T00:30:44.500",
"Id": "506724",
"Score": "1",
"body": "Maybe I haven't read carefully enough, but (1) the expected output shown in the docstring seems incorrect, since the input `expression` is only 10 characters long, and (2) what is the intended `mapping` for the \"motivated example\" in your discussion (I see only what I interpret as the input `expression` and expected output)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T08:21:31.760",
"Id": "506750",
"Score": "0",
"body": "@FMc I've addressed both your concerns in an edit, thanks for pointing them out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T19:31:03.397",
"Id": "506827",
"Score": "0",
"body": "I'm probably missing something but I'm still wondering about the example in the docstring. Shouldn't the expected return value include `(7, 8, 9, 10)` for the parens in this part of the text: `(b)`? Or do bracket pairs never nest inside of other pairs? If nesting is allowed, your code seems to be behaving incorrectly, because it does not find the 4-tuple just noted. Alternatively, if nesting isn't allowed, we don't need all of the complexity of the classic balanced-bracket algorithm; instead, won't a simple greedy approach work?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T20:04:30.823",
"Id": "506829",
"Score": "0",
"body": "@FMc I'm only interested in the top-level nodes, so nesting is indeed not allowed. A greedy algorithm could work if it could also detect when the brackets are unbalanced to raise errors, but I don't see how."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T23:36:08.237",
"Id": "506845",
"Score": "0",
"body": "You should edit the question text to clarify the nesting issue. If I understand the situation, your grammar allows nesting, but you only want to report to the end user the outermost balanced pairs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T23:47:07.753",
"Id": "506847",
"Score": "0",
"body": "@Fmc I've edited the post to explicitly state the goals wrt. nesting and provided another example."
}
] |
[
{
"body": "<ul>\n<li><p>In my opinion <code>head_starts_with_one_from</code> would be cleaner by using a generator expression:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def head_starts_with_one_from(match_targets: Iterable[str]) -> Optional[str]:\n return next(\n (\n m\n for m in match_targets\n if expression.startswith(m, i)\n ),\n None\n )\n</code></pre>\n<p>Or better yet, a plain old for loop.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def head_starts_with_one_from(match_targets: Iterable[str]) -> Optional[str]:\n for m in match_targets:\n if expression.startswith(m, i):\n return m\n return None\n</code></pre>\n</li>\n<li><p>Because you aren't storing <code>start_index</code> in <code>queue</code> your code can't work with nested brackets. We've now got rid of the need for <code>start_index</code>. You didn't really need <code>start_match</code> see next bullet point.</p>\n<pre class=\"lang-py prettyprint-override\"><code>queue.append((i, mapping[open]))\n</code></pre>\n</li>\n<li><p>You never use <code>stack_head</code>, so you don't need to use the walrus operator there.</p>\n</li>\n<li><p>You can use <code>elif</code> and <code>else</code> to get rid of the <code>continue</code>s.</p>\n</li>\n<li><p>You can use guard statements to prevent the arrow anti-pattern.</p>\n<pre class=\"lang-py prettyprint-override\"><code>if queue.pop() != close:\n # raise mismatched opening and closing characters.\n</code></pre>\n</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>def get_top_level_matching_pairs(\n expression: str,\n mapping: dict[str, str],\n) -> list[tuple[int, int, int, int]]:\n def head_starts_with_one_from(match_targets: Iterable[str]) -> Optional[str]:\n for m in match_targets:\n if expression.startswith(m, i):\n return m\n return None\n res = []\n queue = []\n i = 0\n while i < len(expression):\n if open := head_starts_with_one_from(mapping.keys()):\n queue.append((i, open))\n i += len(open)\n elif close := head_starts_with_one_from(mapping.values()):\n if not queue:\n # raise closing sequence without an opening.\n index, first_match = queue.pop()\n match = mapping[first_match]\n if match != close:\n # raise mismatched opening and closing characters.\n if not queue: # This closing token closes a top-level opening sequence, so add the result\n res.append((index, index + len(first_match), i, i + len(close)))\n i += len(close)\n else:\n i += 1\n return res\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T08:37:31.477",
"Id": "506756",
"Score": "0",
"body": "You seem to imply that a normal for loop is preferred over a generator expression, which itself is preferred over a filter expression. Why this ordering?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T08:42:22.570",
"Id": "506757",
"Score": "0",
"body": "`stack_head` was used in error reporting, I've now included in the original code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T08:51:21.367",
"Id": "506759",
"Score": "0",
"body": "The code `res.append((index, index + len(match), i, i + len(close)))` implies that `match` differs from `close`, which it never is. This makes the second tuple argument fail if the length of the opening sequence is not equal to the closing sequence, which is why `start_match` was originally saved. \nBreaking test case: `expression='op a c', mapping={'op': 'c'}`. Expected is `[(0, 2, 5, 6)]`, actual is `[(0, 1, 5, 6)]`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T02:02:17.867",
"Id": "506948",
"Score": "1",
"body": "@Iterniam People read familiar code faster than unfamiliar code. A simple for loop is super basic and is implement in lots of programming languages. So a simple is highly readable for most people. Additionally `filer` is semi-depricated as comprehensions and generator expressions do everything and more. So back to the familiar point, Python programmers are less familiar with `filter`. Whilst a fair argument is no-one will read the code, I'd suggest looking at the long-term affect of potentially getting a 'bad habit' and the potential grief."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T01:15:13.783",
"Id": "256656",
"ParentId": "256650",
"Score": "2"
}
},
{
"body": "<p>In response to question 1, in a REPL, <code>help(obj)</code> returns the docstring for the object. So the docstring should contain information for a developer using the object (class, function, module, method, ...).</p>\n<p>In response to your 3rd question, your method of scanning is fairly simple to understand and implement. However, it is not very efficient. It potentially checks each character in the expression against each opening and closing sequence. It may be "good enough" for your use case. But if there are a lot of sequences, or the expressions are long, or there are many expressions to check, another approach may be more efficient.</p>\n<p>The <code>re</code> module from the standard library can be used to simplify the code. There is some overhead to compile the regular expression, but a regular expression essentially checks for all the sequences in parallel, and <code>re</code> is a c-library so it runs at "c-speed". You should test to see which approach is faster for your use case.</p>\n<p>First, build a regular expression to match any of the opening or closing sequences.</p>\n<pre><code>left = '|'.join(re.escape(k) for k in mapping.keys())\nright = '|'.join(re.escape(k) for k in mapping.values())\n\npattern = re.compile(f"(?P<left>{left})|(?P<right>{right})")\n</code></pre>\n<p>The first line builds a regular expression that matches any of the opening (or left) sequences. Similarly, the second line builds one for any of the closing (or right) sequences. <code>re.escape()</code> is used to escape any characters in a sequence that would have a special meaning to the regex compiler. The f-string combines these pieces into a larger regular expression with named groups. Based on the motivating example, <code>pattern</code> would be a compiled regular expression for:</p>\n<pre><code>"(?P<left>\\\\(|\\\\[|\\\\{|'\\\\('|'\\\\['|'\\\\{')|(?P<right>\\\\)|\\\\]|\\\\}|'\\\\)'|'\\\\]'|'\\\\}')"\n</code></pre>\n<p>This matches any of the opening or left side sequences in the group named 'left' or any of the closing or right side sequences in the group named 'right'.</p>\n<p>The resulting compiled regular expression can be used to scan <code>expression</code> for opening or closing sequences.</p>\n<pre><code>stack = []\nresult = []\n\nfor match in pat.finditer(expression):\n if match.lastgroup == 'left':\n stack.append((match['left'], match.span()))\n\n else:\n if not stack:\n raise ValueError("Unmatched closing sequence")\n\n left, left_span = stack.pop()\n\n if match['right'] != mapping[left]:\n raise ValueError("Mismatched sequences")\n\n if not stack:\n result.append(left_span + match.span())\n \nif stack:\n raise ValueError("Unmatched opening sequence.")\n</code></pre>\n<p><code>match</code> is an <code>re.MatchObject</code>. <code>match.lastgroup</code> is the name of the last (or only) capture group that matched, which can be used to determine whether it matched an opening or closing sequence. Conveniently, <code>match.span()</code> returns a tuple of the indices of the matched sequence, so you don't need to keep track of it yourself.</p>\n<p>Presumably, the regular expression would be compiled once and then used repeatedly to scan many expressions. This could be done by defining a factory function that takes a mapping and returns a scanner:</p>\n<pre><code>def build_top_level_scanner(mapping):\n \n left = '|'.join(re.escape(k) for k in mapping.keys())\n right = '|'.join(re.escape(k) for k in mapping.values())\n\n pattern = re.compile(f"(?P<left>{left})|(?P<right>{right})")\n\n def scanner(expression):\n stack = []\n result = []\n \n for match in pat.finditer(expression):\n if match.lastgroup == 'left':\n stack.append((match['left'], match.span()))\n \n else:\n if not stack:\n raise ValueError("Unmatched closing sequence")\n \n left, left_span = stack.pop()\n \n if match['right'] != mapping[left]:\n raise ValueError("Mismatched sequences")\n \n if not stack:\n result.append(left_span + match.span())\n \n if stack:\n raise ValueError("Unmatched opening sequence.")\n\n return result\n\n return scanner\n</code></pre>\n<p>Used like so:</p>\n<pre><code>expression = """id '(' [FArgs] ')' ['::' FunType] '{' VarDecl* Stmt+ '}'"""\nmapping = {'(': ')', '[': ']', '{': '}', "'('": "')'", "'['": "']'", "'{'": "'}'"}\n\nscan = build_top_level_scanner(mapping)\nscan(expression)\n</code></pre>\n<p>which would return:</p>\n<pre><code>[(3, 6, 15, 18), (19, 20, 32, 33), (34, 37, 53, 56)]\n</code></pre>\n<p>It could also be done by defining a class:</p>\n<pre><code>class TopLevelScanner:\n\n def __init__(self, mapping):\n self.mapping = mapping\n \n left = '|'.join(re.escape(k) for k in mapping.keys())\n right = '|'.join(re.escape(k) for k in mapping.values())\n \n self.pattern = re.compile(f"(?P<left>{left})|(?P<right>{right})")\n\n\n def scan(self, expression):\n stack = []\n result = []\n \n for match in self.pattern.finditer(expression):\n if match.lastgroup == 'left':\n stack.append((match['left'], match.span()))\n \n else:\n if not stack:\n raise ValueError("Unmatched closing sequence")\n \n left, left_span = stack.pop()\n \n if match['right'] != mapping[left]:\n raise ValueError("Mismatched sequences")\n \n if not stack:\n result.append(left_span + match.span())\n \n if stack:\n raise ValueError("Unmatched opening sequence.")\n \n return result\n</code></pre>\n<p>Used like so:</p>\n<pre><code>expression = """id '(' [FArgs] ')' ['::' FunType] '{' VarDecl* Stmt+ '}'"""\nmapping = {'(': ')', '[': ']', '{': '}', "'('": "')'", "'['": "']'", "'{'": "'}'"}\n\nscanner = TopLevelScanner(mapping)\nscanner.scan(expression)\n</code></pre>\n<p>As an alternative to the <code>re</code> module, the third party PyAhoCorasick library could be used in a similar manner to the <code>re</code> module.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T14:49:21.790",
"Id": "506993",
"Score": "0",
"body": "I am in awe of this code. I disregarded regexes because they can't solve the problem on their own, but combining them with the delimiters algorithm makes so much sense. The code is very elegant. I ran timeit on your and @Peilonrayz's non-regex solution and your code is 10-15 times faster than the non-regex solution, regardless of the number of runs. Just for fun I also ran it while constantly recompiling the regex pattern, which only slows it down by a factor of 2."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T14:54:50.570",
"Id": "506994",
"Score": "0",
"body": "Two small nitpicks, `stack.pop()` causes an `IndexError` if there are more closing than opening sequences that would ideally be rethrown as a `ValueError` with a custom error message. A similar error could be raised if `stack` is not empty after going through the for loop."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T16:18:52.063",
"Id": "506999",
"Score": "0",
"body": "@Iterniam, I added checks for the two bugs you found."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T08:47:01.140",
"Id": "256752",
"ParentId": "256650",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "256752",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T23:58:48.247",
"Id": "256650",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"strings",
"balanced-delimiters"
],
"Title": "Retrieving top-level opening and closing sequences from a Python string"
}
|
256650
|
<p><code>dynamic_pointer_cast</code> is only implemented for <code>std::shared_ptr</code>, I need it for unique pointers.</p>
<p>The wrinkle is that dynamic_casting a pointer could fail (yield <code>nullptr</code>), what to do in that case? I decided that in that case i would like the original pointer to remain intact. So i have implemented the following:</p>
<pre><code>template< typename T, typename S >
inline std::unique_ptr<T> dynamic_pointer_cast(std::unique_ptr<S>&& ptr_)
{
T* const converted_ptr = dynamic_cast<T*>(ptr_.get());
if (!converted_ptr)
// cast failed, leave input untouched, return nullptr
return nullptr;
// cast succeeded, clear input, return casted ptr
ptr_.release();
return std::unique_ptr<T>(converted_ptr);
}
</code></pre>
<p>Testing code:</p>
<pre><code>#include <memory>
int main(int argc, char **argv)
{
std::unique_ptr<Base> basePtr = std::make_unique<Derived1>();
// this should fail, basePtr should remain non-empty, return should be empty
auto deriv2Ptr = dynamic_pointer_cast<Derived2>(std::move(basePtr));
// this should succeed, basePtr should become empty, return should be non-empty
auto deriv1Ptr = dynamic_pointer_cast<Derived1>(std::move(basePtr));
return 0;
}
</code></pre>
<p>Is this safe? Does the interface make sense? For the latter question: I decided to take an R-value ref so users have to write <code>std::move</code>, denoting pointer will be emptied. But then it may not if the cast fails... Normal ref is the other option, but then its less clear at the call site that the <code>unique_ptr</code> will likely be cleared.</p>
|
[] |
[
{
"body": "<ul>\n<li><p>Since it's a template function, it doesn't need to be marked <code>inline</code>.</p>\n</li>\n<li><p>It would be nice to handle custom deleters too. We can access the deleter with <code>ptr_.get_deleter()</code>.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T09:00:47.193",
"Id": "256673",
"ParentId": "256651",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "256673",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T00:07:04.963",
"Id": "256651",
"Score": "2",
"Tags": [
"c++11",
"pointers"
],
"Title": "dynamic_pointer_cast for std::unique_ptr"
}
|
256651
|
<p>I tackled a beginners' exercise: "asks the user for a number and then prints out a list of all the divisors of that number."</p>
<p>The workflow I established is: input an integer number, say <code>x</code>; add a variable which value is <code>x/2</code>, say <code>y</code>; declare a divisors list.</p>
<p>If <code>x</code> is greater than 4 iterate between <code>2</code> and <code>y+1</code>; if the remainder is zero append it the the divisors list.</p>
<p>If divisors list is empty or if the input number is smaller than 4 return: this is a primary number.<br />
else, return divisors list.</p>
<p>I ended up with the following solution. It does the job, but isn't good enough, as it has the following issues:</p>
<p>What is the python's input number limit? Currently, I have no limit which is wrong as it beyond the computational capacities of any computer.</p>
<p>I suspect my <code>else</code> statement isn't tidy enough. It can be shorter... but how?</p>
<p>If the number is lower than 4, the script returns twice the message "the number you entered is a primary number". I could fix it with an ad-hoc solution - but it should be solved through an algorithm not in a manual manner (...at least if I try to learn coding).</p>
<p>I ended up iterating in range of 2 and y+2 rather y+1 as I thought. I solved it manually but I don't understand why it isn't y+1.</p>
<pre><code>num = int(input("Please select a number between: "))
y = num/2
if not y==0:
y=int(y-0.5)
list_range = list(range(2,y+2))
divisors_list = []
if num < 4:
print("The number you entered is a primary number")
else:
for i in list_range:
if num%i ==0:
divisors_list.append(i)
if not divisors_list:
print("The number you entered is a primary number")
else:
print(divisors_list)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T00:58:37.683",
"Id": "506725",
"Score": "0",
"body": "If your code isn't working properly, you should post this in Stack Overflow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T01:42:26.593",
"Id": "506726",
"Score": "0",
"body": "@M-Chen-3 Thanks. My code works, I wish to make it better - I cannot tell if it relevant here. I actually posted on overflow before, comments advised me post it here... Can you please advise how/where I can better grasp the scope of each forum?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T01:44:58.497",
"Id": "506727",
"Score": "0",
"body": "@donbonbon I think you're alright. The code does correctly report divisors."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T01:57:58.740",
"Id": "506728",
"Score": "0",
"body": "You should make your question a bit clearer - from the phrasing it's hard to tell if you have a problem with your code or not."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T11:21:06.503",
"Id": "526677",
"Score": "0",
"body": "The english phrase is \"prime number\", not \"primary number\""
}
] |
[
{
"body": "<p>This program has 4 parts: (1) get raw user input; (2) validate the input and\nconvert it to its proper data type (<code>int</code> in this case), halting program if\ninvalid; (3) compute the divisors; and (4) report them to the user. However,\nyour current code has those things jumbled up. While collecting raw input you\ntry to convert it to <code>int</code> (which could fail) and then you turn to preparing\nsome variables needed to compute the divisors and then you do a little bit of\nvalidation. Here's your code with virtually no changes other than reordering\nthe existing lines so we can see the conceptual boundaries better. It's very\neasy to get confused when writing code, especially if the language is new to\nyou; a disciplined, orderly approach to keeping different things clearly\nseparated will help you reduce the confusion.</p>\n<pre><code>import sys\n\n# Get user input.\nnum = input("Please select a number between: ")\n\n# Convert and validate. Stop if invalid.\nnum = int(num)\nif num < 4:\n print("The number you entered is a primary number")\n sys.exit()\n\n# Compute divisors.\ny = num/2\nif not y==0:\n y=int(y-0.5)\nlist_range = list(range(2,y+2))\ndivisors_list = []\nfor i in list_range:\n if num%i ==0:\n divisors_list.append(i)\n\n# Report.\nif not divisors_list:\n print("The number you entered is a primary number")\nelse:\n print(divisors_list)\n</code></pre>\n<p>Regarding Python's number limit, don't worry about it. The only applicable\nlimit for a program like this is your patience. Just decide and\nvalidate.</p>\n<p>Perhaps there are different ways of defining a divisor, but my understanding is\nthat every integer <code>N</code> above 1 has at least two divisors -- namely <code>[1, N]</code>.\nIf you were to embrace that idea, your code would simplify because there would\nbe no need for special handling for prime numbers. The code below starts\nlooking for divisors at <code>1</code>; switch it to <code>2</code> to stay with your current approach.</p>\n<p>When computing divisors, each time you find one, you usually get a second for\nfree. For example, if the input is <code>24</code>, when you find <code>4</code> you also know that\n<code>6</code> is one too. Also, there's no need to check for divisors beyond the number's\nsquare root.</p>\n<p>Regarding your question about the <code>list_range</code> needing <code>y + 1</code> or <code>y + 2</code>, I\nsuspect that's because Python ranges have a non-inclusive endpoint: for\nexample, <code>range(1, 4)</code> is analogous to a list of <code>[1, 2, 3]</code>. The <code>divisor_rng</code>\nin the code below also has to use a <code>+1</code>.</p>\n<p>Here's an illustration of those comments.</p>\n<pre><code>import sys\nimport math\n\n# Some constants.\nMIN = 1\nMAX = 1000\n\n# Get user input.\nreply = input(f'Enter an integer in the range {MIN}-{MAX}: ')\n\n# Convert and validate.\ntry:\n num = int(reply)\n if num not in range(MIN, MAX + 1):\n raise ValueError()\nexcept ValueError:\n print(f'Invalid reply: {reply}')\n sys.exit()\n\n# Compute divisors.\ndivisors = []\ndivisor_rng = range(1, int(math.sqrt(num)) + 1)\nfor d in divisor_rng:\n if num % d == 0:\n # Store divisor.\n divisors.append(d)\n # Store its mate, unless d is the square root.\n d2 = num // d\n if d2 != d:\n divisors.append(num // d)\ndivisors.sort()\n\n# Prime check.\nis_prime = num > 1 and divisors == [1, num]\n\n# Report.\nprint(is_prime, divisors)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T11:57:54.040",
"Id": "506776",
"Score": "1",
"body": "thanks so much @FMc for the detailed explanations, remarks and tips! It a pleasure to learn. Your scripts answers all the needs. Your algorithm is of a higher level, which simplifies the workflow. I still go through this so I can carefully observe the details. I slightly modified the last print a Primary number statement only if True. # Report.\nprint(\"The input number is a primary number\" if is_prime==True else divisors). PS - I voted but as I have no credits, it doesn't count. Hope others will vote."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T01:39:54.300",
"Id": "256659",
"ParentId": "256652",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T00:15:30.500",
"Id": "256652",
"Score": "2",
"Tags": [
"python",
"beginner",
"python-3.x"
],
"Title": "Create a divisors list and identify primary numbers"
}
|
256652
|
<p>This is my first question on Code Review, so please let me know if I botched anything.</p>
<p>After working for quite a while on my CS50 calculator, it has finally reached the point where I am completely satisfied with how it works. However, since it is hosted on Google Sites, I'm slightly worried about security issues; I controversially chose to use <code>eval</code> since I'm too lazy to evaluate it myself. I'm worried this may lead to Javascript hacking.</p>
<p>The way my code works is it has a bunch of buttons to allow you to put in numbers, symbols, and predefined functions. Then, it adds different symbols to the actual displayed text and the evaluated text. This is so non-programmers can understand it better, e.g. <code>**</code> vs <code>^</code>. I also allow you to simply type in symbols, and I restrict it to buttonable ones. Finally, I evaluate what you've typed in using <code>eval</code>. You also have the ability to clear and delete.</p>
<p>There is a link to a working CS50 Calculator in my profile, and I'll also put a link here. You can try it out if my explanation was too vague: <a href="https://sites.google.com/view/cs50-calculator/home" rel="nofollow noreferrer">https://sites.google.com/view/cs50-calculator/home</a></p>
<p>And, of course, below is the full code of CS50 calculator (note that I'm not putting it in a snippet since you can access it on Google Sites anyways):</p>
<pre><code><!DOCTYPE html>
<!--Code help received from thingEvery in Stack Overflow: https://stackoverflow.com/a/63079750/13736952-->
<html lang="en">
<head>
<title>Calculator</title>
<script>
function sqrt(x)
{
return Math.sqrt(x);
}
function abs(x)
{
return Math.abs(x);
}
function sin(x)
{
return Math.sin(x);
}
function cos(x)
{
return Math.cos(x);
}
function tan(x)
{
return Math.tan(x);
}
function arcsin(x)
{
return Math.asin(x);
}
function arccos(x)
{
return Math.acos(x);
}
function arctan(x)
{
return Math.atan(x);
}
function ln(x)
{
return Math.log(x);
}
function log(x)
{
return Math.log10(x)
}
function cbrt(x)
{
return Math.cbrt(x);
}
function exp(x)
{
return Math.exp(x);
}
function root(index, radicand)
{
return radicand**(1/index);
}
function logrtm(base, argument)
{
return Math.log(argument)/Math.log(base);
}
function dec(x)
{
return parseFloat(x);
}
function int(x)
{
return Math.round(x);
}
function min(stuff)
{
let items = []
if (arguments.length > 1)
{
for (var i = 0; i < arguments.length; i++) items[i] = arguments[i];
}
else if (!isNaN(stuff))
{
items = [stuff]
}
else
{
items = stuff;
}
return Math.min(...items);
}
function max(stuff)
{
let items = []
if (arguments.length > 1)
{
for (var i = 0; i < arguments.length; i++) items[i] = arguments[i];
}
else if (!isNaN(stuff))
{
items = [stuff]
}
else
{
items = stuff;
}
return Math.max(...items);
}
function sum(stuff)
{
let items = []
if (arguments.length > 1)
{
for (var i = 0; i < arguments.length; i++) items[i] = arguments[i];
}
else if (!isNaN(stuff))
{
items = [stuff]
}
else
{
items = stuff;
}
let return_value = 0;
for (let i = 0; i < items.length; i++)
{
return_value += parseFloat(items[i]);
}
return return_value;
}
function mean(stuff)
{
let items = [];
if (arguments.length > 1)
{
for (var i = 0; i < arguments.length; i++) items[i] = arguments[i];
}
else if (!isNaN(stuff))
{
items = [stuff]
}
else
{
items = stuff;
}
return sum(items) / items.length;
}
function median(stuff)
{
let items = [];
if (arguments.length > 1)
{
for (var i = 0; i < arguments.length; i++) items[i] = arguments[i];
}
else if (!isNaN(stuff))
{
items = [stuff]
}
else
{
items = stuff;
}
items.sort(function(a, b){return Number(a) - Number(b);});
var half = Math.floor(items.length / 2);
if (half % 2 === 1)
{
return items[half];
}
else
{
return mean([items[half], items[half-1]]);
}
}
function mode(stuff)
{
let items = [];
if (arguments.length > 1)
{
for (var i = 0; i < arguments.length; i++) items[i] = arguments[i];
}
else if (!isNaN(stuff))
{
items = [stuff]
}
else
{
items = stuff;
}
var mapping = {};
for (let i = 0; i < items.length; i++)
{
if (!mapping[items[i]])
{
mapping[items[i]] = 0;
}
mapping[items[i]] += 1;
}
var max_val = max(Object.values(mapping));
var return_string = "";
for (let item in mapping)
{
if (mapping[item] === max_val)
{
if (return_string.length != 0)
{
return_string += " ";
}
return_string += item;
}
}
return return_string;
}
function range(stuff)
{
let items = [];
if (arguments.length > 1)
{
for (var i = 0; i < arguments.length; i++) items[i] = arguments[i];
}
else if (!isNaN(stuff))
{
items = [stuff]
}
else
{
items = stuff;
}
var max_val = max(items);
var min_val = min(items);
return max_val - min_val;
}
function factorial(x)
{
let return_num = 1;
for (let i = 1; i < x + 1; i++)
{
return_num *= i;
}
return return_num;
}
function combination(x, y)
{
return factorial(x) / (factorial(y) * factorial(x - y));
}
function random(low, high)
{
let return_number = Math.random() * (high - low) + low;
return return_number;
}
function quad(a, b, c)
{
if ((b**2 - 4*a*c) > 0)
{
let var1 = (-b + Math.sqrt(b**2 - 4*a*c)) / (2*a);
let var2 = (-b - Math.sqrt(b**2 - 4*a*c)) / (2*a);
let return_string = var1.toString() + " " + var2.toString();
return return_string;
}
else if ((b**2 - 4*a*c) == 0)
{
return (-b / 2*a);
}
else if ((b**2 - 4*a*c) < 0)
{
return "Undefined";
}
}
var x = "x";
function setx(stuff)
{
x = stuff;
return 0;
}
var list = ["Empty"];
function setlist()
{
list = [];
for (var i = 0; i < arguments.length; i++) {
if (typeof arguments[i] == "number") {
list.push(arguments[i]);
}
}
if (list.length == 0) {
list = ["Empty"];
}
return 0;
}
function addtolist()
{
if (list.length == 1 && "Empty".localeCompare(list[0]) == 0) {
list = [];
}
for (var i = 0; i < arguments.length; i++) {
if (typeof arguments[i] == "number") {
list.push(arguments[i]);
}
}
if (list.length == 0) {
list = ["Empty"];
}
return 0;
}
var func = null;
function makefunction(stuff)
{
func = stuff;
return 0;
}
function f(y)
{
if (func !== null)
return eval(func);
else
return "Undefined";
}
var pi = Math.PI;
var e = Math.E;
var percent = 0.01;
</script>
<style>
table
{
border: 3px solid black; border-collapse: collapse;
}
.center
{
margin: auto;
}
.num
{
color: black;
}
.oper
{
color: black;
}
.convert
{
color: black;
}
.operalt
{
color: black;
}
.numalt
{
color: black;
}
.convertalt
{
color: black;
}
.everything
{
margin: auto;
border: 5px ridge midnightblue;
background: gainsboro;
height: 360px;
width: 400px;
}
.buttonsdiv
{
text-align: center;
border-width: 3px;
border-style: ridge double;
height: 30px;
}
button
{
background: bisque;
border: 1px solid coral;
transition-duration: 0.5s;
cursor: pointer;
}
button:hover
{
background: yellow;
border: 1px solid goldenrod;
}
.buttoncenter {
margin: 4px auto;
display:block;
}
</style>
</head>
<body>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<div style="margin: auto; border: 5px ridge midnightblue; background: gainsboro; height: 400px; width: 400px;">
<div style="text-align: center; font-weight: bold; color: black;" id="expression">0</div>
<div class="buttonsdiv" style="border-color: blue; width: 300px; margin: 0 12%;">
<div class="buttoncenter">
<button class="num" id="1">1</button>
<button class="num" id="2">2</button>
<button class="num" id="3">3</button>
<button class="num" id="4">4</button>
<button class="num" id="5">5</button>
<button class="num" id="6">6</button>
<button class="num" id="7">7</button>
<button class="num" id="8">8</button>
<button class="num" id="9">9</button>
<button class="num" id="0">0</button>
</div>
</div>
<div class="buttonsdiv" style="border-color: black; width: 180px; margin: 0% 101%; background: gainsboro;">
<div class="buttoncenter">
<button id="enter">Enter</button>
<button id="clear">Clear</button>
<button id="delete">Delete</button>
</div>
</div>
<div class="buttonsdiv" style="border-color: green; width: 135px; margin: -9% 12%;">
<div class="buttoncenter">
<button class="oper" id="+">+</button>
<button class="oper" id="-">–</button>
<button class="operalt" id="*" name="×">×</button>
<button class="oper" id="/">÷</button>
</div>
</div>
<div class="buttonsdiv" style="border-color: darkblue; width: 159px; margin: 0 47.3%;">
<div class="buttoncenter">
<button class="operalt" id="**2" name="²">x²</button>
<button class="numalt" id="sqrt(" name="√(">√</button>
<button class="num" id="(">(</button>
<button class="num" id=")">)</button>
<button class="num" id="[">[</button>
<button class="num" id="]">]</button>
</div>
</div>
<div class="buttonsdiv" style="border-color: chartreuse; width: 150px; margin: 0 12%;">
<div class="buttoncenter">
<button class="num" id="sin(">sin</button>
<button class="num" id="cos(">cos</button>
<button class="num" id="tan(">tan</button>
</div>
</div>
<div class="buttonsdiv" style="border-color: cornflowerblue; width: 144px; margin: -9% 51%;">
<div class="buttoncenter">
<button class="operalt" id="**" name="^">^</button>
<button class="numalt" id="pi" name="π">π</button>
<button class="num" id="e">e</button>
<button class="oper" id=",">,</button>
<button class="oper" id=".">.</button>
</div>
</div>
<div class="buttonsdiv" style="border-color: darkgreen; width: 159px; margin: 9% 12%;">
<div class="buttoncenter">
<button class="numalt" id="arcsin(" name="sin⁻¹(">sin⁻¹</button>
<button class="numalt" id="arccos(" name="cos⁻¹(">cos⁻¹</button>
<button class="numalt" id="arctan(" name="tan⁻¹(">tan⁻¹</button>
</div>
</div>
<div class="buttonsdiv" style="border-color: aqua; width: 135px; margin: -18% 53.2%;">
<div class="buttoncenter">
<button class="num" id="ln(">ln</button>
<button class="num" id="exp(">exp</button>
<button class="num" id="log(">log</button>
</div>
</div>
<div class="buttonsdiv" style="border-color: mediumseagreen; width: 300px; margin: 18% 12%;">
<div class="buttoncenter">
<button class="num" id="root(">root(index,radicand)</button>
<button class="num" id="logrtm(">logrtm(base,argument)</button>
</div>
</div>
<div class="buttonsdiv" style="border-color: olive; width: 151px; margin: -18% 12%;">
<div class="buttoncenter">
<button class="operalt" id="*percent" name="%">%</button>
<button class="convert" id="dec(">=>dec</button>
<button class="convert" id="int(">=>int</button>
</div>
</div>
<div class="buttonsdiv" style="border-color: royalblue; width: 143px; margin: 9% 51.2%;">
<div class="buttoncenter">
<button class="operalt" id="%" name="mod">mod</button>
<button class="num" id="min(">min</button>
<button class="num" id="max(">max</button>
</div>
</div>
<div class="buttonsdiv" style="border-color: teal; width: 300px; margin: -9% 12%;">
<div class="buttoncenter">
<button class="num" id="mean(">mean</button>
<button class="num" id="median(">median</button>
<button class="num" id="mode(">mode</button>
<button class="num" id="range(">range</button>
<button class="num" id="sum(">sum</button>
</div>
</div>
<div class="buttonsdiv" style="border-color: springgreen; width: 154px; margin: 9% 12%;">
<div class="buttoncenter">
<button class="numalt" id="factorial(" name="!(">!</button>
<button class="num" id="combination(">combination(x,y)</button>
</div>
</div>
<div class="buttonsdiv" style="border-color: mediumblue; width: 140px; margin: -18% 52.1%;">
<div class="buttoncenter">
<button class="num" id="random(">random(low,high)</button>
</div>
</div>
<div class="buttonsdiv" style="border-color: forestgreen; width: 140px; margin: 18% 12%;">
<div class="buttoncenter">
<button class="num" id="quad(">quad(a,b,c)</button>
<button class="convert" id="setx(">setx</button>
</div>
</div>
<div class="buttonsdiv" style="border-color: dodgerblue; width: 154px; margin: -27% 48.5%;">
<div class="buttoncenter">
<button class="num" id="setlist(">setlist</button>
<button class="convert" id="addtolist(">addtolist</button>
</div>
</div>
<div class="buttonsdiv" style="border-color: lawngreen; width: 200px; margin: 27% 12%;">
<div class="buttoncenter">
<button class="num" id='makefunction("'>makefunction("f(y)")</button>
<button class="num" id="f(">f(y)</button>
</div>
</div>
<div class="buttonsdiv" style="border-color: darkslateblue; width: 94px; margin: -36% 63.5%;">
<div class="buttoncenter">
<button class="oper" id='"'>"</button>
<button class="num" id='func'>func</button>
</div>
</div>
</div>
<div style="visibility: hidden;"id="math">0</div>
<script>
let expression = document.querySelector("#expression");
let math = document.querySelector("#math");
let previous_exs = [];
let previous_maths = [];
function enter()
{
let result = eval(math.textContent.toLowerCase());
if (String(result).indexOf(" ") > 0)
{
expression.innerHTML = result;
}
if ((result % 1 != 0) && (!isNaN(result)))
{
expression.innerHTML = eval(result.toFixed(8));
}
else
{
expression.innerHTML = result;
}
if (Object.is(result, NaN) || result === null)
{
expression.innerHTML = "Undefined";
}
math.innerHTML = expression.textContent;
}
function clear()
{
expression.innerHTML = 0;
math.innerHTML = 0;
}
function del()
{
if ((previous_exs.length != 0) && (previous_maths.length != 0))
{
expression.innerHTML = previous_exs[previous_exs.length - 1];
math.innerHTML = previous_maths[previous_maths.length - 1];
previous_exs.pop();
previous_maths.pop();
}
else
{
expression.innerHTML = 0;
math.innerHTML = 0;
}
}
function num(item)
{
previous_exs.push(expression.textContent);
previous_maths.push(math.textContent);
if ((Number(expression.innerHTML) === 0) && (expression.textContent.length === 1)) {
expression.innerHTML = item;
math.innerHTML = item;
} else {
expression.innerHTML += item;
math.innerHTML += item;
}
}
function oper(item)
{
previous_exs.push(expression.textContent);
previous_maths.push(math.textContent);
expression.innerHTML += item;
math.innerHTML += item;
}
function convert(item)
{
previous_exs.push(expression.textContent);
previous_maths.push(math.textContent);
expression.innerHTML = item + expression.textContent + ")";
math.innerHTML = item + math.textContent + ")";
}
function operalt(item1, item2)
{
previous_exs.push(expression.textContent);
previous_maths.push(math.textContent);
expression.innerHTML += item1;
math.innerHTML += item2;
}
function numalt(item1, item2)
{
previous_exs.push(expression.textContent);
previous_maths.push(math.textContent);
if ((Number(expression.innerHTML) === 0) && (expression.textContent.length === 1)) {
expression.innerHTML = item1;
math.innerHTML = item2;
} else {
expression.innerHTML += item1;
math.innerHTML += item2;
}
}
function convertalt(item1, item2)
{
previous_exs.push(expression.textContent);
previous_maths.push(math.textContent);
expression.innerHTML = item1 + expression.textContent + ")";
math.innerHTML = item2 + math.textContent + ")";
}
const numbers = document.querySelectorAll(".num");
for (let i = 0; i < numbers.length; i++) {
numbers[i].addEventListener("click", function() {
num(numbers[i].id);
});
}
const operations = document.querySelectorAll(".oper");
for (let i = 0; i < operations.length; i++) {
operations[i].addEventListener("click", function() {
oper(operations[i].id);
});
}
const conversion = document.querySelectorAll(".convert");
for (let i = 0; i < conversion.length; i++) {
conversion[i].addEventListener("click", function () {
convert(conversion[i].id);
});
}
const operalts = document.querySelectorAll(".operalt");
for (let i = 0; i < operalts.length; i++) {
operalts[i].addEventListener("click", function () {
operalt(operalts[i].name, operalts[i].id);
});
}
const numalts = document.querySelectorAll(".numalt");
for (let i = 0; i < numalts.length; i++) {
numalts[i].addEventListener("click", function () {
numalt(numalts[i].name, numalts[i].id);
});
}
const convertalts = document.querySelectorAll(".convertalt");
for (let i = 0; i < convertalts.length; i++) {
convertalts[i].addEventListener("click", function () {
convertalt(convertalts[i].name, convertalts[i].id);
});
}
document.querySelector("#enter").onclick = enter;
document.querySelector("#clear").onclick = clear;
document.querySelector("#delete").onclick = del;
document.addEventListener('keydown', function(){
var key = event.key;
if ("0123456789[]()".includes(key) || (key.toUpperCase() != key.toLowerCase() && key.length == 1)) {
if (key != "Space")
{
num(key);
}
}
});
document.addEventListener('keydown', function(){
var key = event.key;
if ('-,.+/"'.includes(key)) {
oper(key);
}
});
document.addEventListener("keydown", function(){
var key = event.key;
var symbols = {"*":"×", "^":"**", "%":"*percent", "!":"factorial"};
if ("^%".includes(key)) {
operalt(key, symbols[key]);
}
else if ("*".includes(key)) {
operalt(symbols[key], key);
}
else if ("!".includes(key)) {
numalt("!(", "factorial(")
}
});
document.addEventListener("keydown", function() {
var key = event.key;
if (key == "Enter" || key == "=")
{
enter();
}
if (key == "Backspace")
{
del();
}
if (key == "Delete")
{
clear();
}
});
</script>
</body>
</html>
</code></pre>
<p>SIDENOTE: I tried asking a similar question in Stack Overflow, but it got downvoted. Hopefully it goes better here...</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T11:11:27.097",
"Id": "507132",
"Score": "0",
"body": "Can you explain what you mean with security? What are you trying to protect against?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T19:13:29.807",
"Id": "507180",
"Score": "1",
"body": "@MaartenBodewes Basically, can someone mess up my calculator by inputting Javascript code that gets evaluated?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T20:49:27.647",
"Id": "507189",
"Score": "1",
"body": "Alright. You might want to edit such info into the question as well. I might not be the most experienced security wizz w.r.t. JavaScript eval, so I'll pass."
}
] |
[
{
"body": "<p>As long as the evaluation code is only executed on the client side, you don't have to worry, because the user can just change your code if he wants to.\nAn example where it could be an insecurity is if the attacker can make another user evaluate his formula. If you implement a function to share the result of a calculation in a link (for example <code>cs50.com/calculator?input=hackTheMachine()</code>) and there is a security issue with your evaluation the one that clicked the link has a problem.</p>\n<p>If you would do the evaluation on your server, you would need more security checks because then the attacker can do things he might not be able to do otherwise.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-24T17:47:55.580",
"Id": "257627",
"ParentId": "256653",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "257627",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T00:18:34.607",
"Id": "256653",
"Score": "5",
"Tags": [
"javascript",
"html",
"security",
"math-expression-eval"
],
"Title": "Security of CS50 Calculator code (eval)"
}
|
256653
|
<p>What I have here is a relatively simple endpoint for a small site I'm making. Idea is to take:</p>
<ul>
<li>title</li>
<li>content</li>
<li>tags</li>
</ul>
<p>and create an entry in the database. It works properly.</p>
<p>I threw this together as something that should work and tried to make it clean (like with the error list that gets returned) but clearly I'm doing this all by hand. Are there best practices for writing these API-style endpoints that I'm not following?</p>
<p>I looked under the hood at a few sites (such as SO) and noticed they are using JSON as encoding for the response. That's why I used it too.</p>
<p>On the input validation front, is my system decently robust or is it too flimsy?</p>
<p>I also tried to make the code safe by catching any exceptions that might pop up. If there's something I've overlooked please let me know.</p>
<pre><code>@main.route('/createpost', methods=['POST'])
@login_required
def createpost():
resp = {
'success': False
}
err = []
u = current_user.id # 2458017363
title = request.values.get('title')
_tags = request.values.get('tags') # JSON btw
content = request.values.get('content')
# _attachments = request.files.getlist('file')
# attachments = []
# for f in _attachments:
# if f.filename.rsplit('.', 1)[1].lower() not in ALLOWED_EXTENSIONS:
# filepath = os.path.join(UPLOAD_DIR, secure_filename(f.filename))
# f.save(filepath)
# attachments.append(filepath)
# else:
# err.append('File ' + f.filename + "is not permitted!")
if not title or len(title) > 100:
err.append('Your title must exist and be less than 100 characters.')
try:
tags = json.loads(_tags)
if not tags or len(tags) > 3:
err.append('Choose between 1-3 tags so people know what your post is about!')
except Exception:
err.append('Choose between 1-3 tags so people know what your post is about!')
if not content or len(content) < 50:
err.append('Your content must be at least 50 characters.')
if err:
resp['error'] = err
print('err')
return Response(json.dumps(resp), mimetype='text/json')
# PROVIDED EVERYTHING IS CORRECT
while True:
try:
dbentry = Post(id=snowflake(),
author_id=u,
title=bleach.clean(str(title)),
tags=bleach.clean(str(_tags)),
content=bleach.clean(str(content)).encode(),
)
db.session.add(dbentry)
db.session.commit()
except IntegrityError:
continue
break
resp['success'] = True
return Response(json.dumps(resp), mimetype='text/json')
</code></pre>
<p>imports are as follows:</p>
<pre><code># main.py
import json
import os
import bleach
from sqlalchemy.exc import IntegrityError
from .models import Post # sqlalchemy model for posts
from flask import Blueprint, render_template, request, Response
from flask_login import login_required, current_user
from werkzeug.utils import secure_filename
from . import db
from .utils import snowflake # random number generator
# (hence why i have a while loop around the db entry creation since there is a
# miniscule chance it will give the same number again)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T07:49:46.830",
"Id": "506745",
"Score": "0",
"body": "I changed the title so that it describes what the code does per [site goals](/questions/how-to-ask): \"*State what your code does in your title, not your main concerns about it.*\". Please check that I haven't misrepresented your code, and correct it if I have."
}
] |
[
{
"body": "<p>Some quicky remarks:</p>\n<ul>\n<li>a well-behaved API should return specific <strong>HTTP codes</strong> depending on the outcome, that is:\n200 for success, or 201 for resource created. 204 is a possibility for an empty but successful response too but I would not advise using the full panoply available. Just be aware of what codes exist and when to use them.</li>\n<li>likewise, use 401/403 for permission issues or authentication errors but here you have the @login_required that should take care of that</li>\n<li>accordingly, an error should return a meaningful status code to the client - 400 would be a good candidate for an invalid request</li>\n<li>the bottom line, always return an appropriate status code, never return HTTP/200 if the request failed. API calls are routinely automated, and the client will rely on the status code returned by the server to determine if the call was successful or not.</li>\n<li>useless variable: <code>u = current_user.id # 2458017363</code>. You could just write: <code>author_id=current_user.id</code>, instead of <code>author_id=u</code>. u is not an intuitive variable name anyway</li>\n<li>I don't understand the logic of generating a random ID in your code, the database backend should generate an incremented record ID for you (simply update your data model). I don't see why you need a random value here...</li>\n<li>When you decide to handle certain exceptions like <code>except IntegrityError</code>, you can indeed decide to ignore them or hide them to the client but you should still log them for later review. IntegrityError suggests there is something wrong with your handling of incoming data. It should not happen if data is inspected and sanitized properly.</li>\n<li><code>except Exception</code> is too broad when all you're doing is <code>json.loads</code>. The error that you can expect here should be ValueError. Try submitting empty JSON and malformed JSON to verify.</li>\n<li>to sum I don't think you should have <code>resp['error']</code> and <code>resp['success']</code>, just use the same name in all cases eg: 'response'. It is the status code that will make the difference between success and failure. Whatever you do, the API should respond in a way that is consistent and predictable.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T22:32:45.347",
"Id": "506836",
"Score": "0",
"body": "Thank you! Great idea with the status codes. I will be sure to implement it. I also realized the random ID was not ideal (was using sqlite and I couldn't find such a feature except autoincrementing integers 1 ,2 ,3...) Will also fix the broad exception clauses. Really appreciate it!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T22:11:47.347",
"Id": "256697",
"ParentId": "256658",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "256697",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T01:34:36.377",
"Id": "256658",
"Score": "1",
"Tags": [
"python",
"json",
"api",
"flask"
],
"Title": "Populate database of web articles"
}
|
256658
|
<p>I've just finished writing a program to help track Pokemon across <a href="https://pokemon-soul-link.fandom.com/wiki/Pokemon_Soul_Link_Wiki" rel="nofollow noreferrer">Soul Links</a>. The goal of the program is to take in the names of the two Pokemon alongside the route that they were caught on. The Pokemon is then added to a table for the user to keep track of whether or not the Pokemon has died.</p>
<pre><code>import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Insets;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;
public class PokeTracker extends JFrame {
private static final long serialVersionUID = 1L;
private static final int WIDTH = 600;
private static final int HEIGHT = WIDTH / 2 + WIDTH / 6;
private static final String TITLE = "PokéTracker";
private String name1 = "Ash";
private String name2 = "Brock";
private int fontSize = 12;
private int columns = 14;
private int margin = fontSize / 2 + columns / 2;
private List<Pokemon> pokemon;
private DefaultTableModel model;
public PokeTracker() throws IOException {
this.pokemon = new ArrayList<Pokemon>();
this.model = new DefaultTableModel() {
private static final long serialVersionUID = 1L;
Class<?>[] types = new Class<?>[] { String.class, String.class, String.class };
boolean[] editable = new boolean[] { false, false, true };
@Override
public Class<?> getColumnClass(int columnIndex) {
return this.types[columnIndex];
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return this.editable[columnIndex];
}
};
JPanel panel = new JPanel(null);
JLabel trainerLabel1 = new JLabel(name1 + "'s Pokémon");
trainerLabel1.setBounds(margin, margin, 116, 30);
panel.add(trainerLabel1);
JTextField pokemonNameField1 = new HintTextField("name");
pokemonNameField1.setBounds(trainerLabel1.getX() + trainerLabel1.getWidth(), margin, columns * 10, columns * 2);
panel.add(pokemonNameField1);
JLabel trainerLabel2 = new JLabel(name2 + "'s Pokémon");
trainerLabel2.setBounds(margin, fontSize + margin * 2, 116, 30);
panel.add(trainerLabel2);
JTextField pokemonName2 = new HintTextField("name");
pokemonName2.setBounds(trainerLabel2.getX() + trainerLabel2.getWidth(), fontSize + margin * 2, columns * 10, columns * 2);
panel.add(pokemonName2);
JTextField pokemonRoute = new HintTextField("route");
pokemonRoute.setBounds(pokemonNameField1.getX() + pokemonNameField1.getWidth(), margin * 2, columns * 10, columns * 2);
panel.add(pokemonRoute);
JButton okButton = new JButton("OK");
okButton.setBounds(pokemonRoute.getX() + pokemonRoute.getWidth() + margin / 4, pokemonRoute.getY() + pokemonRoute.getHeight() / 4, 48, pokemonRoute.getHeight() / 2);
okButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addToTable(new Pokemon(pokemonNameField1.getText().isBlank() ? Pokemon.NAMELESS : name1 + "'s " + pokemonNameField1.getText(), pokemonRoute.getText().isBlank() ? Pokemon.ROUTELESS : pokemonRoute.getText()));
addToTable(new Pokemon(pokemonName2.getText().isBlank() ? Pokemon.NAMELESS : name2 + "'s " + pokemonName2.getText(), pokemonRoute.getText().isBlank() ? Pokemon.ROUTELESS : pokemonRoute.getText()));
pokemonNameField1.setText("");
pokemonName2.setText("");
pokemonRoute.setText("");
}
});
panel.add(okButton);
JTable t = new JTable(model);
t.setRowSelectionAllowed(true);
t.setBounds(margin - 1, pokemonName2.getY() + pokemonName2.getHeight() + margin, WIDTH - (margin * 2), HEIGHT - 100 - margin);
t.setDefaultRenderer(String.class, new CustomTableRenderer());
t.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_DELETE || e.getKeyCode() == KeyEvent.VK_BACK_SPACE) removeFromTable(t);
}
});
model.addColumn("Name");
model.addColumn("Route");
model.addColumn("Dead");
t.setRowHeight(16);
TableColumnModel columnModel = t.getColumnModel();
columnModel.getColumn(0).setPreferredWidth(200);
columnModel.getColumn(1).setPreferredWidth(100);
columnModel.getColumn(2).setPreferredWidth(5);
load("data.csv");
JScrollPane sp = new JScrollPane(t);
sp.setBounds(t.getX(), t.getY(), t.getWidth(), t.getHeight());
panel.add(sp);
JLabel icon = new JLabel(new ImageIcon(ImageIO.read(new File("ico.png")).getScaledInstance(64, 64, Image.SCALE_SMOOTH)));
int x = okButton.getX() + okButton.getWidth() + margin;
int y = margin / 2 + 2;
icon.setBounds(x, y, WIDTH - x - margin, HEIGHT - t.getHeight() - margin * 4 + 1);
panel.add(icon);
setAllFont(panel, new Font("Menlo", Font.PLAIN, fontSize));
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
save(t);
System.exit(0);
}
});
setTitle(TITLE);
Dimension size = new Dimension(WIDTH, HEIGHT);
getContentPane().setMinimumSize(size);
getContentPane().setMaximumSize(size);
getContentPane().setPreferredSize(size);
getContentPane().add(panel);
pack();
setLocationByPlatform(true);
setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
}
public void load(String f) {
try (BufferedReader br = Files.newBufferedReader(Paths.get(f), StandardCharsets.US_ASCII)) {
String line = br.readLine();
while (line != null) {
String[] attributes = line.split(",");
String name = attributes[0];
String route = attributes[1];
boolean dead = (attributes[2].contains("false") ? false : true);
addToTable(new Pokemon(name.substring(6, name.length()), route.substring(7, route.length()), dead));
line = br.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void save(JTable t) {
if (!isEmpty(t)) {
Vector<?> row = (Vector<?>) model.getDataVector().elementAt(1);
for (int i = 0; i < t.getRowCount(); i++) {
row = (Vector<?>) model.getDataVector().elementAt(i);
Pokemon p = pokemon.get(i);
/** synchronizing list of pokemon with table representation */
p.shoudlDie((row.get(2).toString().toLowerCase().equals("false") ? false : true));
}
}
try (BufferedWriter writer = new BufferedWriter(new FileWriter("data.csv"))) {
pokemon.forEach(pokemon -> {
try {
writer.append(pokemon.toString() + "\n");
} catch (IOException e) {
e.printStackTrace();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
void addToTable(Pokemon p) {
model.addRow(new String[] { p.getName(), p.getRoute(), (p.isDead()) ? "true" : "false" });
pokemon.add(p);
}
public static boolean isEmpty(JTable t) {
if (t != null && t.getModel() != null) return t.getModel().getRowCount() <= 0 ? true : false;
return false;
}
public void removeFromTable(JTable t) {
int[] rows = t.getSelectedRows();
if (t.getSelectedRow() >= 0) pokemon.remove(t.getSelectedRow());
for (int i = 0; i < rows.length; i++) model.removeRow(rows[i] - i);
}
public void setAllFont(Component c, Font f) {
c.setFont(f);
if (c instanceof Container) for (Component child : ((Container) c).getComponents()) {
setAllFont(child, (child instanceof JButton) ? new Font("Menlo", Font.PLAIN, 11) : f);
}
}
public static void main(String[] args) throws IOException {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) if ("Metal".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
} catch (Exception e) {
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
}
new PokeTracker();
}
class CustomTableRenderer extends DefaultTableCellRenderer {
private static final long serialVersionUID = 1L;
@Override
public Component getTableCellRendererComponent(JTable t, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Component component = super.getTableCellRendererComponent(t, value, isSelected, hasFocus, row, column);
String data = t.getValueAt(row, 0).toString();
if (data.contains(name1)) component.setForeground(Color.RED);
else if (data.contains(name2)) component.setForeground(Color.BLUE);
else component.setForeground(Color.BLACK);
return component;
}
}
/** https://stackoverflow.com/a/24571681 */
class HintTextField extends JTextField {
private static final long serialVersionUID = 1L;
public HintTextField(String hint) {
_hint = hint;
}
@Override
public void paint(Graphics g) {
super.paint(g);
if (getText().length() == 0) {
int h = getHeight();
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
Insets ins = getInsets();
FontMetrics fm = g.getFontMetrics();
int c0 = getBackground().getRGB();
int c1 = getForeground().getRGB();
int m = 0xfefefefe;
int c2 = ((c0 & m) >>> 1) + ((c1 & m) >>> 1);
g.setColor(new Color(c2, true));
g.drawString(_hint, ins.left, h / 2 + fm.getAscent() / 2 - 2);
}
}
private final String _hint;
}
class Pokemon {
public static final String NAMELESS = "???";
public static final String ROUTELESS = "???";
private String name;
private String route;
private boolean dead;
public Pokemon(String name, String route, boolean dead) {
this.name = name;
this.route = route;
this.dead = dead;
}
public Pokemon(String name, String route) {
this.name = name;
this.route = route;
this.dead = false;
}
public Pokemon(String name) {
this.name = name;
this.route = ROUTELESS;
this.dead = false;
}
public Pokemon() {
this.name = NAMELESS;
this.route = ROUTELESS;
this.dead = false;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRoute() {
return route;
}
public void setRoute(String route) {
this.route = route;
}
public boolean isDead() {
return dead;
}
public void shoudlDie(boolean dead) {
this.dead = dead;
}
@Override
public String toString() {
return "name: " + name + ",route: " + route + ",dead: " + dead + ",";
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T05:20:35.087",
"Id": "506956",
"Score": "0",
"body": "So, what is it that you want a reviewer to do with your code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T19:01:13.170",
"Id": "507014",
"Score": "0",
"body": "I guess tell me any malpractices or flaws in my code. I’m self taught so I’m not 100% sure that anything I’m doing is the “correct” or best way to do it."
}
] |
[
{
"body": "<p>There are too many input statements. This is a red flag; it usually means that the classes try and do to much.</p>\n<hr />\n<pre><code>private String name1 = "Ash";\n</code></pre>\n<p>First of all, when we start counting, we should stop and use a list. Second, you're mixing in the program logic with the GUI here.</p>\n<hr />\n<pre><code>private int columns = 14;\nprivate int margin = fontSize / 2 + columns / 2;\n</code></pre>\n<p>This probably means that we're talking about a <code>columnSize</code> here, not an amount of <code>columns</code>.</p>\n<hr />\n<pre><code>Class<?>[] types = new Class<?>[] { String.class, String.class, String.class };\nboolean[] editable = new boolean[] { false, false, true };\n</code></pre>\n<p>This is overly verbose, even for Java:</p>\n<pre><code>Class<?>[] types = { String.class, String.class, String.class };\nboolean[] editable = { false, false, true };\n</code></pre>\n<hr />\n<pre><code>JLabel trainerLabel1 = new JLabel(name1 + "'s Pokémon");\n</code></pre>\n<p>Those identifiers such as <code>trainerLabel1</code> can do without the <code>1</code> and <code>2</code> whatnot counting. Names should make sense by themselves, the <code>1</code> and <code>2</code> that are often automatically added should be removed or replaced by something more descriptive.</p>\n<hr />\n<pre><code>trainerLabel1.setBounds(margin, margin, 116, 30);\n</code></pre>\n<p>If possibly, try to design a GUI in such a way that explicit pixels / point counts are used as little as possible. This helps e.g. with scaling. In other words, please do use a <code>LayoutManager</code>, not <code>null</code>.</p>\n<pre><code>okButton.setBounds(pokemonRoute.getX() + pokemonRoute.getWidth() + margin / 4, pokemonRoute.getY() + pokemonRoute.getHeight() / 4, 48, pokemonRoute.getHeight() / 2);\n</code></pre>\n<p>Unfortunately the "why" behind all the calculations is not made clear. This would require a comment to help future developers (such as yourself, trust me on that one).</p>\n<hr />\n<pre><code>addToTable(new Pokemon(pokemonNameField1.getText().isBlank() ? Pokemon.NAMELESS : name1 + "'s " + pokemonNameField1.getText(), pokemonRoute.getText().isBlank() ? Pokemon.ROUTELESS : pokemonRoute.getText()));\naddToTable(new Pokemon(pokemonName2.getText().isBlank() ? Pokemon.NAMELESS : name2 + "'s " + pokemonName2.getText(), pokemonRoute.getText().isBlank() ? Pokemon.ROUTELESS : pokemonRoute.getText()));\n</code></pre>\n<p>These lines are overly complex and repetitive. That usually means that you have to refactor something into a function (or two).</p>\n<hr />\n<pre><code>JTable t = new JTable(model);\n</code></pre>\n<p>We're a bit into the class, and we've given up on descriptive names entirely. That's a shame, because <code>table</code> and <code>pokeTrackerTable</code> was still free.</p>\n<hr />\n<pre><code>load("data.csv");\n</code></pre>\n<p>Glad you used a method here. But it would be even nicer if you did not use hard coded file names, and if you do, at least make them a constant somewhere on the top of the code.</p>\n<hr />\n<pre><code>JScrollPane sp = new JScrollPane(t);\nsp.setBounds(t.getX(), t.getY(), t.getWidth(), t.getHeight());\npanel.add(sp);\n</code></pre>\n<p>Even small fractions of code like these can be refactored into a method (<code>addScrollPane</code>) which unclutters the code.</p>\n<hr />\n<pre><code> JLabel icon = new JLabel(new ImageIcon(ImageIO.read(new File("ico.png")).getScaledInstance(64, 64, Image.SCALE_SMOOTH)));\n</code></pre>\n<p>Again, you're doing too much in this line. Never nest IO operations. They are common places of failure, and you don't want to clutter the debugging part. Also, icons are generally created from <em>resources</em>, not from local files.</p>\n<hr />\n<pre><code>setTitle(TITLE);\n</code></pre>\n<p>Hmm, this feels a bit too much like an afterthought to me; what about:</p>\n<pre><code>super(TITLE);\n</code></pre>\n<p>as the very first line of code for this method?</p>\n<hr />\n<pre><code>boolean dead = (attributes[2].contains("false") ? false : true);\n</code></pre>\n<p>Oh, really? <code>"not false"</code> is <code>false</code> and <code>"False"</code> is <code>true</code>? Sometimes more strict definitions help a lot keeping things in line.</p>\n<hr />\n<pre><code>addToTable(new Pokemon(name.substring(6, name.length()), route.substring(7, route.length()), dead));\n</code></pre>\n<p>Now you're not just mixing program logic with the GUI, but I/O operations as well. Please keep these all separate. Load to a table in memory and display that.</p>\n<p>Furthermore, a bit of magic happens here: a substring from location 7 (what's that?) from an otherwise unvalidated string. That's just waiting for errors to happen.</p>\n<hr />\n<pre><code>e.printStackTrace();\n</code></pre>\n<p>No, no, no. You never keep running on an error. NEVER leave the printing of the stack trace in. If you need to handle errors later:</p>\n<pre><code>// TODO handle exception\nthrow new RuntimeException("Unhandled exception", e);\n</code></pre>\n<p>This will still print out the stacktrace...</p>\n<p>I have no clue why popular IDE's don't do this by default, but it sucks badly that they don't.</p>\n<hr />\n<pre><code>Vector<?> row = (Vector<?>) model.getDataVector().elementAt(1);\n</code></pre>\n<p>If you keep using values like <code>1</code>, <code>2</code> and <code>3</code> to mean something, you might need either constants or - even better - enumerations. And if those get too complex, you probably need full featured (data) classes.</p>\n<hr />\n<pre><code>p.shoudlDie((row.get(2).toString().toLowerCase().equals("false") ? false : true));\n</code></pre>\n<p>Question: what does <code>equals</code> return?</p>\n<hr />\n<pre><code>void addToTable(Pokemon p) {\n</code></pre>\n<p>In general there needs to be a good reason for the access modifier to be absent (package-private). Generally, methods such as these should be <code>private</code> as you would not expect them to be called by other classes (this is easier if the class just focuses on managing the GUI).</p>\n<hr />\n<pre><code>public static boolean isEmpty(JTable t) {\n</code></pre>\n<p>I got this far when I wondered where the table was stored. Finding out that it is simply a variable local to the constructor was a bit of a surprise. The good thing is that you don't need all the <code>null</code> checking in that case. Of course, that would mean making the method <code>private</code>.</p>\n<hr />\n<pre><code> if (t.getSelectedRow() >= 0) pokemon.remove(t.getSelectedRow());\n</code></pre>\n<p>That's weird, the <code>pokemon</code> is a field and the table isn't? I'd expect <code>remove(Pokemon pokemon)</code> to be a lot more intuitive.</p>\n<hr />\n<pre><code>public void setAllFont(Component c, Font f) {\n</code></pre>\n<p>Here you show that you are definitely capable of splitting up smaller methods, great.</p>\n<pre><code>for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) if ("Metal".equals(info.getName())) {\n</code></pre>\n<p>No, please use parentheses for <code>if</code> statements and put them on a separate line. I don't think it is a problem that <code>info</code> will ever be <code>null</code> or that it has a <code>null</code> name, so the rather stupid <code>"literal".equals(value)</code> construct is unnecessary.</p>\n<p>Generally, just use <code>value.equals("literal")</code> please, it makes for a much better reading experience. In the few cases that <code>value</code> can be <code>null</code>, handle them separately.</p>\n<hr />\n<pre><code>ex.printStackTrace();\n</code></pre>\n<p>Why? Just do nothing, otherwise this will remain and the user will get an unnecessary trace to handle (if setting the L&F fails).</p>\n<hr />\n<pre><code> if (data.contains(name1)) component.setForeground(Color.RED);\n</code></pre>\n<p><code>contains</code> is really unnecessary here. If it is just a name then you could also use a <code>switch</code> with a <code>String</code> nowadays.</p>\n<p>However, what about:</p>\n<pre><code>public enum Pokemon {\n ASH("Ash", Color.RED),\n BROCK("Brock", Color.BLUE),\n UNKNOWN("???", Color.BLACK);\n}\n</code></pre>\n<p>I'll leave creation of the fiels, private contructor and getters up to you.</p>\n<hr />\n<pre><code> /** https://stackoverflow.com/a/24571681 */\n</code></pre>\n<p>This is great, because links to previos documents are really necessary. However, I'd not put it in a JavaDoc without a further description (but I hope other comments are just stripped for this review).</p>\n<p>The class could be private though, or separated out because it is rather large. It probably should be <code>static</code> as I don't see it using any fields of the main class.</p>\n<hr />\n<pre><code> _hint = hint;\n</code></pre>\n<p>etc. Copying is fine, but if the code uses bad identifiers, then please correct them before you get swamped by e.g. a run of CheckStyle.</p>\n<hr />\n<pre><code> public void shoudlDie(boolean dead) {\n</code></pre>\n<p>Your Pokemon can actually be immutable, if not for the state. I'd use another method to keep the state, maybe a table or something. Because now you can resurrect Pokemon and have zombie-pokemons. That's called an "invalid state" and those should always be avoided.</p>\n<p>Actually, it seems like this is explicitly stated as game rule:</p>\n<blockquote>\n<p>If a pokemon dies, you cannot revive it.</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T12:55:46.723",
"Id": "507057",
"Score": "0",
"body": "A little hint: I often first create a textual interface for my game. That requires me to program the game logic separately from the GUI code. Then I can add the GUI code later. Of course, if I use console output in my game logic I still fail."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T12:51:52.763",
"Id": "256802",
"ParentId": "256664",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "256802",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T05:34:27.687",
"Id": "256664",
"Score": "3",
"Tags": [
"java",
"object-oriented",
"recursion",
"swing",
"pokemon"
],
"Title": "Pokemon Soul Link tracker"
}
|
256664
|
<p>This iterator is designed with one purpose in mind. If before you had an iterator where you could do</p>
<pre><code>int x = *it;
</code></pre>
<p>now you do</p>
<pre><code>int x = **make_wrap_iterator(it);
</code></pre>
<p>This is useful for example if you want to use a range-based <code>for</code> loop to produce iterators to each element rather than values. You could do</p>
<pre><code>std::vector<int> source = {1,2,3,4};
for(std::vector<int>::const_iterator it :
boost::make_iterator_range(
make_wrap_iterator(source.begin()),
make_wrap_iterator(source.end())
)
{
std::out << *it << std::endl;;
}
</code></pre>
<p>Try it on <a href="https://godbolt.org/z/ef4j3T" rel="nofollow noreferrer">Godbolt</a>.</p>
<p>The implementation for <code>WrapIterator</code> is:</p>
<pre><code>#include <iostream>
#include <vector>
#include <boost/iterator/iterator_facade.hpp>
#include <boost/range/iterator_range.hpp>
template <typename T>
struct WrapIterator : boost::iterator_facade
< WrapIterator<T> ,T ,typename T::iterator_category ,T >
{
WrapIterator(T ptr) : m_ptr(ptr) {}
T dereference() const { return m_ptr; }
void increment() { m_ptr++; }
void decrement() { m_ptr--; }
void advance(int n){ m_ptr+=n; }
typename T::difference_type distance_to
(WrapIterator<T> const & other) const
{
return other.m_ptr - m_ptr;
}
bool equal(WrapIterator<T> const & other) const {
return other.m_ptr == m_ptr;
}
private:
T m_ptr;
};
template <typename T>
WrapIterator<T> make_wrap_iterator(T it){return WrapIterator<T>(it);}
</code></pre>
<p>I have two questions.</p>
<ol>
<li><p><code>WrapIterator</code> is a terrible name. Is there a better name for this iterator? Boost already has a class called <a href="https://www.boost.org/doc/libs/1_75_0/libs/iterator/doc/html/iterator/specialized/indirect.html" rel="nofollow noreferrer"><code>indirect_iterator</code></a> which does the exact opposite of my iterator in that if you do '<code>*it</code>' indirect iterator does '<code>**it</code>'. Essentially if you wrap my iterator with a boost <code>indirect_iterator</code> you get back the same thing you started with. I found this because I was going to call my class <code>indirect_iterator</code> and then was confused for a while until I realized that what I found in boost was the opposite of what I intended.</p>
</li>
<li><p>Is the class complete? Can it wrap any iterator type correctly?</p>
</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T11:58:26.620",
"Id": "506777",
"Score": "0",
"body": "Could you detail a bit more the purpose, what you gain by wrapping like this ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T13:57:00.830",
"Id": "506784",
"Score": "0",
"body": "I have a generic algorithm that stores copies of items from a range into a spatial 3d partition tree. It is useful to store the iterators to individual objects into the tree instead of copies of the objects themselves. Thus I can transform an iterator to some object into an iterator to an iterator to some object. In this case all I really need is a forward iterator"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T16:58:51.133",
"Id": "506806",
"Score": "0",
"body": "But if the iterator only goes one direction (as opposed to something like a 2D matrix for example where you could go vertically or horizontally), then you might as well just copy the iterators themselves ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T05:57:02.307",
"Id": "506867",
"Score": "0",
"body": "Copying the iterators is exactly what this is used for. If you have a generic algorithm that copies all the values between a beig and end iterator then the same algorithm will copy all the iterators if the begin and end are wrapped with the above tool."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T06:49:42.703",
"Id": "506872",
"Score": "0",
"body": "I still don't understand why one would want to copy a whole range of iterators, whereas just a pair begin/end is enough to iterate."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T08:00:22.350",
"Id": "506891",
"Score": "0",
"body": "Because I want to build a binary space partition tree that stores pointer/iterators to values rather than the values themselves. The constructor for the partition tree takes a pair of iterators"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T17:12:01.887",
"Id": "506928",
"Score": "0",
"body": "Worded like this, it still seems to me like you would want to store references, or some kind of pointers (smart or not) to values, rather than iterators, if the goal is just to avoid copying the values from somewhere else, where they are owned."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T07:25:27.080",
"Id": "506960",
"Score": "0",
"body": "An iterator is exactly what I want to store."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T07:26:20.283",
"Id": "506961",
"Score": "0",
"body": "So I wish to create a range that generates an iterator for every element. You will just have to accept that I have good reason for wanting this even if you do not understand it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T07:29:56.827",
"Id": "506962",
"Score": "0",
"body": "An iterator is better than a pointer. Imagine I have a linked list. If I just store the pointer to the values in the linked list then if I do ``std::next(ptr)`` I will get a pointer to some undefined piece of memory. If I have an iterator to my value in the linked list then I can do ``std::next(it)`` and get the next item in the list. Thus no I do not want to store references or pointers. I want iterators."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T07:34:56.597",
"Id": "506963",
"Score": "0",
"body": "And the constructor for the binary tree is fixed. It stores values retrieved by iterating over a pair of iterators. So back to the code above. I create an iterator that when dereferenced returns an iterator and the tree stores that iterator as the value."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T16:59:21.950",
"Id": "507002",
"Score": "0",
"body": "I think the idea is great, and could be very useful (in fact, I can think of a few cases where I could have used it), but unfortunately I can’t review this because it all really boils down to `boost::iterator_facade`, which I don’t know much about. I suspect that’s going to be true for most people, so you’re going to have a tough time finding a reviewer."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T07:01:23.250",
"Id": "256666",
"Score": "2",
"Tags": [
"c++",
"iterator"
],
"Title": "A C++ iterator that adds an extra layer of indirection"
}
|
256666
|
<p>I want to notate Stock prices with html table.</p>
<p>The Number of rows (tickers) will be fixed.</p>
<p>and order of Response is also same always.</p>
<p>I want to Just updating Price Cell continuously.</p>
<p>Price data is come from other REST API server and I'll fetch this data on every 2 seconds.</p>
<p>and The Data will be notate on HTML table and Price Cell also will be updated every 2 seconds.</p>
<p>I coded and It works well, but I have a doubt on this DOM Operation. (seems uneconomic)</p>
<p>My codes work like below:</p>
<ol>
<li>JSON response from the REST API server will be like this:</li>
</ol>
<pre class="lang-json prettyprint-override"><code>[
{"ticker": "stack", "price": "$3.4"},
{"ticker": "over", "price": "$5.2"},
{"ticker": "flow", "price": "$6.4"}
]
</code></pre>
<ol start="2">
<li>HTML table will be like below:</li>
</ol>
<pre class="lang-html prettyprint-override"><code><table>
<tr>
<th>TICKER</th>
<th>PRICE</th>
</tr>
<tr>
<td>STACK</td>
<td id="stackPrice">$3.4</td>
</tr>
<tr>
<td>OVER</td>
<td id="overPrice">$5.2</td>
</tr>
<tr>
<td>FLOW</td>
<td id="flowPrice">$6.4</td>
</tr>
</table>
</code></pre>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>TICKER</th>
<th>PRICE</th>
</tr>
</thead>
<tbody>
<tr>
<td>STACK</td>
<td>$3.4</td>
</tr>
<tr>
<td>OVER</td>
<td>$5.2</td>
</tr>
<tr>
<td>FLOW</td>
<td>$6.4</td>
</tr>
</tbody>
</table>
</div>
<ol start="3">
<li>On this condition, My JavaScript code like below.</li>
</ol>
<pre class="lang-javascript prettyprint-override"><code>function fetchAndNotateData(){
fetch(apiURL, {
method: "GET",
})
.then((res) => {
return res.json();
})
.then((data) => {
data.forEach(element => {
document.getElementById(`${element.ticker}Price`).innerText = element.price; // seems inefficient
});
setTimeout(fetchAndNotateData,2000);
})
.catch((err) => {
console.log(err);
});
}
</code></pre>
<p>There is even 100 over tickers to notate in practice.</p>
<p>so There will be many DOM Operation (e.g. <em>document.getElementById</em>).</p>
<p>and Giving id on each table price cell seems not that efficient.</p>
<p>Is there any other more effective way of fetching data and notating table?
(maybe I need Server-side Rendering ?)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T08:51:13.910",
"Id": "506758",
"Score": "0",
"body": "By saying efficient, are you suffering from bad performance? Or you are just considering current implementation not such elegant? How is the table build first time? By another snippet of JavaScript? Or by some server side rendering method (PHP, for example)? Or simply from static HTML file?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T11:54:17.063",
"Id": "506775",
"Score": "0",
"body": "@tsh only by vanilla javascript, client-side rendering. 'not such elegant' is my case.\n\nHow can I check performance? I don't know even how calculate my code's performance.\n\nJust have a doubt on my codes. I just think 'These DOM operation seems occur many performance loss'.\n\nthx for comment"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T01:49:33.230",
"Id": "506851",
"Score": "0",
"body": "If the <table> is rendered client side. You may save references of these table cells by a `Map` to avoid further `getElementById`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T10:52:44.747",
"Id": "506900",
"Score": "0",
"body": "In the example the price cells already have an id. That is going to be in the `window` scope, so no need to query the elements, as you can just call, i.e. `overPrice` to get the element. If there is a possibility to get server-sent events from the API, one could use [EventSource](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) instead of polling each source every two seconds."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T07:07:46.003",
"Id": "256668",
"Score": "0",
"Tags": [
"javascript",
"html5"
],
"Title": "Most Effective way of fetching data and then notating html table with JavaScript"
}
|
256668
|
<p>I have two python scripts (or one bash script + one python script) which are working independently from another, one script puts data into a folder, the other one reads from it.</p>
<p>Since I don't want to accidentally read from the folder at the same time it's updated, I created this simple folder lock using a dummy file.</p>
<p>In the bash script a similar thing is done, by checking whether that lock.file exists, and if not create it, put the current PID into it, and after it's done delete it.</p>
<pre><code>import os
import sys
import time
import logging
LOGGER = logging.getLogger()
class SimpleFolderLock():
def __init__(self, folder_path, time_out=5):
self._folder_to_lock = folder_path
self._lock_file_path = os.path.join(self._folder_to_lock, "folder.lock")
self._lock_time_out = time_out
def __enter__(self):
start_time = time.time()
while os.path.exists(self._lock_file_path):
LOGGER.debug(f"Waiting for {self._lock_file_path} to clear")
time.sleep(5)
if (time.time() - start_time) > self._lock_time_out:
LOGGER.error(
f"Time-out for waiting for {self._lock_file_path} to clear")
raise TimeoutError(f"Can't lock {self._folder_to_lock} after {self._lock_time_out} seconds")
LOGGER.debug(f"Locking with {self._lock_file_path}")
with open(self._lock_file_path, "w") as fn:
fn.write(str(os.getpid()))
return self._lock_file_path
def __exit__(self, type, value, traceback):
try:
LOGGER.debug(f"Clearing {self._lock_file_path}")
os.remove(self._lock_file_path)
except FileNotFoundError:
LOGGER.error(f"File {self._lock_file_path} already got deleted")
</code></pre>
<p>And for a simple test:</p>
<pre><code># Just some dummy logging configuration
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
test_folder = "/tmp/test_dir/"
os.makedirs(test_folder, exist_ok=True)
with SimpleFolderLock(test_folder) as lock:
lock_path = lock
LOGGER.info(f"Locked with {lock_path}")
assert os.path.exists(lock_path)
fiddle_around_in_folder(test_folder)
assert not os.path.exists(lock_path)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T09:22:40.060",
"Id": "506897",
"Score": "0",
"body": "Welcome to Code Review. I have rolled back your last edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] |
[
{
"body": "<p>There is a race condition here:</p>\n<pre><code>while os.path.exists(self._lock_file_path):\n...\nwith open(self._lock_file_path, "w") as fn:\n</code></pre>\n<p>The file could have been created by the other process in between. You need to check file existence and create the file in one operation.</p>\n<p>Since python 3.3 there is a special <code>open</code> mode <code>x</code> for this use case:</p>\n<blockquote>\n<p>open for exclusive creation, failing if the file already exists</p>\n</blockquote>\n<p>For example:</p>\n<pre><code>while (time.time() - start_time) < self._lock_time_out:\n try:\n with open(self._lock_file_path, "x") as fn:\n fn.write(str(os.getpid()))\n except FileExistsError:\n time.sleep(5)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T08:59:05.303",
"Id": "506896",
"Score": "0",
"body": "Ah, great, updated it, thank you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T09:06:32.850",
"Id": "256674",
"ParentId": "256670",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "256674",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T08:30:25.793",
"Id": "256670",
"Score": "0",
"Tags": [
"python-3.x",
"locking"
],
"Title": "Simple folder/file lock handler"
}
|
256670
|
<p>I have a lot of redundancy here, but I am not sure how could I make it look shorter.</p>
<pre class="lang-cs prettyprint-override"><code>namespace Notan
{
public class EquipmentSystem : ScriptableObject
{
public UnityEvent onUpdate = new UnityEvent();
[SerializeField] private Weapon weapon1;
public Weapon Weapon1
{
get => weapon1;
private set
{
weapon1 = value;
onUpdate?.Invoke();
}
}
[SerializeField] private Weapon weapon2;
public Weapon Weapon2
{
get => weapon2;
private set
{
weapon2 = value;
onUpdate?.Invoke();
}
}
[SerializeField] private Accessory accessory1;
public Accessory Accessory1
{
get => accessory1;
private set
{
accessory1 = value;
onUpdate?.Invoke();
}
}
[SerializeField] private Accessory accessory2;
public Accessory Accessory2
{
get => accessory2;
private set
{
accessory2 = value;
onUpdate?.Invoke();
}
}
[SerializeField] private Shield shield;
public Shield Shield
{
get => shield;
private set
{
shield = value;
onUpdate?.Invoke();
}
}
[SerializeField] private Armor armor;
public Armor Armor
{
get => armor;
private set
{
armor = value;
onUpdate?.Invoke();
}
}
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T11:26:09.957",
"Id": "506771",
"Score": "1",
"body": "use `PropertyChangedEventHandler` to raise event whenever a property changes. here is a good answer to it : https://stackoverflow.com/questions/2246777/raise-an-event-whenever-a-propertys-value-changed"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T13:18:54.930",
"Id": "506781",
"Score": "1",
"body": "Without knowing the domain it is hard to give any naming advice but for me `PrimaryWeapon` and `SecondaryWeapon` would be more meaningful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-12-01T13:21:06.090",
"Id": "534406",
"Score": "0",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
}
] |
[
{
"body": "<p>You could make your code less redundant through the use of a custom <a href=\"https://devblogs.microsoft.com/dotnet/introducing-c-source-generators/\" rel=\"nofollow noreferrer\">SourceGenerator</a>. It could work kinda like <a href=\"https://github.com/Fody/Fody\" rel=\"nofollow noreferrer\">Fody</a> works for WPF and <a href=\"https://docs.microsoft.com/fr-fr/dotnet/api/system.componentmodel.inotifypropertychanged?view=net-5.0\" rel=\"nofollow noreferrer\"><code>INotifyPropertyChanged</code></a>.</p>\n<p>Sadly I have no example to provide for the <code>SourceGenerator</code>'s implementation because I haven't had time to toy with them yet. Though the idea is to make your <code>SourceGenerator</code> generate the redundant code for you at compile time whenever it detects something that you want to be autogenerated.</p>\n<p>You have two options but both are gonna require custom attribute(s) :</p>\n<ul>\n<li><p>Make it work like a white-list : don't autogenerate by default, autogenerate only when property is tagged with your attribute. Your property (or field) would then be reduced to</p>\n<pre class=\"lang-cs prettyprint-override\"><code>[MyAutoGenerationAttribute]\npublic object MyProperty { get; set; }\n</code></pre>\n</li>\n<li><p>Make it work like a black-list (like Fody does) : always autogenerate by default, don't autogenerate when property is tagged with your attribute.</p>\n</li>\n</ul>\n<p>I'm not really familiar with Unity but my only concern is that this solution may not be compatible with Unity's shenanigans, especially since SourceGenerators is a fairly new feature.</p>\n<p>PS : If optimization matters I recommend you edit your setters so that the event gets raised only when the value of the property changes for real (ex: by wrapping the setter with something like <code>if (myBackingField != value)</code>)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T21:19:10.730",
"Id": "256779",
"ParentId": "256676",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T11:11:42.637",
"Id": "256676",
"Score": "3",
"Tags": [
"c#",
"unity3d"
],
"Title": "Remove redundancies in similar properties"
}
|
256676
|
<p>I've implemented a dynamic queue with a random-access iterator.</p>
<p>iterator:</p>
<pre class="lang-cpp prettyprint-override"><code>#pragma once
#include <iterator>
namespace con {
template <class T> class rnd_iterator {
T *m_Ptr;
public:
/*
* type aliases
*/
using value_type = T;
using iterator_type = rnd_iterator<value_type>;
using iterator_category = std::random_access_iterator_tag;
using pointer = value_type *;
using const_pointer = const pointer;
using difference_type = std::ptrdiff_t;
using reference = value_type &;
using const_reference = const value_type &;
/*
* constructors
*/
rnd_iterator(const rnd_iterator<T> &other) noexcept : m_Ptr(other.m_Ptr) {}
rnd_iterator(T *p) noexcept : m_Ptr(p) {}
/*
* access operators
*/
reference operator*() { return *m_Ptr; }
reference operator[](std::size_t idx) { return m_Ptr[idx]; }
pointer operator->() { return m_Ptr; }
/*
* increment/decrement and assign operators
*/
rnd_iterator &operator=(pointer oth) {
m_Ptr = oth;
return *this;
}
rnd_iterator &operator+=(pointer oth) {
m_Ptr += oth;
return *this;
}
rnd_iterator &operator-=(pointer oth) {
m_Ptr -= oth;
return *this;
}
iterator_type &operator=(const iterator_type &rhs) {
m_Ptr = rhs.m_Ptr;
return *this;
}
friend iterator_type &operator+=(const iterator_type &lhs,
const iterator_type &rhs) {
lhs.m_Ptr += rhs.m_Ptr;
return lhs;
}
friend iterator_type &operator-=(const iterator_type &lhs,
const iterator_type &rhs) {
lhs.m_Ptr -= rhs.m_Ptr;
return lhs;
}
rnd_iterator operator++() {
++m_Ptr;
return *this;
}
rnd_iterator operator++(int) {
auto temp = *this;
m_Ptr++;
return temp;
}
rnd_iterator &operator--() {
--m_Ptr;
return *this;
}
rnd_iterator operator--(int) {
auto temp = *this;
m_Ptr--;
return temp;
}
/*
* comparison operators
*/
friend bool operator!=(const iterator_type &lhs, const iterator_type &rhs) {
return lhs.m_Ptr != rhs.m_Ptr;
}
friend bool operator!=(const iterator_type &lhs, pointer rhs) {
return lhs.m_Ptr != rhs;
}
friend bool operator==(const iterator_type &lhs, const iterator_type &rhs) {
return lhs.m_Ptr == rhs.m_Ptr;
}
friend bool operator==(const iterator_type &lhs, pointer rhs) {
return lhs.m_Ptr == rhs;
}
friend bool operator<(const iterator_type &lhs, const iterator_type &rhs) {
return lhs.m_Ptr < rhs.m_Ptr;
}
friend bool operator<(const iterator_type &lhs, pointer rhs) {
return lhs.m_Ptr < rhs;
}
friend bool operator<=(const iterator_type &lhs, const iterator_type &rhs) {
return lhs.m_Ptr <= rhs.m_Ptr;
}
friend bool operator<=(const iterator_type &lhs, pointer rhs) {
return lhs.m_Ptr <= rhs;
}
friend bool operator>(const iterator_type &lhs, const iterator_type &rhs) {
return lhs.m_Ptr > rhs.m_Ptr;
}
friend bool operator>(const iterator_type &lhs, pointer rhs) {
return lhs.m_Ptr > rhs;
}
friend bool operator>=(const iterator_type &lhs, const iterator_type &rhs) {
return lhs.m_Ptr >= rhs.m_Ptr;
}
friend bool operator>=(const iterator_type &lhs, pointer rhs) {
return lhs.m_Ptr >= rhs;
}
friend difference_type operator+(const iterator_type &lhs,
const iterator_type &rhs) {
return lhs.m_Ptr + rhs.m_Ptr;
}
friend difference_type operator+(const iterator_type &lhs, pointer rhs) {
return lhs.m_Ptr + rhs;
}
friend iterator_type operator+(const iterator_type &lhs,
difference_type rhs) {
return lhs.m_Ptr + rhs;
}
friend difference_type operator-(const iterator_type &lhs,
const iterator_type &rhs) {
return lhs.m_Ptr - rhs.m_Ptr;
}
friend iterator_type operator-(const iterator_type &lhs,
difference_type rhs) {
return lhs.m_Ptr - rhs;
}
friend difference_type operator-(const iterator_type &lhs, pointer rhs) {
return lhs.m_Ptr - rhs;
}
};
}
</code></pre>
<p>queue:</p>
<pre class="lang-cpp prettyprint-override"><code>#pragma once
#include "iterator.hpp"
#include <algorithm>
#include <cassert>
#include <initializer_list>
#include <iostream>
#include <iterator>
#include <limits>
#include <memory>
#include <type_traits>
#include <utility>
namespace con {
template <class T, class Allocator = std::allocator<T>> class queue {
Allocator m_Alloc;
std::size_t m_Size, m_Capacity;
std::allocator_traits<Allocator> m_AllocTraits;
T *m_RawData;
void m_ReallocAnyway(std::size_t t_NewCapacity) {
std::size_t f_old = m_Capacity;
T *f_temp = m_Alloc.allocate(sizeof(T) * t_NewCapacity);
try {
for (std::size_t i = 0; i < m_Size; i++) {
new (&f_temp[i]) T(std::move_if_noexcept(m_RawData[i]));
m_AllocTraits.destroy(m_Alloc, std::addressof(m_RawData[i]));
}
m_Alloc.deallocate(m_RawData, f_old);
m_RawData = f_temp;
} catch (const std::exception &exc) {
m_Alloc.deallocate(f_temp, sizeof(T) * t_NewCapacity);
throw std::move(exc);
}
}
void m_Realloc(std::size_t t_NewCapacity) {
if (t_NewCapacity > m_Capacity) {
m_ReallocAnyway(t_NewCapacity);
} else {
return;
}
}
void m_ShiftToLeft() {
for (std::size_t i = 0; i < m_Size; i++) {
new (&m_RawData[i]) T(std::move_if_noexcept(m_RawData[i + 1]));
}
}
template <class F>
void m_ShiftFromTo(std::size_t from, std::size_t to, F &&func) {
for (; from < to; from++) {
new (&m_RawData[from])
T(std::move_if_noexcept(m_RawData[func(from, to)]));
}
}
template <class It> void m_ShiftRangeFromTo(It from, It to) {
for (; from != to; from++) {
new (std::addressof(*from))
T(std::move_if_noexcept(*(from + (to - from))));
}
}
template <class Iter> void m_DestroyRange(Iter beg, Iter end) {
for (; beg != end; beg++) {
m_AllocTraits.destroy(m_Alloc, std::addressof(*beg));
}
}
void m_CheckOrAlloc(std::size_t t_Size) {
if (t_Size >= m_Capacity) {
m_Realloc(m_Capacity * 2);
}
}
public:
using value_type = T;
using allocator_type = Allocator;
using size_type = decltype(m_Size);
using difference_type = std::ptrdiff_t;
using reference = value_type &;
using const_reference = const value_type &;
using pointer = typename std::allocator_traits<Allocator>::pointer;
using const_pointer =
typename std::allocator_traits<Allocator>::const_pointer;
using iterator = con::rnd_iterator<value_type>;
using const_iterator = const iterator;
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
explicit queue(size_type cap = (sizeof(value_type) * 5),
const Allocator &alloc = Allocator{}) noexcept
: m_Alloc(alloc), m_Size(0), m_Capacity(cap),
m_RawData(m_Alloc.allocate(m_Capacity)) {}
explicit queue(const std::initializer_list<T> &init,
const Allocator &alloc = Allocator{}) noexcept
: m_Alloc(alloc), m_Size(init.size()), m_Capacity(sizeof(value_type) * 5),
m_RawData(m_Alloc.allocate(m_Capacity)) {
m_Size = init.size();
m_CheckOrAlloc(m_Size);
std::uninitialized_copy(init.begin(), init.end(), m_RawData);
}
explicit queue(const queue<value_type> &oth) : queue() {
if (std::is_destructible<value_type>::value)
clear();
m_Size = oth.size();
m_CheckOrAlloc(m_Size);
std::uninitialized_copy(oth.begin(), oth.end(), m_RawData);
}
explicit queue(queue<value_type> &&oth) noexcept : queue() {
if (std::is_destructible<value_type>::value)
clear();
m_Size = oth.size();
m_CheckOrAlloc(m_Size);
std::uninitialized_move(oth.begin(), oth.end(), m_RawData);
}
template <class It> queue(It begin, It end) noexcept : queue() {
assert(begin <= end);
size_type f_size = std::distance(begin, end);
m_CheckOrAlloc(f_size);
m_Size = f_size;
std::uninitialized_copy(begin, end, m_RawData);
}
explicit queue(const queue<value_type> &&oth) = delete;
iterator begin() noexcept { return iterator(m_RawData); }
iterator end() noexcept { return iterator(m_RawData + size()); }
reverse_iterator rbegin() noexcept { return reverse_iterator(end()); }
reverse_iterator rend() noexcept { return reverse_iterator(begin()); }
const_iterator begin() const noexcept { return const_iterator(m_RawData); }
const_iterator end() const noexcept {
return const_iterator(m_RawData + size());
}
const_reverse_iterator rbegin() const noexcept {
return const_reverse_iterator(m_RawData + size());
}
const_reverse_iterator rend() const noexcept {
return const_reverse_iterator(m_RawData);
}
const_iterator cbegin() const noexcept { return const_iterator(m_RawData); }
const_iterator cend() const noexcept {
return const_iterator(m_RawData + size());
}
const_reverse_iterator crbegin() const noexcept { return rbegin(); }
const_reverse_iterator crend() const noexcept { rend(); }
bool empty() const noexcept { return size() == 0; }
size_type size() const noexcept { return m_Size; }
size_type capacity() const noexcept { return m_Capacity; }
size_type max_capacity() const noexcept {
return std::numeric_limits<size_type>::max();
}
const_pointer data() const { return m_RawData; }
void clear() requires(std::is_destructible<value_type>::value) {
for (size_type i = 0; i < size(); i++) {
m_AllocTraits.destroy(m_Alloc, std::addressof(m_RawData[i]));
}
m_Size = 0;
}
void reserve(size_type cp) { m_CheckOrAlloc(cp); }
void resize(size_type sz) {
m_Size = sz;
m_CheckOrAlloc(sz);
}
void erase(iterator val) {
if (val != end()) {
difference_type x = val - begin();
pointer p = m_RawData + x;
m_AllocTraits.destroy(m_Alloc, std::addressof(*val));
m_ShiftFromTo(std::distance(begin(), iterator(p)), size(),
[](auto l, [[maybe_unused]] auto _) { return l + 1; });
m_Size--;
} else {
return;
}
}
void erase(iterator first, iterator last) {
assert(first <= last && "queue::erase invalid range");
m_DestroyRange(first, last);
m_ShiftRangeFromTo(first, last);
m_Size -= std::distance(first, last);
}
void erase(reverse_iterator first, reverse_iterator last) {
assert(first <= last && "queue::erase invalid range");
m_DestroyRange(first, last);
m_ShiftRangeFromTo(first, last);
m_Size -= std::distance(first, last);
}
void erase(reverse_iterator val) {
if (val != rend()) {
m_AllocTraits.destroy(m_Alloc, std::addressof(*val));
m_ShiftFromTo(std::distance(val, rend()) - 1, size(),
[](auto l, [[maybe_unused]] auto _) { return l + 1; });
m_Size--;
} else {
return;
}
}
void erase(const value_type &obj) { erase(std::find(begin(), end(), obj)); }
void rerase(const value_type &obj) {
erase(std::find(rbegin(), rend(), obj));
}
iterator find(const value_type &obj) {
return std::find(begin(), end(), obj);
}
reverse_iterator rfind(const value_type &obj) {
return std::find(rbegin(), rend(), obj);
}
const_iterator find(const_reference obj) const {
return std::find(begin(), end(), obj);
}
const_reverse_iterator rfind(const value_type &obj) const {
return std::find(rbegin(), rend(), obj);
}
void enqueue(const value_type &oth) requires(
std::is_copy_constructible<value_type>::value) {
m_CheckOrAlloc(size());
new (&m_RawData[m_Size++]) value_type(oth);
}
void enqueue(value_type &&oth) requires(
std::is_move_constructible<value_type>::value) {
m_CheckOrAlloc(size());
new (&m_RawData[m_Size++]) value_type(std::move(oth));
}
[[nodiscard]] value_type
dequeue() requires(std::is_destructible<value_type>::value) {
--m_Size;
value_type temp = m_RawData[0];
m_AllocTraits.destory(m_Alloc, std::addressof(m_RawData[0]));
m_ShiftToLeft();
return temp;
}
template <class... Args> void emplace(Args &&...args) {
enqueue(value_type(std::forward<Args>(args)...));
}
value_type at(size_type index) const {
if (index >= size()) {
throw std::range_error("out of bounds queue"); // yes helpful error
} else {
return m_RawData[index];
}
}
reference at(size_type index) {
if (index >= size()) {
throw std::range_error("out of bounds queue"); // yes helpful error
} else {
return m_RawData[index];
}
}
value_type operator[](size_type index) const { return m_RawData[index]; }
reference operator[](size_type index) { return m_RawData[index]; }
queue<value_type> &operator=(const queue<value_type> &oth) {
if (&oth != this) {
clear();
m_Size = oth.size();
m_CheckOrAlloc(m_Size);
std::uninitialized_copy(oth.begin(), oth.end(), m_RawData);
}
return *this;
}
queue<value_type> &operator=(queue<value_type> &&oth) {
if (&oth != this) {
clear();
m_Size = oth.size();
m_CheckOrAlloc(m_Size);
std::uninitialized_move(oth.begin(), oth.end(), m_RawData);
oth.~queue();
}
return *this;
}
queue<value_type> &operator=(const queue<value_type> &&oth) = delete;
~queue() {
m_Alloc.deallocate(m_RawData, m_Capacity);
std::exchange(m_RawData, nullptr);
std::exchange(m_Size, 0);
}
~queue() requires(std::is_destructible<value_type>::value) {
clear();
m_Alloc.deallocate(m_RawData, m_Capacity);
std::exchange(m_RawData, nullptr);
std::exchange(m_Size, 0);
}
};
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>Despite the many criticisms in my review, I think this is an <em>OUTSTANDING</em> effort.</p>\n<h1>Design review</h1>\n<h2>Iterators are part of range interfaces</h2>\n<p>The first issue that strikes me about your design is that you have separated the iterator from the container. That’s nonsense. Iterators can’t exist independently from a container. There is no such thing as a “general-purpose random-access iterator”.</p>\n<p><strong>Iterators are a part of a range</strong>. We <em>talk</em> about them as independent “things”, but they are not. In fact, you can’t even <em>create</em> an iterator without a range to create it from. By attempting to separate the iterator from the range, you’ve actually created numerous problems. It is possible (even dangerously easy) to create broken <code>rnd_iterator</code>s (<code>rnd_iterator</code>s that don’t actually reference a legitimate range).</p>\n<p>What you’ve actually created with <code>rnd_iterator</code> is not really a random-access iterator. It <em>looks</em> like one, and it will work for <em>some</em> containers—it will work for <code>std::vector</code>, but not <code>std::deque</code>, for example—but it will crash with most random-access containers (like <code>std::deque</code>). It’s actually an iterator type that will work with <em>contiguous</em> ranges (<code>std::vector</code> is a contiguous range, and so is <code>con::queue</code>)… not random-access ranges… but it will work <em>worse</em> than the range’s own iterator type.</p>\n<p>In <em>fact</em>, <code>rnd_iterator</code> is really nothing more than an alias for <code>T*</code>… except it’s more limited, less efficient, and lacks the well-understood semantics.</p>\n<h2>Dangerous conversions</h2>\n<p><code>rnd_iterator</code> has a serious problem with dangerous conversions from raw pointers. That’s not a good thing; that’s very, very bad. There are <em>NO</em> situations, any time, ever, where you’d want client code to be able to freely convert raw pointers to queue iterators. And <em>especially</em> to have those conversions happen silently, by default.</p>\n<p>The problem here is that because the iterator is separate from the container, you need a way to convert the container’s internal pointers to iterators. But by making that <em>public</em>, you’ve allowed random user code to be able to do the same thing. I can take any random pair of raw pointers, and create a pair of iterators… even if those pointers are not pointing to the same array. And in fact, even worse, random pointers will be automatically and silently converted to iterators, so at the slightest typo, suddenly I have what looks like a valid range. Hello, bugs. For example:</p>\n<pre><code>auto i = 0;\nauto ptr = &i;\n\nauto q = con::queue<int>{};\n\nfind(q.begin(), ptr, 42); // compiles without a warning, and probably crashes\n</code></pre>\n<p>You need for <code>con::queue</code> to be able to construct iterators from raw pointers… <em>but that should only be an <em>internal</em> function</em>. It should not be available to outside code. You could do this by friendship, I suppose, but however you do it, <code>con::queue</code> should be able to turn its internal pointers into iterators, but nothing else.</p>\n<p>Incidentally, this also implies you should remove all the other operations with raw pointers:</p>\n<pre><code> // all these are bad\n\n rnd_iterator &operator=(pointer oth);\n rnd_iterator &operator+=(pointer oth);\n rnd_iterator &operator-=(pointer oth);\n\n friend bool operator!=(const iterator_type &lhs, pointer rhs);\n friend bool operator==(const iterator_type &lhs, pointer rhs);\n friend bool operator<(const iterator_type &lhs, pointer rhs);\n friend bool operator<=(const iterator_type &lhs, pointer rhs);\n friend bool operator>(const iterator_type &lhs, pointer rhs);\n friend bool operator>=(const iterator_type &lhs, pointer rhs);\n friend difference_type operator+(const iterator_type &lhs, pointer rhs);\n</code></pre>\n<p>There is <em>NO</em> situation where it would be a <em>good</em> thing to do comparisons or other operations between iterators and raw pointers. (And if you ever create a situation where you need to do that: 1) you should rewrite your algorithm; and 2) you could do it anyway, it would just be much more verbose, but that’s a good thing.)</p>\n<h2>Overblown interface</h2>\n<p>Now, you’re making a queue, which, by definition, exists to take elements in on one end, and pop them off from the other. Does the existing interface make sense for that?</p>\n<p>Like, what is the purpose of being able to iterate through the queue… <em>backwards</em>? Seems a bit silly. I mean, one might ask why you need to iterate through the queue <em>at all</em> even, including <em>forwards</em>, because… that’s not how you use queues. You push, and you pop; <a href=\"https://en.wikipedia.org/wiki/Queue_(abstract_data_type)\" rel=\"nofollow noreferrer\">those are the only operations a queue needs</a>. But okay, having range access isn’t a <em>bad</em> thing because it can allow some <em>massive</em> optimizations (like rather than repeatedly popping items off the queue until it’s empty, you could iterate through the queue doing some operation, then clear the whole queue in a single step). But… <em>backwards</em>? Really?</p>\n<p>And let’s be clear, if your queue <em>can</em> support reverse iteration, I’m not saying you should <em>prevent</em> it. But you don’t need to make it part of the public interface. You could remove <code>rbegin()</code>/<code>rend()</code> etc. and still have reverse iteration:</p>\n<pre><code>std::for_each(std::reverse_iterator{q.begin()}, std::reverse_iterator{q.end()}, func);\n\n// or:\n\nstd::for_each(std::ranges::rbegin(q), std::ranges::rend(q), func);\n\n// or:\n\nfor (auto&& element : q | std::views::reverse)\n func(element);\n</code></pre>\n<p>All of the above work with <em>just</em> <code>begin()</code> and <code>end()</code>, and do the exact same thing, just as efficiently. So there’s no need to add more cruft to the queue’s interface, especially stuff that doesn’t <em>directly</em> relate to what a queue actually is.</p>\n<p>Similar logic goes for the element access functions. Does it really make sense to provide random access to the middle of a queue? I don’t see why. If I want efficient random-access to a sequential data structure… well, that’s what <code>std::vector</code> is for (or <code>std::deque</code> for that matter). Again, even if you remove <code>operator[size_type]</code> and <code>at()</code>, it’s still possible to get efficient access to random elements in the queue (because the queue iterators are random-access iterators). So you’re not <em>losing</em> functionality by removing those functions. You’re just sending the message “that’s not how I intend for this type to be used (because it’s a queue)”.</p>\n<p>A good interface should be:</p>\n<ol>\n<li>Complete. It should be possible to do every operation necessary for the type with maximal efficiency.</li>\n<li>Minimal. The more crap you add to an interface, the more unwieldy the class becomes both for maintainers and users (because now users have learn and memorize more functions).</li>\n<li>Logical. The interface should have all the operations that make semantic sense for what the type <em>means</em>… and no more than that (with exceptions made for the sake usability and efficiency).</li>\n</ol>\n<p>A queue’s basic interface should be nothing more than construction, destruction, moving, copying, pushing, and popping, and <em>maybe</em> peeking at the front of the queue, and <em>maybe-maybe</em> peeking at the back of the queue… <em>and that… is… it</em>. If you add <em>ANYTHING ELSE</em>, you need to seriously justify why it’s <em>NECESSARY</em>, either for usability or efficiency… because every single little thing you add to a class makes it that much more brittle, that much less maintainable, and that much more annoying to learn and use.</p>\n<p>So I would suggest trimming down this interface quite a bit. I would suggest removing:</p>\n<ul>\n<li><code>reverse_iterator</code> and <code>const_reverse_iterator</code>.</li>\n<li><code>rbegin()</code>, <code>rend()</code>, <code>crbegin()</code>, <code>crend()</code>.</li>\n<li><code>max_capacity()</code>, because it is not a standard container function; <code>max_size()</code> is.</li>\n<li><em>All</em> the element access functions. You can get at elements just as easily and efficiently with iterators.</li>\n<li>All the erase functions that don’t take <code>iterator</code>.</li>\n<li>All the find functions.</li>\n</ul>\n<p>I would also suggest <em>adding</em> a few functions:</p>\n<ul>\n<li>Definitely <code>shrink_to_fit()</code>.</li>\n<li>At least <code>front()</code>, and maybe <code>back()</code> as well.</li>\n<li>A <code>dequeue_and_discard()</code> function for when you want to pop but don’t care what you’re popping.</li>\n<li>Maybe <code>assign()</code>, where you can assign from an iterator pair or initializer list.</li>\n<li>Maybe a <code>resize()</code> (and perhaps <code>assign()</code>) overload that takes a source to copy for any new elements.</li>\n<li><code>get_allocator()</code> and <code>max_size()</code>, for container requirements.</li>\n</ul>\n<h2>Unbalanced efficiency</h2>\n<p>The standard library has a queue—<a href=\"https://en.cppreference.com/w/cpp/container/queue\" rel=\"nofollow noreferrer\"><code>std::queue</code></a>. It’s actually a container <em>adapter</em>: you supply a container, and it makes it act like a queue. The reason I’m mentioning all this is because the default container for a <code>std::queue</code> is <code>std::deque</code>… not <code>std::vector</code>.</p>\n<p>Why is that relevant? Because your queue—<code>con::queue</code>—is actually built on an implementation that is <em>basically</em> <code>std::vector</code>.</p>\n<p>Here’s why that’s an issue. When you are <em>pushing</em> to your queue, you get maximal efficiency. Let’s imagine you start with a queue that has capacity = 2, and is full, and you want to push a total of 8 elements:</p>\n<ol>\n<li>Push element 3.\n<ul>\n<li>Allocate 4 spaces.</li>\n<li>Move element 1 to new memory.</li>\n<li>Move element 2 to new memory.</li>\n<li>Push element 3 into new memory.</li>\n<li>(Queue now has size = 3, capacity = 4)</li>\n</ul>\n</li>\n<li>Push element 4.\n<ul>\n<li>Push element 4 into existing capacity</li>\n<li>(Queue now has size = 4, capacity = 4)</li>\n</ul>\n</li>\n<li>Push element 5.\n<ul>\n<li>Allocate 8 spaces.</li>\n<li>Move element 1 to new memory.</li>\n<li>Move element 2 to new memory.</li>\n<li>Move element 3 to new memory.</li>\n<li>Move element 4 to new memory.</li>\n<li>Push element 5 into new memory.</li>\n<li>(Queue now has size = 5, capacity = 8)</li>\n</ul>\n</li>\n<li>Push element 6.\n<ul>\n<li>Push element 6 into existing capacity</li>\n<li>(Queue now has size = 6, capacity = 8)</li>\n</ul>\n</li>\n<li>Push element 7.\n<ul>\n<li>Push element 7 into existing capacity</li>\n<li>(Queue now has size = 7, capacity = 8)</li>\n</ul>\n</li>\n<li>Push element 8.\n<ul>\n<li>Push element 8 into existing capacity</li>\n<li>(Queue now has size = 8, capacity = 8)</li>\n</ul>\n</li>\n</ol>\n<p>That’s not bad! That’s actually highly efficient. There are two allocations during the process, but that’s not really avoidable (unless you reserve, of course), and during those two allocations, there are a bunch of extra moves… but for fully <em>half</em> of the pushes, it’s doing the absolute minimum work possible: just adding the element directly into the queue. (And if you actually reserved the required capacity up front, you’d <em>really</em> get the minimum work possible.)</p>\n<p>But now look what happens when you try to <em>pop</em> those 6 elements back off:</p>\n<ol>\n<li>Pop element.\n<ul>\n<li>Move element 1 to return slot.</li>\n<li>Move element 2 to position 1.</li>\n<li>Move element 3 to position 2.</li>\n<li>Move element 4 to position 3.</li>\n<li>Move element 5 to position 4.</li>\n<li>Move element 6 to position 5.</li>\n<li>Move element 7 to position 6.</li>\n<li>Move element 8 to position 7.</li>\n</ul>\n</li>\n<li>Pop element.\n<ul>\n<li>Move element 1 to return slot.</li>\n<li>Move element 2 to position 1.</li>\n<li>Move element 3 to position 2.</li>\n<li>Move element 4 to position 3.</li>\n<li>Move element 5 to position 4.</li>\n<li>Move element 6 to position 5.</li>\n<li>Move element 7 to position 6.</li>\n</ul>\n</li>\n<li>Pop element\n<ul>\n<li>Move element 1 to return slot.</li>\n<li>Move element 2 to position 1.</li>\n<li>Move element 3 to position 2.</li>\n<li>Move element 4 to position 3.</li>\n<li>Move element 5 to position 4.</li>\n<li>Move element 6 to position 5.</li>\n</ul>\n</li>\n<li>Pop element.\n<ul>\n<li>Move element 1 to return slot.</li>\n<li>Move element 2 to position 1.</li>\n<li>Move element 3 to position 2.</li>\n<li>Move element 4 to position 3.</li>\n<li>Move element 5 to position 4.</li>\n</ul>\n</li>\n<li>Pop element.\n<ul>\n<li>Move element 1 to return slot.</li>\n<li>Move element 2 to position 1.</li>\n<li>Move element 3 to position 2.</li>\n<li>Move element 4 to position 3.</li>\n</ul>\n</li>\n<li>Pop element.\n<ul>\n<li>Move element 1 to return slot.</li>\n<li>Move element 2 to position 1.</li>\n<li>Move element 3 to position 2.</li>\n</ul>\n</li>\n</ol>\n<p>Yikes. That’s not a problem with your implementation. In fact, if you used <code>std::vector</code> with <code>std::queue</code> you’d get the same behaviour. That’s why <code>std::vector</code> is not the default container to use with <code>std::queue</code>. Every time you pop an element off of a queue built on a vector-like container with <code>N</code>, you trigger a chain of <code>N − 1</code> moves. If your queue has a million elements, popping an item off triggers 9,999,999 moves. Not great.</p>\n<p>Here is what would happen with a <code>std::queue</code> using <code>std::deque</code>:</p>\n<ol>\n<li>Pop element.\n<ul>\n<li>Move element 1 to return slot.</li>\n</ul>\n</li>\n<li>Pop element.\n<ul>\n<li>Move element 1 to return slot.</li>\n</ul>\n</li>\n<li>Pop element\n<ul>\n<li>Move element 1 to return slot.</li>\n</ul>\n</li>\n<li>Pop element.\n<ul>\n<li>Move element 1 to return slot.</li>\n</ul>\n</li>\n<li>Pop element.\n<ul>\n<li>Move element 1 to return slot.</li>\n</ul>\n</li>\n<li>Pop element.\n<ul>\n<li>Move element 1 to return slot.</li>\n</ul>\n</li>\n</ol>\n<p>Wow, big difference, eh?</p>\n<p>Now I am <em>NOT</em> saying you should make your queue with a re-implementation of <code>std::deque</code> internally. In fact, I think you could do <em>much</em> better. Your implementation is already half-way there. The only thing I think you need to do differently is <em>not</em> adjusting the entire internal array when you pop from the front.</p>\n<p>Here’s one way you could do it:</p>\n<ul>\n<li>Store the currently allocated block address.</li>\n<li>Store a pointer to the head of the queue (in the currently allocated block).</li>\n<li>Store the queue size.</li>\n</ul>\n<p>Currently you store only <code>m_RawPtr</code> as <em>BOTH</em> the current block address <em>AND</em> the head of the queue… and <em>that</em> is where your problems arise. I recommend splitting them into two. That way, when you pop from the queue, you don’t need to move all the elements one position over… you just move the pointer to the queue head.</p>\n<p>Here’s how that might look. Suppose you have a queue with size 6, capacity 8:</p>\n<pre><code> +---+---+---+---+---+---+---+---+\n | A | B | C | D | E | F | _ | _ |\n +---+---+---+---+---+---+---+---+\n ^\n |\nm_block -+\n |\nm_head --/\n\nm_size = 6\n\nm_capacity = 8\n</code></pre>\n<p>With your current design, when you pop, you get this:</p>\n<pre><code> +---+---+---+---+---+---+---+---+\n | B | C | D | E | F | _ | _ | _ |\n +---+---+---+---+---+---+---+---+\n ^\n |\nm_block -+\n |\nm_head --/\n\nm_size = 5\n\nm_capacity = 8\n</code></pre>\n<p>(Except of course, instead of <code>m_block</code> and <code>m_head</code>, you just have the one <code>m_RawPtr</code>.)</p>\n<p>What I’m suggesting is that when you pop, you destroy the head element, and then just advance the head pointer:</p>\n<pre><code> +---+---+---+---+---+---+---+---+\n | _ | B | C | D | E | F | _ | _ |\n +---+---+---+---+---+---+---+---+\n ^ ^\n | |\nm_block -/ |\n |\nm_head ------/\n\nm_size = 5\n\nm_capacity = 7\n</code></pre>\n<p>The pro of this design is that popping now becomes <em>MUCH</em> faster, and there is no more chance of failure (which might happen if you have elements that are not nothrow-movable). The con is that you don’t recover capacity by popping. So if your use pattern is one-push-one-pop over and over… you’ll need to reallocate eventually. (With <code>std::deque</code> as the underlying container, that can be avoided because a deque is a bunch of chunks: if necessary, the deque can just move empty chunks around to avoid needing to reallocate at one end or the other.) <em>HOWEVER</em>, if your use pattern is to basically pump the queue empty every so often, then this design could be <em>very</em> efficient, because every time you empty the queue, you can just reset the head pointer to the beginning of the block, and recover <em>all</em> the capacity. Or, if the space at the beginning is larger than the size, you can safely copy the whole queue back to the beginning of the block. (And if the elements are nothrow-movable, you can do that safely any time, so you can always recover the capacity when you need it.)</p>\n<p>Anyway, whatever design you choose, I just wanted to point out that you have an unbalanced efficiency issue: pushing is fast, popping is slow. If that’s what you <em>want</em>, well then fine; there’s nothing <em>wrong</em> with having fast pushes and slow pops. It’s a little surprising, but if you document that that’s the point, then that’s cool. That pattern does have real-world usage potential.</p>\n<h2>Indestructible elements?</h2>\n<p>Several functions in the queue class have a bizarre requirement: <code>requires(std::is_destructible<value_type>::value)</code>. Now, for starters, it would probably make more sense to use the destructible concept: <code>requires std::destructible<T></code>. But aside from that… what do you think it means for a type to not be destructible?</p>\n<p>If a type cannot be destroyed, then how the hell are you are supposed to pop elements from the queue? How the hell are you supposed to <em>destroy the queue itself</em>? (No, your answer— simply ignoring the destruction of the elements and deallocating their memory out from under them—is absolutely <em>NOT</em> the right answer. That’s a one-way ticket to UB-land, with bonus leakage along the way.)</p>\n<p>If a type cannot be destroyed, it cannot be constructed. (At least, not without significant chicanery that’s not worth serious consideration.) If a type cannot be constructed… how the hell is it supposed to get <em>into</em> the queue? The only way to put things <em>into</em> the queue is either to move construct, copy construct, or otherwise directly (via <code>emplace()</code>) construct them in the queue. If you can’t destruct, you can’t construct, so none of those things should be possible (conceptually). So never mind getting things <em>out</em> of the queue; you can’t even put things <em>into</em> the queue.</p>\n<p>So if a type is indestructible, you can’t put it into the queue, and even if you could, you couldn’t then take it <em>out</em> of the queue, or even destroy the queue itself.</p>\n<p>So what do <em>you</em> think it means to have a queue full of indestructible objects? Do you have any actual use-cases for this?</p>\n<p>From where I’m sitting, it looks like complete nonsense, but maybe I’m missing something.</p>\n<h1>Code review</h1>\n<h2><code>rnd_iterator</code></h2>\n<p>To start, let me reiterate that what you’ve basically done is re-implemented <code>T*</code>… except not as efficiently. That being said, let’s dive in to the actual code.</p>\n<pre><code>#pragma once\n</code></pre>\n<p><code>#pragma once</code> is non-standard, and it has serious problems that while rare, are <em>nightmarish</em> to deal with (which is why it’s never been standardized). <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#sf8-use-include-guards-for-all-h-files\" rel=\"nofollow noreferrer\">Use include guards instead</a>.</p>\n<pre><code>T *m_Ptr;\n</code></pre>\n<p><a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#nl18-use-c-style-declarator-layout\" rel=\"nofollow noreferrer\">In C++, the convention is to put the pointer asterisk or reference ampersand with the type, not with the variable name</a>. That’s because types matter more in C++… it’s more important to think of <code>m_Ptr</code> as a <code>T*</code> than it is to think of it as a pointer to a <code>T</code>.</p>\n<ul>\n<li><code>T *m_ptr</code> is C style.</li>\n<li><code>T* m_ptr</code> is C++ style.</li>\n</ul>\n<p>This is true for references as well.</p>\n<pre><code>using value_type = T;\n</code></pre>\n<p>If you want this template to be used for both <code>iterator</code> and <code>const_iterator</code>, then you will need to remove the <code>const</code> here. This is as easy as <code>using value_type = std::remove_cv_t<T>;</code>.</p>\n<pre><code>using pointer = value_type *;\n// ... [snip] ...\nusing difference_type = std::ptrdiff_t;\nusing reference = value_type &;\n</code></pre>\n<p>You have a problem where <code>con::queue<T>::iterator::pointer</code> may not be the same as <code>con::queue<T>::pointer</code>, because the former is <code>typename std::allocator_traits<Allocator>::pointer</code> while the latter is just <code>T*</code>. This is just one of a number of problems that arise because you have separated the iterator from the container.</p>\n<pre><code>using iterator_type = rnd_iterator<value_type>;\n</code></pre>\n<p>I don’t see the point of this type alias. It’s actually <em>longer</em> than just using <code>rnd_iterator</code>.</p>\n<pre><code>using const_pointer = const pointer;\n// ...\nusing const_reference = const value_type &;\n</code></pre>\n<p>These two type aliases make no sense. They make sense in the context of the <em>container</em>… but not in the context of the iterator. <code>iterator::const_reference</code> makes no sense; what you’d really want is <code>const_iterator::reference</code>.</p>\n<p>In any case, you have defined <code>const_pointer</code> incorrectly (although <code>const_reference</code> is correct).</p>\n<pre><code>rnd_iterator(const rnd_iterator<T> &other) noexcept : m_Ptr(other.m_Ptr) {}\n</code></pre>\n<p>There is no reason to write this constructor, because it’s not doing anything differently from the default, implicitly generated copy constructor. And, in fact, by writing it out, you have actually crippled the efficiency. See the <a href=\"https://en.cppreference.com/w/cpp/language/rule_of_three\" rel=\"nofollow noreferrer\">the rule of 3/5/0</a>.</p>\n<pre><code>rnd_iterator(T *p) noexcept : m_Ptr(p) {}\n</code></pre>\n<p><a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#c46-by-default-declare-single-argument-constructors-explicit\" rel=\"nofollow noreferrer\">All single-argument constructors should, by default, be declared <code>explicit</code></a>.</p>\n<p>But as mentioned in the design overview, this constructor should also be private (if it even exists at all).</p>\n<pre><code>reference operator[](std::size_t idx) { return m_Ptr[idx]; }\n</code></pre>\n<p>This should actually be using the container’s <code>size_type</code>, not <code>std::size_t</code>. Again, this is why iterators should be defined with their containers. They don’t make sense independently.</p>\n<p>Also, all of the access operators should be <code>const</code>. None of them change <em>the iterator</em>. You could use the returned pointer/reference to change whatever is pointed-to or referenced… but <em>the iterator itself</em> isn’t being changed.</p>\n<pre><code> rnd_iterator &operator=(pointer oth)\n rnd_iterator &operator+=(pointer oth)\n rnd_iterator &operator-=(pointer oth)\n</code></pre>\n<p>All of these operations should be deleted.</p>\n<p>Also… what sense does adding two pointers make? What do you think will happen if you add a pointer to a pointer?</p>\n<pre><code> iterator_type &operator=(const iterator_type &rhs)\n</code></pre>\n<p>Like the copy constructor, this shouldn’t be explicitly defined.</p>\n<pre><code> friend iterator_type &operator+=(const iterator_type &lhs,\n const iterator_type &rhs)\n</code></pre>\n<p>Adding pointers, or iterators, makes no sense.</p>\n<pre><code> friend iterator_type &operator-=(const iterator_type &lhs,\n const iterator_type &rhs)\n</code></pre>\n<p><em>Subtracting</em> iterators <em>does</em> make sense… but the result will be a <code>difference_type</code>… not an iterator. So <code>operator-=</code> with an iterator on the right-hand side makes no sense.</p>\n<pre><code> rnd_iterator operator++()\n</code></pre>\n<p>You have a bug; you forgot the <code>&</code> on the return type.</p>\n<pre><code> friend bool operator!=(const iterator_type &lhs, const iterator_type &rhs)\n friend bool operator!=(const iterator_type &lhs, pointer rhs)\n friend bool operator==(const iterator_type &lhs, const iterator_type &rhs)\n friend bool operator==(const iterator_type &lhs, pointer rhs)\n friend bool operator<(const iterator_type &lhs, const iterator_type &rhs)\n friend bool operator<(const iterator_type &lhs, pointer rhs)\n friend bool operator<=(const iterator_type &lhs, const iterator_type &rhs)\n friend bool operator<=(const iterator_type &lhs, pointer rhs)\n friend bool operator>(const iterator_type &lhs, const iterator_type &rhs)\n friend bool operator>(const iterator_type &lhs, pointer rhs)\n friend bool operator>=(const iterator_type &lhs, const iterator_type &rhs)\n friend bool operator>=(const iterator_type &lhs, pointer rhs)\n</code></pre>\n<p>Okay, first, all of the operations that take raw pointers should be removed.</p>\n<p>That leaves you with only the operations between two iterators. But you’re using C++20, so all of the above can be reduced to one line:</p>\n<pre><code> constexpr auto operator<=>(iterator const&) const noexcept = default;\n</code></pre>\n<p>(I’ve added <code>constexpr</code>, though you don’t have it anywhere else. You <em>could</em>, though.)</p>\n<pre><code> friend difference_type operator+(const iterator_type &lhs,\n const iterator_type &rhs)\n friend difference_type operator+(const iterator_type &lhs, pointer rhs)\n</code></pre>\n<p>Adding iterators makes no sense. Adding a pointer to an iterator makes even less sense.</p>\n<pre><code> friend iterator_type operator-(const iterator_type &lhs, difference_type rhs)\n friend difference_type operator-(const iterator_type &lhs, pointer rhs)\n</code></pre>\n<p>The operation with a raw pointer should be removed, but you have also forgotten all the addition operations. You can’t add two iterators… but you can add an iterator and a <code>difference_type</code> in either order.</p>\n<p>A big problem that you will probably run into is that you haven’t given any thought to the relationship between <code>rnd_iterator<T></code> and <code>rnd_iterator<const T></code>. The former should be implicitly convertible to the latter… but the latter should <em>not</em> be convertible to the former. This will really become an issue when you try to use it as <code>iterator</code> and <code>const_iterator</code> for the container.</p>\n<p>One more thing worth mentioning: you explicitly said you want a random-access iterator, and yeah, that’s what you have. <em>However</em>, you <em>could</em> have a <em>contiguous</em> iterator, if you wanted.</p>\n<h2><code>queue<T, Allocator></code></h2>\n<pre><code> Allocator m_Alloc;\n std::size_t m_Size, m_Capacity;\n std::allocator_traits<Allocator> m_AllocTraits;\n T *m_RawData;\n</code></pre>\n<p>There are a couple issues with the way you’ve laid out your class.</p>\n<p>First, when you are ordering a class’s data members, you should try to <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#per17-declare-the-most-used-member-of-a-time-critical-struct-first\" rel=\"nofollow noreferrer\">put the most important data members first</a>. Why? Because the address of the very first member in a class is (usually!) the same as <code>this</code>, which means the moment you access <code>this</code>, you already have the first data member right there. Later data members <em>might</em> not be in cache yet, and may require a separate load.</p>\n<p>In this case, the data member you probably want right up front is <code>m_rawData</code>. So that should be first. Next most important is maybe <code>m_Size</code>, followed by <code>m_Capacity</code>, with <code>m_Alloc</code> being the least important.</p>\n<p>The second problem comes from the fact that allocators are often stateless, which means they have zero size. However, when you write an allocator data member like that, it has to take up <em>at least</em> 1 byte. And, unfortunately, the next type is <code>std::size_t</code>, which is usually 8 bytes, and has to be aligned on an 8-byte boundary… so <code>m_Alloc</code> will have to be padded with 7 extra bytes just to make things line up.</p>\n<p>To fix that, you can use <a href=\"https://en.cppreference.com/w/cpp/language/attributes/no_unique_address\" rel=\"nofollow noreferrer\"><code>[[no_unique_address]]</code></a>, so if <code>m_Allocator</code> really is zero-sized, it will take up zero space in the class.</p>\n<p>Never do this:</p>\n<pre><code>std::size_t m_Size, m_Capacity;\n</code></pre>\n<p><a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#es10-declare-one-name-only-per-declaration\" rel=\"nofollow noreferrer\">Each declaration should be on its own line</a>.</p>\n<p>And, finally, there is no need for <code>m_AllocTraits</code>. <code>std::allocator_traits</code> is a traits class. It is zero-sized by definition, and it is meant to be used statically. You’re never supposed to create an <code>allocator_traits</code> object, let alone store one in a class. <code>m_AllocTraits.destroy(...)</code> is just plain wrong. <code>destroy()</code> is not a non-static member function, it is a static member function. You have to call it like this: <code>decltype(m_AllocTraits)::destroy(...)</code>. But of course, that makes no sense when you can just do <code>std::allocator_traits<Allocator>::destroy(...)</code>.</p>\n<p>So your data members should probably look more like this:</p>\n<pre><code> T* m_RawData = nulltpr;\n std::size_t m_Size = 0;\n std::size_t m_Capacity = 0;\n [[no_unique_address]] Allocator m_Alloc = {};\n</code></pre>\n<p>Note I added initializers, which is probably a good idea, too.</p>\n<pre><code> void m_ReallocAnyway(std::size_t t_NewCapacity)\n</code></pre>\n<p>This is a very good attempt at writing what is actually an <em>EXTREMELY</em> complicated operation.</p>\n<p>You correctly use <code>std::allocator_traits</code> elsewhere in the code, but not here, which is a shame. Instead of calling <code>m_Alloc.allocate(...)</code> directly, you should do:</p>\n<pre><code>auto f_temp = std::allocator_traits<Allocator>::allocate(m_Alloc, t_NewCapacity);\n</code></pre>\n<p>Note also that it’s just <code>t_NewCapacity</code>… not <code>sizeof(T) * t_NewCapacity</code>. The allocator already knows about <code>sizeof(T)</code> (as well as <code>alignof(T)</code>).</p>\n<p>Also, using <code>std::addressof()</code> is a little ridiculous. You know <code>m_RawData</code> is a <code>T*</code>. It doesn’t make sense to dereference the pointer, then use <code>addressof()</code> to get it back. Just do <code>m_RawData + i</code>.</p>\n<p>Alright, now comes the <em>really</em> tricky part:</p>\n<pre><code> for (std::size_t i = 0; i < m_Size; i++) {\n new (&f_temp[i]) T(std::move_if_noexcept(m_RawData[i]));\n // ...\n }\n</code></pre>\n<p>First, rather than a raw placement-<code>new</code>, you should be using <code>std::allocator_traits<Allocator>::construct(m_Alloc, f_temp + i, std::move_if_noexcept(m_RawData[i]))</code>.</p>\n<p>But now here comes the critical issue. Let’s say <code>m_Size</code> is 10; there are 10 elements in queue. So you start the loop, and successfully copy-construct 5 elements… then, catastrophe, an exception is thrown copying the 6th element. What happens now?</p>\n<p>Well, you bubble up to the <code>catch</code> block, deallocate <code>f_temp</code>, and then propagate the exception…</p>\n<p>… but… hang on… you’ve missed something.</p>\n<p>5 objects were constructed. Those 5 objects need to be destructed before you can deallocate the memory out from under them.</p>\n<p>So what you actually need to do is something more like:</p>\n<pre><code>// allocate the memory\nauto const f_temp = std::allocator_traits<Allocator>::allocate(m_Alloc, t_NewCapacity);\n\nauto num_constructed = std::size_t{0};\ntry\n{\n // construct the objects in that memory\n for (; num_constructed != m_Size; ++num_constructed)\n {\n std::allocator_traits<Allocator>::construct(\n m_Alloc,\n f_temp + num_constructed,\n std::move_if_noexcept(m_RawData[num_constructed])\n );\n }\n}\ncatch (...)\n{\n // destroy objects in reverse order\n for (auto i = num_constructed; i != 0; --i)\n {\n std::allocator_traits<Allocator>::destroy(m_Alloc, f_temp + (i - 1));\n }\n\n // deallocate the memory\n std::allocator_traits<Allocator>::deallocate(m_Alloc, f_temp, t_NewCapacity);\n\n throw;\n}\n</code></pre>\n<p>Now, your <code>catch</code> block is also wrong. You should <em>never</em> rethrow an exception the way you do, because while you catch a <code>std::exception const&</code>, the <em>actual</em> exception might not be an actual <code>std::exception</code>. It might be <code>std::bad_alloc</code> or some other type that derives from <code>std::exception</code>. So when you do <code>throw exc;</code> (or <code>throw std::move(exc);</code>, which is pointless, because <code>exc</code> is a <code>const</code> reference… you can’t move from a <code>const</code> object, it’s going to turn into a copy anyway) you might actually be slicing the actual exception object. That’s bad.</p>\n<p><em>Never</em> rethrow an exception like <code>throw exc;</code>. Just do <code>throw;</code>.</p>\n<p>Also, there is no reason you need to limit the exceptions you catch to types that derive from <code>std::exception</code>. If some <code>T</code> constructor throws some other exception type, you want to catch and rethrow that, too. So don’t limit the <code>catch</code> to <code>std::exception const&</code>. Catch everything with <code>catch (...)</code>. Rethrow anything with <code>throw;</code>.</p>\n<p>Finally, you’re asking for trouble interleaving the construction of the new elements with the destruction of the old ones. Consider the same scenario as before, where you’ve copied 5 out of 10 elements, and then there’s an exception. If you’ve been destroying the source elements as you go along… well, now you’re screwed. You have an array where the first 5 elements are invalid.</p>\n<p>Instead, what you should aim to do is get all the dangerous stuff out of the way first, and <em>then</em> do cleanup. Allocating the new array and copy-constructing the new elements are the dangerous steps. Once those are done, destroying the old elements and deallocating the old array should be safe. So do those last. Something like:</p>\n<pre><code> void m_ReallocAnyway(std::size_t new_capacity)\n {\n using alloc_traits = std::allocator_traits<Allocator>;\n\n // this might throw, but if it does, meh, we haven't done anything yet\n auto const new_data = alloc_traits::allocate(m_Alloc, new_capacity);\n\n auto num_constructed = std::size_t{0};\n try\n {\n // any of these copy-constructions might fail\n //\n // if they do, the catch block will clean up everything done so far\n for (; num_constructed != m_Size; ++num_constructed)\n {\n alloc_traits::construct(\n m_Alloc,\n new_data + num_constructed,\n std::move_if_noexcept(m_RawData[num_constructed])\n );\n }\n }\n catch (...)\n {\n // all the clean-up from the potentially dangerous stuff goes here\n\n for (auto i = num_constructed; i != 0; --i)\n {\n alloc_traits::destroy(m_Alloc, new_data + (i - 1));\n }\n\n alloc_traits::deallocate(m_Alloc, new_data, new_capacity);\n\n throw;\n }\n\n // now new_data contains all the stuff from m_RawData\n //\n // from this point on, all we need to do is clean up the old stuff,\n // which should be no-fail\n\n // destroy old objects in reverse order\n for (auto i = m_Size; ; i != 0; --i)\n {\n // shouldn't fail\n alloc_traits::destroy(m_Alloc, m_RawData + (i - 1));\n }\n\n // deallocate old memory; shouldn't fail\n alloc_traits::deallocate(m_Alloc, m_RawData, m_Capacity);\n\n // and finally, set the class data members to the new values\n //\n // these also can't fail\n m_RawData = new_data;\n m_Capacity = new_capacity;\n }\n</code></pre>\n<p>As an optimization to the above, you could put the entire <code>try</code>-<code>catch</code> block in an <code>if constexpr</code> block, so that you only need it when you don’t have no-fail moving. If moving is no-fail (as it is for most types), then there’s no need to worry about anything in that first loop failing, so there’s no need for any cleanup.</p>\n<pre><code> void m_Realloc(std::size_t t_NewCapacity) {\n if (t_NewCapacity > m_Capacity) {\n m_ReallocAnyway(t_NewCapacity);\n } else {\n return;\n }\n }\n</code></pre>\n<p>I mean, you don’t really need the <code>else { return; }</code> here. But I suppose that’s just a matter of personal style.</p>\n<pre><code> void m_ShiftToLeft() {\n for (std::size_t i = 0; i < m_Size; i++) {\n new (&m_RawData[i]) T(std::move_if_noexcept(m_RawData[i + 1]));\n }\n }\n</code></pre>\n<p>This is really wrong.</p>\n<p>First, placement <code>new</code> constructs a new object in raw memory. You should never do that overtop of an existing object. If an object is already constructed, you need to destroy it before you can construct a new object over it. If you want to replace an existing object with another existing object… as you’re doing here… you have two options:</p>\n<ol>\n<li>The hard way:\n<ol>\n<li>Destroy object 1</li>\n<li>Use placement <code>new</code> to copy/move construct from object 2 over the old location of object 1</li>\n</ol>\n</li>\n<li>The easy way:\n<ol>\n<li>Just copy/move assign object 2 to object 1</li>\n</ol>\n</li>\n</ol>\n<p>The catch of option 2 is that it requires the type to be copy/move assignable, whereas option 1 only requires the type to be copy/move <em>constructible</em> (which you need anyway).</p>\n<p>(By the way, I get that the only time this function is ever used, you’ve already destroyed the first object in the queue. So the <em>first</em> iteration of the loop is correct… though every subsequent iteration is still wrong. In any case, the whole plan is still terrible. But we’ll get to that later.)</p>\n<p>If you <em>actually</em> want to shift everything in the queue to the left, the safest way to do it would be to use <code>move_if_no_except()</code> to copy/move-assign every item to the previous one. If moving really is no-fail, then this will be perfectly safe. If it’s not… well, then there’s really no way to make this operation safe. (Well, there is one! But we’ll get to it later.)</p>\n<p>Also, note that in your code, you have a bug. You loop from 0 to <code>m_Size</code>, which is fine, but then you access <code>m_RawData[i + 1]</code>, which is one-past-the-end.</p>\n<pre><code> template <class F>\n void m_ShiftFromTo(std::size_t from, std::size_t to, F &&func)\n</code></pre>\n<p>This whole function really doesn’t make any sense. All you ever use it for is to shift elements to the start <code>N</code> positions over starting at position <code>I</code> (and <code>N</code> is always 1, though it doesn’t need to be, conceivably). <code>m_ShiftRangeFromTo()</code> already covers that. There’s no need for all the extra complexity of a function object. Keep things simple, and you’ll have fewer bugs and less maintenance headache.</p>\n<pre><code> void m_CheckOrAlloc(std::size_t t_Size) {\n if (t_Size >= m_Capacity) {\n m_Realloc(m_Capacity * 2);\n }\n }\n</code></pre>\n<p>Are you sure this is what you want? If your capacity is 10, and someone wants to put 10 elements in the queue… you <em>really</em> want to reallocate to a capacity of 20 rather than just put the 10 elements in the existing capacity?</p>\n<pre><code> using iterator = con::rnd_iterator<value_type>;\n using const_iterator = const iterator;\n</code></pre>\n<p><code>const_iterator</code> is incorrect. It should be <code>con::rnd_iterator<value_type const></code> (assuming <code>rnd_iterator</code> correctly handles <code>const</code> value types… which it doesn’t, but should).</p>\n<pre><code> explicit queue(size_type cap = (sizeof(value_type) * 5),\n const Allocator &alloc = Allocator{}) noexcept\n : m_Alloc(alloc), m_Size(0), m_Capacity(cap),\n m_RawData(m_Alloc.allocate(m_Capacity)) {}\n</code></pre>\n<p>This is your default constructor… among other things (which is not good!)… and you want it to be <code>noexcept</code>, which is a good idea… however, it can’t be, because you’ve crammed too much work into it. How can it possibly be <code>noexcept</code> when you’re allocating?</p>\n<p>The first thing I would recommend is to not use default parameters. I think they’re a terrible idea in general, and it’s an especially bad idea here. At the very least, even <em>if</em> you insist on using default parameters, you’re going to need more constructors than this, because it should be possible to construct a queue with just an allocator, like so: <code>auto q = queue<int>(alloc);</code>.</p>\n<p>So you need at least two constructors:</p>\n<pre><code>explicit queue(const Allocator& alloc = {}) noexcept;\nexplicit queue(size_type cap, const Allocator& alloc = {});\n</code></pre>\n<p>But this is still a wacky interface, because when I do <code>auto q = queue<int>(5);</code>, I expect that means to create a queue with 5 default-constructed elements in it. That’s what it means for every container in the standard library, after all. But, no, here I get an <em>empty</em> queue… with a <em>capacity</em> of 5. That’s just weird.</p>\n<p>My advice is to just forget the constructor with the capacity. You don’t need it. This:</p>\n<pre><code>auto q = queue<int>{};\nq.reserve(5);\n</code></pre>\n<p>… is clearer than:</p>\n<pre><code>auto q = queue<int>(5);\n</code></pre>\n<p>… and there’s no reason it couldn’t be just as efficient.</p>\n<p>So that leaves you with just the default constructor (with optional allocator). But it’s still not <code>noexcept</code> so long as it’s allocating. So if you really want a <code>noexcept</code> default constructor (and you should!), you need to not do any allocating. How is that possible?</p>\n<p>Well, one option is to say that a default-constructed queue has a size of 0 and a capacity of 0, and thus <code>m_RawData</code> is <code>nullptr</code>:</p>\n<pre><code>template <typename T, typename Allocator = std::allocator<T>>\nclass queue\n{\n T* m_RawData = nullptr;\n std::size_t m_Size = 0;\n std::size_t m_Capacity = 0;\n [[no_unique_address]] Allocator m_alloc = {};\n\n // ... [snip] ...\n\npublic:\n constexpr explicit queue(Allocator const& alloc = {}) noexcept :\n m_Alloc{alloc}\n {}\n\n // ...\n</code></pre>\n<p>Of course, since you now have a “null state”, you have to be careful in some of your member functions to account for it… but not that many actually. (Mostly just the destructor and the functions that might do destruction in one form or another (like <code>reserve()</code>).</p>\n<p>But having this no-fail default construction is <em>enormously</em> important, because it allows for no-fail <em>moving</em> as well, and thus, swapping. And you really, <em>really</em> want <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#c66-make-move-operations-noexcept\" rel=\"nofollow noreferrer\">no-fail moving</a> and <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#c85-make-swap-noexcept\" rel=\"nofollow noreferrer\">no-fail swapping</a>. You could do:</p>\n<pre><code> static constexpr auto _swap_data_with_equal_allocators(queue& to, queue&& from) noexcept\n {\n std::ranges::swap(to.m_RawData, from.m_RawData);\n std::ranges::swap(to.m_Size, from.m_Size);\n std::ranges::swap(to.m_Capacity, from.m_Capacity);\n }\n\n static constexpr auto _move_data_with_equal_allocators(queue& to, queue&& from) noexcept\n {\n return _swap_data_with_equal_allocators(to, std::move(from));\n }\n\n constexpr queue() noexcept = default;\n\n constexpr explicit queue(Allocator const& alloc) noexcept :\n m_Alloc{alloc}\n {}\n\n constexpr queue(queue&& other) noexcept :\n m_Alloc{std::move(other.m_Alloc)}\n {\n _move_data_with_equal_allocators(*this, std::move(other));\n }\n\n constexpr queue(queue&& other, Allocator const& alloc)\n noexcept(std::allocator_traits<Allocator>::is_always_equal) :\n m_Alloc{alloc}\n {\n if constexpr (std::allocator_traits<Allocator>::is_always_equal)\n {\n _move_data_with_equal_allocators(*this, std::move(other));\n }\n else\n {\n if (m_Alloc == other.m_Alloc)\n {\n _move_data_with_equal_allocators(*this, std::move(other));\n }\n else\n {\n // need to allocate memory, then MOVE-CONSTRUCT elements\n // from other\n //\n // afterwards, other should have its original size and\n // capacity... but all the elements should be moved-from\n }\n }\n }\n\n constexpr auto operator=(queue&& other)\n noexcept(std::allocator_traits<Allocator>::propagate_on_container_move_assignment\n or std::allocator_traits<Allocator>::is_always_equal)\n -> queue&\n {\n if constexpr (std::allocator_traits<Allocator>::propagate_on_container_move_assignment)\n {\n // this is safe, because copying allocators is guaranteed to be\n // noexcept, and of course moving a queue's data is noexcept\n clear();\n\n m_alloc = other.m_alloc;\n\n _move_data_with_equal_allocators(*this, std::move(other));\n }\n else\n {\n if constexpr (std::allocator_traits<Allocator>::is_always_equal)\n {\n _move_data_with_equal_allocators(*this, std::move(other));\n }\n else\n {\n if (m_alloc == other.m_alloc)\n {\n _move_data_with_equal_allocators(*this, std::move(other));\n }\n else\n {\n // need to make sure this has enough capacity, then\n // MOVE-ASSIGN the elements from other into this\n //\n // take into account whether moving/copying is noexcept;\n // if not, then maybe you need to use a temporary buffer\n // to keep the strong exception guarantee\n //\n // afterwards, other should have its original size and\n // capacity... but all the elements should be moved-from\n }\n }\n }\n\n return *this;\n }\n\n constexpr auto swap(queue& other)\n noexcept(std::allocator_traits<Allocator>::propagate_on_container_swap\n or std::allocator_traits<Allocator>::is_always_equal)\n -> void\n {\n if constexpr (std::allocator_traits<Allocator>::is_always_equal)\n {\n if constexpr (std::allocator_traits<Allocator>::propagate_on_container_swap)\n std::ranges::swap(m_alloc, other.m_alloc);\n\n _swap_data_with_equal_allocators(*this, std::move(other));\n }\n else\n {\n if (m_Alloc == other.m_Alloc)\n {\n _swap_data_with_equal_allocators(*this, std::move(other));\n }\n else\n {\n // ??? you're on your own here\n //\n // this is UB for all standard containers, so maybe make it UB\n // for yours, too, and throw or terminate\n }\n }\n }\n</code></pre>\n<p>With the above, moving and swapping is guaranteed no-fail whenever possible, and even when it’s not possible to <em>guarantee</em>, it’s no-fail whenever possible.</p>\n<p>But let’s get back to your constructor:</p>\n<pre><code> explicit queue(size_type cap = (sizeof(value_type) * 5),\n const Allocator &alloc = Allocator{}) noexcept\n</code></pre>\n<p>Now you seem confused about what “capacity” means, and sizing in general. In the standard containers, a capacity of 5 means it can hold 5 <code>T</code>s without reallocating… <em>no matter what size the <code>T</code>s are</em>. Same goes for the size, basically: a size of 8 means it has 8 objects… not that it’s 8 bytes large.</p>\n<p>So when you do… <code>cap = (sizeof(value_type) * 5)</code>, you’re saying that the default capacity for a queue depends on the size of the objects its holding. If it’s a <code>queue<std::byte></code>, then it has a capacity to hold 5 objects, so the total size in memory is 5 bytes… but if it's a <code>queue<std::array<std::byte, 1000>></code>, then it has a capacity to hold <em>5,000</em> objects… so the total size in memory is <em>5,000,000</em> bytes. Clearly something has gone awry.</p>\n<p>What you really want, I think, is just <code>cap = 5</code>. That means the default capacity is 5 objects, regardless of what those objects are.</p>\n<p>Also, once again, don’t intialize multiple things on a single line. It makes your code damn near illegible.</p>\n<pre><code> explicit queue(const std::initializer_list<T> &init,\n const Allocator &alloc = Allocator{}) noexcept\n : m_Alloc(alloc), m_Size(init.size()), m_Capacity(sizeof(value_type) * 5),\n m_RawData(m_Alloc.allocate(m_Capacity))\n</code></pre>\n<p>First, you should never take initializer lists by <code>const&</code>. They are made to be passed around by value.</p>\n<p>Second, this constructor obviously can’t be <code>noexcept</code>, because it’s allocating.</p>\n<p>Third, I don’t see the sense of allocating a capacity of 5 (or <code>sizeof(T) * 5</code> even) when you know already how many objects are in the initializer list. If it’s greater, then you’ll need to throw away what you’ve just allocated and reallocate… which is silly. If it’s less, then you’ve got wasted capacity that you may never need, because if someone gave you an initializer list, that often means they already know all the data they need in the queue.</p>\n<p>In fact, you might as well just delegate this constructor over to the iterator constructor:</p>\n<pre><code> constexpr queue(std::initializer_list<T> init, Allocator const& alloc = {}) :\n queue(init.begin(), init.end(), alloc)\n {}\n</code></pre>\n<p>Assuming you write the iterator constructor well, there will be no performance loss from doing this.</p>\n<pre><code> explicit queue(const queue<value_type> &oth) : queue() {\n if (std::is_destructible<value_type>::value)\n clear();\n m_Size = oth.size();\n m_CheckOrAlloc(m_Size);\n std::uninitialized_copy(oth.begin(), oth.end(), m_RawData);\n }\n</code></pre>\n<p>First, let’s get the obvious issue out of the way: you are clearing a queue that you know has to be empty… because it’s just been constructed and nothing’s been put in it. I don’t think you thought this through.</p>\n<p>But the real issue here is the test for <code>is_destructible</code>. As mentioned in the design section… this is gibberish.</p>\n<p>Okay, that weirdness aside, you have an efficiency issue when you delegate to the default constructor, which allocates a default capacity, and then possibly <em>reallocate</em> with a new size. As with the initializer list constructor, it’s easier just to delegate to the iterator constructor:</p>\n<pre><code> constexpr queue(queue const& other) :\n queue(other.begin(), other.end())\n {}\n\n constexpr queue(queue const& other, Allocator const& alloc) :\n queue(other.begin(), other.end(), alloc)\n {}\n</code></pre>\n<p>Once again, assuming the iterator constructor is properly written, this should cause no performance penalty.</p>\n<pre><code> explicit queue(queue<value_type> &&oth) noexcept : queue() {\n if (std::is_destructible<value_type>::value)\n clear();\n m_Size = oth.size();\n m_CheckOrAlloc(m_Size);\n std::uninitialized_move(oth.begin(), oth.end(), m_RawData);\n }\n</code></pre>\n<p>Yikes, no, this is <em>not</em> how you move containers. You absolutely do <em>not</em> allocate a whole new buffer and then move construct a whole new set of objects there. I’ve already shown how to do a <em>proper</em> <code>noexcept</code> move constructor above.</p>\n<pre><code> template <class It> queue(It begin, It end) noexcept : queue() {\n assert(begin <= end);\n size_type f_size = std::distance(begin, end);\n m_CheckOrAlloc(f_size);\n m_Size = f_size;\n std::uninitialized_copy(begin, end, m_RawData);\n }\n</code></pre>\n<p>Now this is an important constructor to get right, because if it’s done well, so many other operations can be built on top of it.</p>\n<p>The first problem here is that you don’t seem to understand iterator categories. <code>assert(begin <= end);</code> will only work for random-access or better iterators… and, frankly, it’s a pointless test anyway. But the real sneaky issue is that call to <code>std::distance()</code>. Because you use that, you are restricting the iterator category to forward iterators or better… meaning you can’t fill a queue with data from a file like this:</p>\n<pre><code>auto file = std::ifstream{"/path/to/data"};\n\nauto q = queue<int>{std::istream_iterator<int>{file}, std::istream_iterator<int>{}};\n// q now has all the ints that were in the data file\n</code></pre>\n<p>If you try the code above, it will compile and run… but the queue will be empty. That’s because <code>istream_iterator</code>s are input iterators, which means you get only one pass. You blow through that one pass with <code>std::distance()</code>. Which means that by the time you get to <code>std::uninitialized_copy()</code>… there’s no more data. Your queue is now broken, because it <em>says</em> it has a certain size… but there will be nothing in it but uninitialized gibberish.</p>\n<p>What you need to do is check the iterator category. If it’s forward or better, you can use <code>std::distance()</code> to preallocate the buffer. But if it’s just input iterator, then the best you can do is add elements one at a time, reallocating as you go:</p>\n<pre><code> template <std::input_iterator It, std::sentinel_for<It> Sen>\n constexpr queue(It first, Sen last, Allocator const& alloc = {}) :\n m_Alloc{alloc}\n {\n while (first != last)\n push_back(*first++);\n }\n\n template <std::forward_iterator It, std::sentinel_for<It> Sen>\n constexpr queue(It first, Sen last, Allocator const& alloc = {}) :\n m_Alloc{alloc}\n {\n reserve(std::distance(begin, end));\n std::ranges::uninitialized_copy(first, last, m_RawData, m_RawData + m_Capacity);\n m_Size = m_Capacity;\n }\n</code></pre>\n<p>Note that I’m using iterator/sentinel pairs, rather than iterator/iterator pairs. That’s the C++20 way. Also note that I haven’t included any error handling. Let’s call than an exercise for the reader.</p>\n<pre><code> explicit queue(const queue<value_type> &&oth) = delete;\n</code></pre>\n<p>? </p>\n<pre><code> const_iterator cbegin() const noexcept { return const_iterator(m_RawData); }\n const_iterator cend() const noexcept {\n return const_iterator(m_RawData + size());\n }\n</code></pre>\n<p>These can both just return <code>begin()</code> and <code>end()</code> respectively.</p>\n<pre><code> const_reverse_iterator crend() const noexcept { rend(); }\n</code></pre>\n<p>Missing <code>return</code>.</p>\n<pre><code> size_type max_capacity() const noexcept {\n return std::numeric_limits<size_type>::max();\n }\n</code></pre>\n<p>Standard containers don’t have <code>max_capacity()</code>… but they do have <code>max_size()</code>, which you don’t.</p>\n<p>Also, assuming you can hold the max value of <code>size_type</code> seems optimistic. A better estimate would probably be <code>std::numeric_limits<size_type>::max() / sizeof(T)</code>. But meh, I’ve never seen anyone actually <em>use</em> <code>max_size()</code>.</p>\n<pre><code>const_pointer data() const { return m_RawData; }\n</code></pre>\n<p>If you’re providing this, you might as well provide the non-<code>const</code> overload.</p>\n<pre><code> void clear() requires(std::is_destructible<value_type>::value) {\n for (size_type i = 0; i < size(); i++) {\n m_AllocTraits.destroy(m_Alloc, std::addressof(m_RawData[i]));\n }\n m_Size = 0;\n }\n</code></pre>\n<p>The constraint makes no sense, as discussed earlier.</p>\n<p>The function should be <code>noexcept</code> (especially since it needs to be used in the destructor).</p>\n<p>You are not using allocator traits correctly, as discussed earlier.</p>\n<p>The <code>addressof()</code> is pointless.</p>\n<pre><code>void reserve(size_type cp) { m_CheckOrAlloc(cp); }\n</code></pre>\n<p>It’s good that you’re willing to delegate to helper functions, but…</p>\n<ol>\n<li><code>m_CheckOrAlloc()</code> checks whether the new capacity is larger, and if so delegates to <code>m_Realloc()</code>.</li>\n<li><code>m_Realloc()</code> checks whether the new capacity is larger, and if so delegates to <code>m_ReallocAnyway()</code>.</li>\n<li><code>m_ReallocAnyway()</code> finally just reallocates unconditionally.</li>\n</ol>\n<p>Is all that dancing really necessary?</p>\n<ol>\n<li><code>m_ReallocAnyway()</code> is <em>ONLY</em> ever called from <code>m_Realloc()</code>.</li>\n<li><code>m_Realloc()</code> is <em>ONLY</em> ever called from <code>m_CheckOrAlloc()</code>.</li>\n<li><code>m_CheckOrAlloc()</code> is called from multiple places (good!)… but… it’s really just <code>reserve()</code>.</li>\n</ol>\n<p>I think <em>AT MOST</em> all you need is <code>reserve()</code>, and then <em>maybe</em> an internal, unconditional reallocation function. Keep it simple.</p>\n<pre><code> void resize(size_type sz) {\n m_Size = sz;\n m_CheckOrAlloc(sz);\n }\n</code></pre>\n<p>This is just completely wrong. You allocate enough capacity, <em>but you never actually construct or destruct any objects</em>. You just set the size. You’re either going to truncate your queue with a bunch of inaccessible objects past the end, or the last few elements in your queue are going to be empty garbage.</p>\n<pre><code> void erase(iterator val)\n void erase(iterator first, iterator last)\n</code></pre>\n<p><code>erase()</code> is perhaps the trickiest function in <code>std::vector</code> to properly implement, and your queue is basically <code>std::vector</code>. In the <code>std::vector</code> version of <code>erase()</code> there are basically 2 paths:</p>\n<ol>\n<li><code>erase(p, q)</code>, where <code>q</code> is equal to <code>end()</code>.</li>\n<li><code>erase(p, q)</code>, where <code>q</code> is <em>not</em> equal to <code>end()</code>.</li>\n</ol>\n<p>And the single-argument form of <code>erase()</code> just delegates to those two paths:</p>\n<ol>\n<li><code>erase(p)</code> where <code>p</code> is <code>end()</code>… just return.</li>\n<li><code>erase(p)</code> where <code>p</code> is <code>end() - 1</code>… go to path 1 above as <code>erase(end() - 1, end())</code>.</li>\n<li><code>erase(p)</code> where <code>p</code> is <em>not</em> <code>end() - 1</code>… go to path 2 above as <code>erase(p, p + 1)</code>.</li>\n</ol>\n<p>So the single argument version is easy:</p>\n<pre><code> void erase(const_iterator p)\n {\n if (p != end())\n erase(p, p + 1);\n }\n</code></pre>\n<p>Now, in the 2-argument version, if <code>last</code> is <code>end()</code>, you just destroy everything from <code>first</code> to <code>end()</code>. No biggie:</p>\n<pre><code> void erase(const_iterator first, const_iterator last)\n {\n if (last == end())\n {\n for (; first != end(); ++first)\n // use allocator traits to destroy each element\n\n // set m_Size\n }\n else\n {\n // ...\n }\n }\n</code></pre>\n<p>Simple.</p>\n<p>If <code>last</code> is <em>not</em> <code>end()</code>, <em>now</em> you need to do the shifting. Something like:</p>\n<pre><code> void erase(const_iterator first, const_iterator last)\n {\n if (last == end())\n {\n // ...\n }\n else\n {\n std::ranges::move(last, end(), first);\n\n for (; last != end(); ++last)\n // use allocator traits to destroy each element\n\n // set m_Size\n }\n }\n</code></pre>\n<p>You can simplify this, but when you do, you will find that it is the <em>opposite</em> of your implementation: <em>first</em> it does the shift, <em>then</em> it does the destroying. Why? Exception safety. If you destroy all the elements in the middle first, then you try to start the shifting, what happens if an exception is thrown midway through shifting? Now you have a hole of uninitialized memory in the middle of your queue.</p>\n<pre><code> void erase(reverse_iterator first, reverse_iterator last)\n void erase(reverse_iterator val)\n</code></pre>\n<p>These functions just seem ridiculous. Who’s seriously going to want to erase elements from the queue… <em>backwards</em>? And if they don’t <em>really</em> want to erase elements backwards, but it’s just that they have reverse iterators and want to erase some stuff (but don’t really care about the order), then they can just do:</p>\n<pre><code>q.erase(rev_first.base(), rev_last.base());\n</code></pre>\n<p>Don’t put crap in your interface you don’t need. The more you over-complicate the plumbing, the easier it is to clog up the drain.</p>\n<pre><code> void erase(const value_type &obj) { erase(std::find(begin(), end(), obj)); }\n</code></pre>\n<p>Notice how the entirety of this function is implementable from the public interface, just as efficiently? Thus you don’t need it.</p>\n<pre><code> void rerase(const value_type &obj)\n</code></pre>\n<p>The Scooby-Doo version of <code>erase()</code>, I presume.</p>\n<pre><code> iterator find(const value_type &obj)\n reverse_iterator rfind(const value_type &obj)\n const_iterator find(const_reference obj) const\n const_reverse_iterator rfind(const value_type &obj) const\n</code></pre>\n<p>All of these functions are pointless, because you can do the exact same job from the rest of the public interface, with no loss of efficiency. In fact, you can do <em>MORE</em> from the public interface. For example:</p>\n<pre><code>auto q1 = queue<std::string>{};\n\nstd::ranges::find(q1, "foo"sv); // can search with a string view,\n // without having to construct a string\n\n// could also use projections\n\nauto q2 = queue<int>{};\n\nstd::find(std::unseq, q2.begin(), q2.end(), 42); // vectorized find\n</code></pre>\n<p>You see, adding more functions to an interface doesn’t make it better. Making it easier to use existing algorithms is what really makes it better. And for that, all you really need are basics: <code>begin()</code>, <code>end()</code>, <code>size()</code> maybe, and so on. Less is more.</p>\n<pre><code> void enqueue(const value_type &oth) requires(\n std::is_copy_constructible<value_type>::value) {\n m_CheckOrAlloc(size());\n new (&m_RawData[m_Size++]) value_type(oth);\n }\n void enqueue(value_type &&oth) requires(\n std::is_move_constructible<value_type>::value) {\n m_CheckOrAlloc(size());\n new (&m_RawData[m_Size++]) value_type(std::move(oth));\n }\n</code></pre>\n<p>You’ve actually introduced a subtle bug by being clever here. By incrementing <code>m_Size</code> in the same expression, if the copy/move construction fails, now the queue has the wrong size; the last element will be random garbage.</p>\n<p>You shouldn’t increment <code>m_Size</code> until <em>after</em> the creation of the new element succeeds.</p>\n<p>A word about using concepts: concepts are still very new technology, and we haven’t really established a good set of rules for when to use them or how. But one idea that seems to be taking root is that <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#t20-avoid-concepts-without-meaningful-semantics\" rel=\"nofollow noreferrer\">you shouldn’t treat concepts as simply assertions on operations</a>. In other words, you shouldn’t say, “well, I’m move-constructing the element here… therefore I should add a <code>move_constructible</code> concept”. When you do that, you are limiting your options. As a somewhat silly example, let’s say that someone has a non-move-constructible type… but that type is <code>noexcept</code> default constructible, and <code>noexcept</code> move-assignable. In that case, you could still implement <code>enqueue(value_type&&)</code>… except if you already blocked it by requiring move construction, now you’re screwed.</p>\n<p>That example may have been silly, but there’s actually a real case of it in your code here. Your <code>enqueue(value_type&&)</code> says that it requires move construction… except that it will still work without move construction. If I have a type that is copy constructible, but not move constructible, then move construction will fall back on copy construction. So <code>enqueue(value_type&&)</code> still works fine with types that are not move constructible. Your requires clause prevents perfectly good code from working.</p>\n<p>The bottom line is: don’t use concepts unless you know you need them. You don’t need them here. They don’t actually improve anything. Even without the concepts, the functions will fail to compile for types that won’t work.</p>\n<pre><code> [[nodiscard]] value_type\n dequeue() requires(std::is_destructible<value_type>::value) {\n --m_Size;\n value_type temp = m_RawData[0];\n m_AllocTraits.destory(m_Alloc, std::addressof(m_RawData[0]));\n m_ShiftToLeft();\n return temp;\n }\n</code></pre>\n<p>Now this requires clause is obviously unnecessary, as discussed earlier.</p>\n<p>I’m also not keen on the <code>[[nodiscard]]</code> here. It’s not hard to image usage scenarios where I want to pop something off the front of the queue, but I don’t really care what it is. <em>Forcing</em> me to care about what I’m taking off the queue seems unnecessarily dictatorial. You should use <code>[[nodiscard]]</code> in situations where ignoring the return value is probably an error. I don’t see that that’s the case here.</p>\n<p>You also have some exception safety issues. What happens if the copy construction to <code>temp</code> fails? You’ve already decremented <code>m_Size</code>… which means you’ve “lost” the last element of the queue. Seems safer to not change the size until after you’ve done the dangerous stuff.</p>\n<p>(Also, you misspelled “destroy”.)</p>\n<pre><code> template <class... Args> void emplace(Args &&...args) {\n enqueue(value_type(std::forward<Args>(args)...));\n }\n</code></pre>\n<p>Ah, you’ve kinda missed the point of emplacing. The point of emplacing is to construct the new object <em>in place</em>. (Hence, “<a href=\"https://en.wiktionary.org/wiki/emplace\" rel=\"nofollow noreferrer\">emplace</a>”.) Not to just construct it somewhere random and then copy it in. Rather than writing <code>emplace()</code> in terms of <code>enqueue()</code>, it would make more sense to do the opposite.</p>\n<pre><code> value_type at(size_type index) const\n value_type operator[](size_type index) const\n</code></pre>\n<p>These should return a <code>const_reference</code>, not a <code>value_type</code>.</p>\n<pre><code> queue<value_type> &operator=(const queue<value_type> &oth) {\n if (&oth != this) {\n clear();\n m_Size = oth.size();\n m_CheckOrAlloc(m_Size);\n std::uninitialized_copy(oth.begin(), oth.end(), m_RawData);\n }\n return *this;\n }\n</code></pre>\n<p>This is a dangerous way to do copy assignment. If any of the copying at the end fails, you’ve lost the original data. A better way is to use the “copy and swap” idiom.</p>\n<pre><code> queue<value_type> &operator=(queue<value_type> &&oth) {\n if (&oth != this) {\n clear();\n m_Size = oth.size();\n m_CheckOrAlloc(m_Size);\n std::uninitialized_move(oth.begin(), oth.end(), m_RawData);\n oth.~queue();\n }\n return *this;\n }\n</code></pre>\n<p>It’s usually possible, and much easier, to implement moving in terms of swapping.</p>\n<p>But in any case, explicitly calling the destructor of <code>oth</code> is definitely wrong. Except in very rare, special-case situations, you should never manually call destructors.</p>\n<pre><code> queue<value_type> &operator=(const queue<value_type> &&oth) = delete;\n</code></pre>\n<p>Again, what is the purpose of this?</p>\n<pre><code> ~queue() {\n m_Alloc.deallocate(m_RawData, m_Capacity);\n std::exchange(m_RawData, nullptr);\n std::exchange(m_Size, 0);\n }\n ~queue() requires(std::is_destructible<value_type>::value) {\n clear();\n m_Alloc.deallocate(m_RawData, m_Capacity);\n std::exchange(m_RawData, nullptr);\n std::exchange(m_Size, 0);\n }\n</code></pre>\n<p>So, let’s set aside the whole <code>is_destructible</code> thing; only the second destructor is correct (sorta).</p>\n<p>However, there’s no point in zeroing the data members at the end (and even less point in using <code>std::exchange()</code> to do it). It doesn’t matter if <code>m_RawData</code> is still pointing to now deallocated memory, because <code>m_RawData</code> is about to cease existing anyway.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T15:12:43.807",
"Id": "508054",
"Score": "0",
"body": "I appreciate your effort, I'm confused about the move assignment/ctor, why having `noexcept` depending on the allocator stats and also the swap when `is_always_equal` is true otherwise just allocate enough capacity, why it does and why is it important ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-18T21:09:14.293",
"Id": "508364",
"Score": "0",
"body": "Answering that would take far more space than comments allow, and the answer above is already full, so I'll add another answer with the explanation."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T00:15:56.647",
"Id": "257088",
"ParentId": "256677",
"Score": "4"
}
},
{
"body": "<h1>Answers to questions</h1>\n<h2>Allocator equality</h2>\n<p>The first piece of the puzzle is understanding what it means when two allocators are equal. <strong>If two allocators are equal, then any memory allocated with one can be deallocated with the other.</strong></p>\n<p>For example:</p>\n<pre><code>auto a1 = std::allocator<int>{};\nauto a2 = std::allocator<int>{};\n\nstd::cout << std::boolalpha << (a1 == a2); // will print "true"\n\nauto p = a1.allocate(1);\n\n// this is okay:\na2.deallocate(p);\n</code></pre>\n<p>If two allocators are <em>not</em> equal, then you <em>cannot</em> deallocate memory from one with the other:</p>\n<pre><code>auto mr1 = std::pmr::unsynchronized_pool_resource{};\nauto mr2 = std::pmr::unsynchronized_pool_resource{};\n\nauto a1_a = std::pmr::polymorphic_allocator<int>{&mr1};\nauto a1_b = std::pmr::polymorphic_allocator<int>{&mr1};\n\nstd::cout << std::boolalpha << (a1_a == a1_b) << '\\n'; // will print "true"\n\nauto a2 = std::pmr::polymorphic_allocator<int>{&mr2};\n\nstd::cout << std::boolalpha << (a2 == a1_a) << '\\n'; // will print "false"\nstd::cout << std::boolalpha << (a2 == a1_b) << '\\n'; // will print "false"\n\nauto p1 = a1_a.allocate(1);\nauto p2 = a1_a.allocate(1);\n\n// this is okay:\na1_b.deallocate(p1);\n\n// this is *NOT* okay:\na2.deallocate(p2);\n</code></pre>\n<p>Some types of allocators are <em>always</em> equal. For example, <code>std::allocator</code> just uses <code>new</code> and <code>delete</code>, so it doesn’t matter <em>which</em> <code>std::allocator</code> instance you use (in theory, you could even mix <code>std::allocator</code> with raw <code>new</code> and <code>delete</code>… but I do <em>not</em> recommend that).</p>\n<h2>Which allocator gets used?</h2>\n<p>The next piece of the puzzle is knowing which allocator gets used with different methods of construction, assignment, and swapping. I’ll use <code>std::vector</code> as a guide (since your queue is basically a <code>std::vector</code> under the hood):</p>\n<ul>\n<li><code>vector() noexcept(noexcept(Allocator()))</code>\n<ul>\n<li>Default-constructed allocator.</li>\n</ul>\n</li>\n<li><code>explicit vector(Allocator const& alloc) noexcept</code>\n<ul>\n<li>Uses <code>alloc</code>. (It can be <code>noexcept</code> because allocators must be <code>noexcept</code> copyable, and it’s not doing any allocating.)</li>\n</ul>\n</li>\n<li><code>vector(vector const& other)</code>\n<ul>\n<li>Uses <code>std::allocator_traits<Allocator>::select_on_container_copy_construction(other.get_allocator())</code>. Usually just copies the allocator.</li>\n</ul>\n</li>\n<li><code>vector(vector const& other, Allocator const& alloc)</code>\n<ul>\n<li>Uses <code>alloc</code>.</li>\n</ul>\n</li>\n<li><code>vector(vector&& other) noexcept</code>\n<ul>\n<li>Uses an allocator move-constructed from <code>other.get_allocator()</code>.</li>\n</ul>\n</li>\n<li><code>vector(vector&& other, Allocator const& alloc)</code>\n<ul>\n<li>Uses <code>alloc</code>.</li>\n</ul>\n</li>\n<li><code>auto operator=(vector const& other) -> vector&</code>\n<ul>\n<li>If <code>std::allocator_traits<Allocator>::propagate_on_container_copy_assignment::value</code> is <code>true</code>:\n<ul>\n<li>Uses a copy of <code>other</code>’s allocator.</li>\n</ul>\n</li>\n<li>Else:\n<ul>\n<li>Keeps its own allocator.</li>\n</ul>\n</li>\n</ul>\n</li>\n<li><code>auto operator=(vector&& other) noexcept(/* !!! */) -> vector&</code>\n<ul>\n<li>If <code>std::allocator_traits<Allocator>::propagate_on_container_move_assignment::value</code> is <code>true</code>:\n<ul>\n<li>Uses a copy of <code>other</code>’s allocator.</li>\n</ul>\n</li>\n<li>Else:\n<ul>\n<li>Keeps its own allocator.</li>\n</ul>\n</li>\n</ul>\n</li>\n<li><code>auto swap(vector& a, vector& b) noexcept (/* !!! */) -> void</code>\n<ul>\n<li>If <code>std::allocator_traits<Allocator>::propagate_on_container_swap::value</code> is <code>true</code>:\n<ul>\n<li><code>a</code> and <code>b</code> swap allocators along with their data.</li>\n</ul>\n</li>\n<li>Else:\n<ul>\n<li><code>a</code> and <code>b</code> keep their own allocators.</li>\n</ul>\n</li>\n</ul>\n</li>\n</ul>\n<p>Most of those are pretty trivial. The move-plus-allocator constructor, the move-assignment, and the swap are the really interesting cases.</p>\n<h2><code>vector(vector&& other, Allocator const& alloc)</code></h2>\n<p>Okay, so <code>other</code> has a bunch of elements allocated with its own allocator. You want to move them into <code>this</code>… but there’s a catch. The elements were allocated with <code>other.get_allocator()</code>… if you move them into <code>this</code>, then they will be deallocated with <code>alloc</code>.</p>\n<p>If <code>alloc == other.get_allocator()</code>, then there’s no problem. Just move the pointer and you’re good.</p>\n<p>But if <code>alloc != other.get_allocator()</code>, then you can’t simply transfer the memory over. You need to allocate all new memory, and then move the elements from the old memory into the new memory. This, of course, might fail and throw an exception.</p>\n<p>So that’s this:</p>\n<pre><code>constexpr queue(queue&& other, Allocator const& alloc) :\n m_Alloc{alloc}\n{\n if (m_Alloc == other.m_Alloc)\n {\n // just move the pointer; cannot fail\n }\n else\n {\n // need to allocate memory, then MOVE-CONSTRUCT elements\n // from other\n //\n // afterwards, other should have its original size and\n // capacity... but all the elements should be moved-from\n }\n}\n</code></pre>\n<p>But there’s an optimization we can make. If the allocators are <em>always</em> equal, then this constructor can <em>never</em> fail. So:</p>\n<pre><code>constexpr queue(queue&& other, Allocator const& alloc)\n noexcept(std::allocator_traits<Allocator>::is_always_equal) :\n m_Alloc{alloc}\n{\n if constexpr (std::allocator_traits<Allocator>::is_always_equal)\n {\n // just move the pointer; cannot fail\n }\n else\n {\n if (m_Alloc == other.m_Alloc)\n {\n // just move the pointer; cannot fail\n }\n else\n {\n // need to allocate memory, then MOVE-CONSTRUCT elements\n // from other\n //\n // afterwards, other should have its original size and\n // capacity... but all the elements should be moved-from\n }\n }\n}\n</code></pre>\n<h2><code>auto operator=(vector&& other) noexcept(/* !!! */) -> vector&</code></h2>\n<p>Okay, now <code>this</code> has a bunch of elements, allocated with <code>this->get_allocator()</code>, and <code>other</code> has a different bunch of elements, allocated with <code>other.get_allocator()</code>.</p>\n<p>The first question to ask is whether the allocator gets moved, too, or whether <code>this</code> keeps its own allocator. For that we use <code>std::allocator_traits<Allocator>::propagate_on_container_move_assignment::value</code>.</p>\n<p>If the allocator <em>does</em> get moved, then things are pretty easy. The allocator is actually just copied, and copying allocators cannot fail. The same time we take <code>other</code>’s allocator, we can just steal its data pointer, too. And of course, clearing the data that was previously in <code>this</code> also cannot fail. (Though, in practice, for efficiency, the data usually isn’t cleared, it’s just moved over to <code>this</code>, where it will presumably be destroyed or assigned-over shortly anyway.) So it’s all simple, and no-fail.</p>\n<p>If the allocator <em>doesn’t</em> get moved, then things get more complicated. Let’s deal with that in a moment, and for now, take a look at what we have:</p>\n<pre><code>constexpr auto operator=(queue&& other)\n noexcept(std::allocator_traits<Allocator>::propagate_on_container_move_assignment /* ??? */)\n -> queue&\n{\n if constexpr (std::allocator_traits<Allocator>::propagate_on_container_move_assignment)\n {\n // basically do `this->clear()`, but in practice, the pointer to\n // `this`'s data is usually just moved over to `other`\n\n // move `other`'s allocator and data pointer over to `this`\n }\n else\n {\n // ...\n }\n\n return *this;\n}\n</code></pre>\n<p>Okay, if the allocator <em>doesn’t</em> propagate, then we need to check if the two allocators are equal.</p>\n<p>If they are equal, then there’s no problem. We can simply swap the data pointers around, because it doesn’t matter which allocated them, or which will deallocate. And swapping pointers cannot fail.</p>\n<p>If they are <em>not</em> equal, then we can’t simply swap the pointers. We actually need to make sure <code>this</code> has enough capacity, then move everything over from <code>other</code> one element at a time. Of course this could fail.</p>\n<p>So:</p>\n<pre><code>constexpr auto operator=(queue&& other)\n noexcept(std::allocator_traits<Allocator>::propagate_on_container_move_assignment /* ??? */)\n -> queue&\n{\n if constexpr (std::allocator_traits<Allocator>::propagate_on_container_move_assignment)\n {\n // basically do `this->clear()`, but in practice, the pointer to\n // `this`'s data is usually just moved over to `other`\n\n // move `other`'s allocator and data pointer over to `this`\n }\n else\n {\n if (m_alloc == other.m_alloc)\n {\n // basically do `this->clear()`, but in practice, the pointer to\n // `this`'s data is usually just moved over to `other`\n\n // move `other`'s data pointer over to `this`\n }\n else\n {\n // need to make sure this has enough capacity, then\n // MOVE-ASSIGN the elements from other into this\n //\n // take into account whether moving/copying is noexcept;\n // if not, then maybe you need to use a temporary buffer\n // to keep the strong exception guarantee\n //\n // afterwards, other should have its original size and\n // capacity... but all the elements should be moved-from\n }\n }\n\n return *this;\n}\n</code></pre>\n<p>Now, in that <code>else</code> clause, we can use the same optimization we used before. If the allocators are <em>always</em> equal, then there’s no need to waste time doing the comparison, plus we know that the whole move will never fail.</p>\n<p>Which gives us:</p>\n<pre><code>constexpr auto operator=(queue&& other)\n noexcept(std::allocator_traits<Allocator>::propagate_on_container_move_assignment\n or std::allocator_traits<Allocator>::is_always_equal)\n -> queue&\n{\n if constexpr (std::allocator_traits<Allocator>::propagate_on_container_move_assignment)\n {\n // basically do `this->clear()`, but in practice, the pointer to\n // `this`'s data is usually just moved over to `other`\n\n // move `other`'s allocator and data pointer over to `this`\n }\n else\n {\n if constexpr (std::allocator_traits<Allocator>::is_always_equal)\n {\n // basically do `this->clear()`, but in practice, the pointer to\n // `this`'s data is usually just moved over to `other`\n\n // move `other`'s data pointer over to `this`\n }\n else\n {\n if (m_alloc == other.m_alloc)\n {\n // basically do `this->clear()`, but in practice, the pointer to\n // `this`'s data is usually just moved over to `other`\n\n // move `other`'s data pointer over to `this`\n }\n else\n {\n // need to make sure this has enough capacity, then\n // MOVE-ASSIGN the elements from other into this\n //\n // take into account whether moving/copying is noexcept;\n // if not, then maybe you need to use a temporary buffer\n // to keep the strong exception guarantee\n //\n // afterwards, other should have its original size and\n // capacity... but all the elements should be moved-from\n }\n }\n }\n\n return *this;\n}\n</code></pre>\n<p>The <code>noexcept</code> clause basically says: “if the allocator is being moved (in which case, we can no-fail move the data pointer along with it; this case is the first comment block in the function above) <em><strong>OR</strong></em> if it is <em>always</em> okay to allocate and deallocate with different allocator instances (this case is the second comment block above)”. If it is only <em>sometimes</em> okay to allocate and deallocate with different allocator instances (that is, if allocators aren’t <em>always</em> equal; the third and fourth comment blocks), then we cannot <em>guarantee</em> no-fail.</p>\n<h2><code>auto swap(vector& a, vector& b) noexcept (/* !!! */) -> void</code></h2>\n<p>This case is pretty similar to the case above, with only minor tweaks (like replacing <code>propagate_on_container_move_assignment</code> with <code>propagate_on_container_swap</code>). So we can start with this:</p>\n<pre><code>constexpr auto swap(queue& other)\n noexcept(std::allocator_traits<Allocator>::propagate_on_container_swap\n or std::allocator_traits<Allocator>::is_always_equal)\n -> void\n{\n if constexpr (std::allocator_traits<Allocator>::propagate_on_container_swap)\n {\n // just swap the pointers and allocators\n }\n else\n {\n if constexpr (std::allocator_traits<Allocator>::is_always_equal)\n {\n // just swap the pointers\n }\n else\n {\n if (m_alloc == other.m_alloc)\n {\n // just swap the pointers\n }\n else\n {\n // ???\n }\n }\n }\n\n return *this;\n}\n</code></pre>\n<p>The complexity comes when you ask what happens in that last block (the one marked with the “<code>???</code>” comment). I’m not going to work through the logic here, because it’s just long and tedious, with many, many different cases to consider (are the sizes equal? if not, does the smaller one have enough capacity for all the elements in the larger? etc. etc.). I’ll just tell you the punch line: it turns out there is no way, in general, to swap elements from one allocator’s arena into another’s. (You can do things that <em>look</em> kinda like swapping when the dust settles, like move-constructing <code>a</code>’s elements into memory allocated by <code>b</code> and move-constructing <code>b</code>’s elements into memory allocated by <code>a</code>, but that’s not <em>actually</em> swapping since the elements in both queues are now totally newly-constructed… not simply swapped over.)</p>\n<p>That’s why <code>std::vector</code> doesn’t even bother to handle that case; it’s just undefined behaviour.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-18T21:11:20.687",
"Id": "257369",
"ParentId": "256677",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "257088",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T11:22:14.330",
"Id": "256677",
"Score": "0",
"Tags": [
"c++",
"beginner",
"queue"
],
"Title": "dynamic queue implementation in C++"
}
|
256677
|
<p>I have a <a href="https://github.com/staticdev/git-portfolio" rel="nofollow noreferrer">CLI lib</a> to automate batch operations on GitHub with many use cases: create issue, merge PR, delete branch... Since they all operate in a similar fashing regarding execution and output, I created a parent class GhUseCase as follows:</p>
<pre class="lang-py prettyprint-override"><code>class GhUseCase:
# ...other methods
def action(self, github_repo: str, *args: Any, **kwargs: Any) -> None:
"""Execute some action in a repo."""
raise NotImplementedError # pragma: no cover
def execute(
self, *args: Any, **kwargs: Any
) -> Union[res.ResponseFailure, res.ResponseSuccess]:
"""Execute GitHubUseCase."""
if self.github_repo:
self.action(self.github_repo, *args, **kwargs)
else:
for github_repo in self.config_manager.config.github_selected_repos:
self.action(github_repo, *args, **kwargs)
return self.generate_response()
</code></pre>
<p>Basically, each use cases inherits this class and implements <code>action</code> method. Eg. overload 1 (delete branch):</p>
<pre class="lang-py prettyprint-override"><code>import git_portfolio.use_cases.gh as gh
class GhDeleteBranchUseCase(gh.GhUseCase):
"""Github delete branch use case."""
def action(self, github_repo: str, branch: str) -> None: # type: ignore[override]
"""Delete branches."""
github_service_method = "delete_branch_from_repo"
self.call_github_service(github_service_method, github_repo, branch)
</code></pre>
<p>Eg. overload 2 (create issue) with another signature:</p>
<pre class="lang-py prettyprint-override"><code>import git_portfolio.domain.issue as i
import git_portfolio.use_cases.gh as gh
class GhCreateIssueUseCase(gh.GhUseCase):
"""Github create issue use case."""
def action( # type: ignore[override]
self, github_repo: str, issue: i.Issue
) -> None:
"""Create issues."""
github_service_method = "create_issue_from_repo"
self.call_github_service(github_service_method, github_repo, issue)
</code></pre>
<p>Full use-cases code can be found <a href="https://github.com/staticdev/git-portfolio/tree/duplicated-code-github-use-cases/src/git_portfolio/use_cases" rel="nofollow noreferrer">in this branch</a> (files with names stating in <code>gh</code>).</p>
<p>The problem is that each use case's <code>action</code> has a different list of parameters and I could not find a proper way to declare the type annotations without having <code>type: ignore[override]</code> errors on Mypy.</p>
<p>Any ideas of how to make this better and properly annotated?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T14:28:42.093",
"Id": "506787",
"Score": "0",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T15:18:23.513",
"Id": "506792",
"Score": "0",
"body": "Fair enough, I tried to put a more specific title then."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T09:09:32.243",
"Id": "507309",
"Score": "0",
"body": "@FMc the problem is that every `action` needs some specific parameters regarding their use case. In the two examples I put you can see that, delete branch needs the branch name and create issue, all the issue fields. I am not sure I understood your suggestion, you suggest that I create one `dataclass` or `attrs` class with all parameters for all actions or what?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T08:42:49.913",
"Id": "507561",
"Score": "0",
"body": "So if I have 20 use cases with 40 different parameters I create a class with all 50 parameters? I think there should be a more modular solution in that case to make it more maintainable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-23T14:53:06.420",
"Id": "508734",
"Score": "0",
"body": "I don't understand what you are trying to type check. `execute()` accepts arguments of any type (signature `[Any, Any]`), so there isn't anything to type check there. And it then uses `self.action(*args, **kwargs)` to call an instance method, so there isn't any type information to check there either. The types in `action()` could be used to type check the code in `action()` itself, but we don't know what args `call_github_service()` takes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-29T07:33:07.017",
"Id": "510317",
"Score": "0",
"body": "I want to type-annotate the `action()` method on the parent class so that I don't have to ignore type-checking on the classes that inherit `GhUseCase`."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T11:56:51.647",
"Id": "256679",
"Score": "0",
"Tags": [
"python",
"python-3.x",
"git",
"type-safety"
],
"Title": "Proper Python type-annotation for variable parameters signature of inherited method overloads"
}
|
256679
|
<p>Hi I've finished my code but I want to make it shorter and more OOP. Can anyone help me out?</p>
<p>The question The cost to become a member of a fitness center is as follows:</p>
<p>a. the Senior citizens discount is 30%;<br />
b. if the membership is bought and paid for 12 or more months in advance, the discount is 15%;<br />
c. if more than 5 personal training sessions are purchased, the discount on each session is 20%.</p>
<p>Write a menu driven program that determines the cost of a new membership. Your program must contain a method that displays the general information about the fitness center and its charges, a method to get all the necessary information to determine the membership cost, and a method to determine the membership cost.</p>
<p>Use appropriate parameters to pass information in and out of a method.</p>
<pre class="lang-java prettyprint-override"><code>package com.diit;
import java.util.Scanner;
public class Question4 {
public static void main(String[] args) {
//Scanner Object
Scanner in = new Scanner(System.in);
information();
input();
price();
}
public static void information() {
System.out.println("\n\nWelcome to Fitness Centre!");
System.out.println("--------------------------------------------\n");
System.out.println("If you are a senior citizen, then you are eligible for a\ndiscount of 30% of the regular membership price");
System.out.println("--------------------------------------------\n");
System.out.println("If you buy membership for twelve months and pay today, the discount is 15%");
System.out.println("--------------------------------------------\n");
System.out.println("If you purchased more than 5 personal training sessions\n,the discount of each session is 20%");
System.out.println("\n--------------------------------------------\n");
}
public static void input() {
Scanner in = new Scanner(System.in);
System.out.println("Please fill in your information");
System.out.print("Please enter your name: ");
String name = in.nextLine();
System.out.println("Welcome " + name + "to our Fitness Centre!");
}
public static void price() {
Scanner in = new Scanner(System.in);
//Declarations
int age, twelve = 0, sessions = 0;
double total, price, price2, months = 0, months2;
System.out.println("Please enter your age: ");
age = in.nextInt();
if (age >= 0 && age <= 60) {
System.out.println("Do you want to pay for you membership 12 months or more in advance? (1 for YES, 2 for NO");
twelve = in.nextInt();
if (twelve == 2) {
System.out.println("How many months do you want to pay for?");
System.out.println("The original price per month is RM140");
months = in.nextInt();
System.out.println("How many training sessions do you want to purchase (0-10)");
System.out.println("The original price per sessions is RM85");
sessions = in.nextInt();
if (sessions > 5) {
price = 68;
price2 = price * sessions;
months2 = months * 140;
total = months2 + price2;
System.out.println("Your total price in MYR is RM" + total);
}
if (sessions < 5 && sessions >= 0) {
price = 85;
price2 = price * sessions;
months2 = months * 140;
total = months2 + price2;
System.out.println("Your total price in MYR is RM" + total);
}
} else if (twelve == 1) {
System.out.println("How many months do you want to pay for?");
System.out.println("The original price per month is RM140");
months = in.nextInt();
System.out.println("How many training sessions do you want to purchase (0-10)");
System.out.println("The original price per sessions is RM85");
sessions = in.nextInt();
if (sessions > 5) {
price = 68;
price2 = price * sessions;
months2 = months * 119;
total = months2 + price2;
System.out.println("Your total price in MYR is RM" + total);
}
if (sessions < 5 && sessions >= 0) {
price = 85;
price2 = price * sessions;
months2 = months * 119;
total = months2 + price2;
System.out.println("Your total price in MYR is RM" + total);
}
}
}
else if (age >= 60) {
System.out.println("Congratulations! You are entitled to a 30% discount.");
System.out.println("Do you want to pay for you membership 12 months or more in advance? (1 for YES, 2 for NO");
twelve = in.nextInt();
if (twelve == 2) {
System.out.println("How many months do you want to pay for?");
System.out.println("The original price per month is RM140");
months = in.nextInt();
System.out.println("How many training sessions do you want to purchase (0-10)");
System.out.println("The original price per sessions is RM85");
sessions = in.nextInt();
if (sessions > 5) {
price = 68;
price2 = price * sessions;
months2 = months * 98;
total = months2 + price2;
System.out.println("Your total price in MYR is RM" + total);
}
if (sessions < 5 && sessions >= 0) {
price = 85;
price2 = price * sessions;
months2 = months * 98;
total = months2 + price2;
System.out.println("Your total price in MYR is RM" + total);
}
if (sessions < 0) {
System.out.println("Invalid!");
}
}
if (twelve == 1) {
System.out.println("How many months do you want to pay for?");
System.out.println("The original price per month is RM140");
months = in.nextInt();
System.out.println("How many training sessions do you want to purchase (0-10)");
System.out.println("The original price per sessions is RM85");
sessions = in.nextInt();
if (sessions > 5) {
price = 68;
price2 = price * sessions;
months2 = months * 83.3;
total = months2 + price2;
System.out.println("Your total price in MYR is RM" + total);
}
if (sessions < 5 && sessions >= 0) {
price = 85;
price2 = price * sessions;
months2 = months * 83.3;
total = months2 + price2;
System.out.println("Your total price in MYR is RM" + total);
}
if (sessions < 0) {
System.out.println("Invalid!");
}
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T17:16:59.297",
"Id": "506812",
"Score": "2",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T04:46:36.877",
"Id": "506860",
"Score": "1",
"body": "Do the gym discounts stack?"
}
] |
[
{
"body": "<p>You had the right idea. A Java method is an encapsulation of code to produce one output.</p>\n<p>I reworked your code and created 10 methods, not including the main method. Each method does one thing.</p>\n<p>I removed all but one instance of <code>Scanner</code>. It's not a good idea to have more than one <code>System.in</code> <code>Scanner</code>. I pass that <code>Scanner</code> instance to all the methods that read from the console.</p>\n<p>Method names should be a verb-noun combination, like <code>printInformation</code> or <code>processMember</code>.</p>\n<p>I created two methods with the same name, <code>calculateTotal</code>. Since the two methods have different input parameter signatures, there's no confusion on the compiler's part. Hopefully, you'll see the difference.</p>\n<p>I tested your code a few times, but check my work to make sure I got the discount calculations correct.</p>\n<p>Here's the complete runnable code.</p>\n<pre><code>import java.util.Scanner;\n\npublic class Question4 {\n\n public static void main(String[] args) {\n //Scanner Object\n Scanner in = new Scanner(System.in);\n new Question4().processMember(in);\n in.close();\n }\n \n public void processMember(Scanner in) {\n printInformation();\n double total = processInformation(in);\n String formattedTotal = String.format("%,.2f", total);\n System.out.println("Your total price in MYR is RM" + formattedTotal);\n }\n\n private void printInformation() {\n System.out.println("\\nWelcome to Fitness Centre!\\n");\n System.out.println("--------------------------------------------\\n");\n System.out.println("If you are a senior citizen, then you are "\n + "eligible for a\\ndiscount of 30% of the regular "\n + "membership price");\n System.out.println("--------------------------------------------\\n");\n System.out.println("If you buy a membership for twelve months "\n + "or more and pay today, the discount is 15%");\n System.out.println("--------------------------------------------\\n");\n System.out.println("If you purchased more than 5 personal training "\n + "sessions,\\nthe discount of each session is 20%\\n");\n System.out.println("--------------------------------------------\\n");\n }\n\n private double processInformation(Scanner in) {\n readName(in);\n int age = readAge(in);\n boolean advance = readAdvance(in);\n int months = readMonths(in, advance);\n int sessions = readSessions(in);\n return calculateTotal(age, advance, months, sessions);\n }\n \n private void readName(Scanner in) {\n System.out.println("Please fill in your information");\n System.out.print("Please enter your name: ");\n String name = in.nextLine();\n System.out.println("Welcome " + name + " to our Fitness Centre!");\n }\n\n private int readAge(Scanner in) {\n System.out.print("Please enter your age: ");\n int age = in.nextInt();\n in.nextLine();\n \n if (age >= 60) {\n System.out.println("Congratulations! You are entitled "\n + "to a 30% discount.");\n }\n \n return age;\n }\n\n private boolean readAdvance(Scanner in) {\n System.out.print("Do you want to pay for you membership 12 months "\n + "or more in advance? (Y for YES, N for NO) ");\n String response = in.nextLine();\n boolean advance = Character.toLowerCase(response.charAt(0)) == 'y';\n \n return advance;\n }\n\n private int readMonths(Scanner in, boolean advance) {\n int months;\n do {\n System.out.println("How many months do you want to pay for?");\n System.out.println("The original price per month is RM140");\n months = in.nextInt();\n in.nextLine();\n } while (months < 0 || (advance && months < 12));\n return months;\n }\n\n private int readSessions(Scanner in) {\n int sessions;\n do {\n System.out.println("How many training sessions do you "\n + "want to purchase (0-10)");\n System.out.println("The original price per sessions is RM85");\n sessions = in.nextInt();\n in.nextLine();\n } while (sessions < 0 || sessions > 10);\n \n return sessions;\n }\n \n private double calculateTotal(int age, boolean advance, \n int months, int sessions) {\n double total;\n \n if (age >= 0 && age < 60) {\n if (advance) {\n total = calculateTotal(sessions, 85, months, 140, 15);\n } else {\n total = calculateTotal(sessions, 85, months, 140, 0);\n }\n } else { \n total = calculateTotal(sessions, 85, months, 140, 30); \n }\n \n return total;\n }\n \n private double calculateTotal(int sessions, int sessionsPrice, \n int months, int membershipPrice, int discount) {\n if (sessions < 5 && sessions >= 0) {\n double sessionsTotal = sessionsPrice * sessions;\n double membershipTotal = membershipPrice * months * \n (1.0 - discount * 0.01);\n return sessionsTotal + membershipTotal;\n } else {\n double sessionsTotal = sessionsPrice * sessions * 0.8;\n double membershipTotal = membershipPrice * months * \n (1.0 - discount * 0.01);\n return sessionsTotal + membershipTotal;\n }\n }\n \n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T03:18:35.370",
"Id": "506856",
"Score": "0",
"body": "Hi sir what does this line of code mean? Sorry I am a beginner \n\nString formattedTotal = String.format(\"%,.2f\", total);"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T06:03:04.483",
"Id": "506868",
"Score": "1",
"body": "Java has a complete [API specification](https://docs.oracle.com/javase/8/docs/api/index.html) that describes in detail all of the classes and methods that make up the Java platform. The format method of String in this case formats a double into a String with a decimal point and comma every three digits."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T20:59:28.753",
"Id": "507191",
"Score": "0",
"body": "@Aaron: as a complete beginner it might be a good idea to go your way through the Java Tutorials: https://docs.oracle.com/javase/tutorial/"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T02:31:33.640",
"Id": "256706",
"ParentId": "256682",
"Score": "3"
}
},
{
"body": "<p>One thing important to me is to separate the presentation part (input and display) with your business rules. It will be easier to test (and better, you can even do TDD ;) ).\nI wrote this, it is not complete, all of your business rules are not covered, but I think you can get the idea : gather all the info you need from the UI to compute the price, and then call the Pricer.</p>\n<p>First, the input reader (inspired by the Gilbert's answer) :</p>\n<pre><code>public class InputReader {\n\n private int age = 0;\n private int months = 0;\n private int sessions = 0;\n\n private final Scanner scanner;\n\n public InputReader(Scanner scanner) {\n this.scanner = scanner;\n }\n\n private Order processMember() {\n informationMessage();\n welcome();\n readAge();\n readMonths();\n readSessions();\n return new Order(age, months, sessions);\n }\n\n private void informationMessage() {\n outWithNewLine("");\n outWithNewLine("");\n outWithNewLine("Welcome to Fitness Centre!");\n outSeparator();\n outWithNewLine("If you are a senior citizen, then you are eligible for a");\n outWithNewLine("discount of 30% of the regular membership price");\n outSeparator();\n outWithNewLine("If you buy membership for twelve months and pay today, the discount is 15%");\n outSeparator();\n outWithNewLine("If you purchased more than 5 personal training sessions");\n outWithNewLine(",the discount of each session is 20%");\n outSeparator();\n }\n\n private void welcome() {\n outWithNewLine("Please fill in your information");\n out("Please enter your name: ");\n String name = scanner.nextLine();\n outWithNewLine("Welcome " + name + " to our Fitness Centre!");\n }\n\n private void readAge() {\n outWithNewLine("Please enter your age: ");\n age = scanner.nextInt();\n scanner.nextLine();\n if (age >= 60) {\n outWithNewLine("Congratulations! You are entitled to a 30% discount.");\n }\n }\n\n private void readMonths() {\n while (months <= 0) {\n outWithNewLine("How many months do you want to pay for?");\n outWithNewLine("The original price per month is RM140");\n months = scanner.nextInt();\n scanner.nextLine();\n }\n }\n\n private void readSessions() {\n while(sessions <= 0 || sessions > 10) {\n outWithNewLine("How many training sessions do you want to purchase (0-10)");\n outWithNewLine("The original price per sessions is RM85");\n sessions = scanner.nextInt();\n scanner.nextLine();\n }\n }\n \n private void outWithNewLine(String content) {\n System.out.println(content);\n }\n\n private void out(String content) {\n System.out.print(content);\n }\n\n private void outSeparator() {\n outWithNewLine("--------------------------------------------");\n }\n\n}\n</code></pre>\n<p>Then, a Pricer that computes the price :</p>\n<pre><code>public class Pricer {\n private static final BigDecimal ONE_SESSION_PRICE = BigDecimal.valueOf(85L);\n private static final BigDecimal MEMBERSHIP_FOR_ONE_MONTH = BigDecimal.valueOf(140L);\n private static final BigDecimal SESSION_DISCOUNT = BigDecimal.valueOf(0.15d);\n private static final BigDecimal SENIOR_DISCOUNT = BigDecimal.valueOf(0.3);\n\n private final int age;\n private final BigDecimal nbMonthsToPay;\n private final BigDecimal nbSession;\n \n public Pricer(Order order) {\n this.age = order.age;\n this.nbMonthsToPay = new BigDecimal(order.months);\n this.nbSession = new BigDecimal(order.sessions);\n }\n\n public String membershipAmount() {\n BigDecimal membershipAmount = computeMembershipPrice();\n BigDecimal sessionAmount = computeSessionPrice();\n return membershipAmount.add(sessionAmount).toString();\n }\n\n private BigDecimal computeSessionPrice() {\n BigDecimal sessionAmount = ONE_SESSION_PRICE.multiply(nbSession);\n if (nbSession.intValue() >= 6) {\n return sessionAmount.subtract(sessionAmount.multiply(SESSION_DISCOUNT));\n }\n return sessionAmount;\n }\n\n private BigDecimal computeMembershipPrice() {\n BigDecimal membership = MEMBERSHIP_FOR_ONE_MONTH.multiply(nbMonthsToPay);\n if (age >= 60) {\n return membership.subtract(membership.multiply(SENIOR_DISCOUNT));\n }\n return membership;\n }\n}\n</code></pre>\n<p>The Order (I put public fields because the class is immutabe) :</p>\n<pre><code>public class Order {\n public final int age;\n public final int months;\n public final int sessions;\n\n public Order(int age, int months, int sessions) {\n this.age = age;\n this.months = months;\n this.sessions = sessions;\n }\n}\n</code></pre>\n<p>The main method :</p>\n<pre><code>public static void main(String[] args) {\n Scanner scanner = new Scanner(System.in);\n Order order = new InputReader(scanner).processMember();\n String membershipAmount = new Pricer(order).membershipAmount();\n System.out.println("Your total price in MYR is RM" + membershipAmount);\n scanner.close();\n}\n</code></pre>\n<p>I hope it helps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T20:56:31.187",
"Id": "507190",
"Score": "0",
"body": "I don't think your answer is of any use for the Questioner. It does not explain the concept you want to show and how your code snipped fits into that concept."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T21:03:45.497",
"Id": "507192",
"Score": "0",
"body": "Hello, sad to hear that, but I am ready to improve my answer. What do you think I can add to make it better ? A call to the pricer ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T21:32:06.583",
"Id": "507198",
"Score": "1",
"body": "The Questioner provided a [SSCCE](http://www.sscce.org/) so you should do the same, maybe not completely covering all the original code but enough to show your, that the output of your code is the same as the original and the TO can play with it..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T06:17:47.557",
"Id": "507210",
"Score": "0",
"body": "Thank you for your answer, you are right, I see what you mean. I have improved my answer and I think it's more useful now."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T13:39:33.107",
"Id": "256722",
"ParentId": "256682",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T15:05:55.157",
"Id": "256682",
"Score": "-1",
"Tags": [
"java"
],
"Title": "How to make my code more OOP?"
}
|
256682
|
<p>I attempted to implement a stack based on functional programming. Specifically, the idea is to allow structural sharing to reduce space usage. To do structural sharing, I added a unique key for the stack.</p>
<p>This stack data structure allows deletion in two ways. First, the stack might be popped. Second, the constructor takes a bool that is true when it is removed.</p>
<pre><code>
"""
stack module
A functional programming based stack
This stack has a unique key which allows part of one stack to use memory from another stack
Also, this stack uses sentenails rather than None for simplicity in looping
"""
class Stack:
def __init__(self, key, val, is_removed, length, below_stack = None):
"""
average time: O(1)
average space: O(1)
amortized time: O(1)
amortized space: O(1)
:param key: a unique key for the stack object
:param val: the value stored in stack
:param is_removed: if this has been marked as deleted
:param length: the number of elements below
:param below_stack: the stack object below, None results ina senentail
"""
self.__key = key
self.__val = val
self.__is_removed = is_removed
self.__length = length
if below_stack:
self.__below_stack = below_stack
else:
self.__below_stack = self
def is_removed(self):
"""
average time: O(1)
average space: O(1)
amortized time: O(1)
amortized space: O(1)
:return: if this stack has been marked as removed
"""
return self.__is_removed
def val(self):
"""
average time: O(1)
average space: O(1)
amortized time: O(1)
amortized space: O(1)
:return: val part of the stack
"""
return self.__val
def key(self):
"""
average time: O(1)
average space: O(1)
amortized time: O(1)
amortized space: O(1)
:return: key of the stack
"""
return self.__key
def popped(self):
"""
average time: O(1)
average space: O(1)
amortized time: O(1)
amortized space: O(1)
:return: stack which has the bottom poppped off
"""
return Stack(self.__key, self.__val, self.__is_removed, self.__length, None)
def __len__(self):
"""
average time: O(1)
average space: O(1)
amortized time: O(1)
amortized space: O(1)
:return: the length of this stack
"""
return self.__length
def __eq__(self, other):
"""
average time: O(1)
average space: O(1)
amortized time: O(1)
amortized space: O(1)
:param other: another stack, or this one
:return: if these have the same key
"""
return self.__key == other.__key
def __ne__(self, other):
"""
average time: O(1)
average space: O(1)
amortized time: O(1)
amortized space: O(1)
:param other: another stack or this one
:return: if these stacks do Not equal each other
"""
return not self == other
def append(self, the_stack):
"""
average time: O(1)
average space: O(1)
amortized time: O(1)
amortized space: O(1)
:param the_stack: the stack to append
:return: a new stack with this one as its bottom stack
"""
if the_stack.__is_removed:
return self
if self.__below_stack == self:
return Stack(self.__key, self.__val, self.__is_removed, self.__length + 1, self.__below_stack)
else:
return Stack(self.__key, self.__val, self.__is_removed, self.__length, self.__below_stack)
def __iter__(self):
"""
:return: yields the stack elements below if not marked for delete
"""
if not self.__is_removed:
yield self
if not self == self.__below_stack and not self.__below_stack.__is_removed:
yield self.__below_stack
def test_is_removed():
assert Stack(0, 'a', False, 1, None).is_removed() == False
assert Stack(2, 'a', True, 1, None).is_removed() == True
def test_val():
assert Stack(0, 'e', False, 1, None).val() == 'e'
assert Stack(1, 'b', False, 1, None).val() == 'b'
def test_key():
assert Stack(0, 'c', False, 1, None).key() == 0
assert Stack(1, 'a', False, 1, None).key() == 1
def test_popped():
below = Stack(1, 'a', False, 1, None)
above = Stack(3, 'b', False, 1, below)
popped = Stack(3, 'b', False, 1, None)
assert above.popped() == above
def test_len():
assert len(Stack(1, 'a', False, 1, None)) == 1
assert len(Stack(2, 'b', False, 2, None)) == 2
def test_equals():
assert not Stack(0, 'a', 1, False, None) == Stack(1, 'a', 1, False, None)
assert Stack(1, 'b', 0, False, None) == Stack(1, 'b', 0, False, None)
def test_not_equals():
assert not Stack(-1, 'z', 1, False, None) != Stack(-1, 'z', 1, False, None)
assert Stack(0, 'a', 1, False, None) != Stack(1, 'a', 1, False, None)
def test_append():
first = Stack(1, 'b', False, 1, None)
to_add = Stack(2, 'c', True, 1, None)
assert first.append(to_add) == first
second_add = Stack(4, 'c', False, 0, None)
expected = Stack(1, 'b', False, 0, second_add)
assert first.append(second_add) == expected
def test_iter():
#key, val, is_removed, length, below_stack = None)
top = Stack(0, 'a', False, 1, None)
vec = [s for s in top]
assert vec[0] == top
new_bottom = Stack(1, 'b', False, 1, None)
new_top = Stack(-1, 'c', False, 2, new_bottom)
new_vec = [s for s in new_top]
assert new_vec[0] == new_top
assert new_vec[1] == new_bottom
def main():
test_val()
test_key()
test_popped()
test_len()
test_equals()
test_not_equals()
test_append()
test_iter()
print('hello world')
if __name__ == '__main__':
main()
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T16:28:36.010",
"Id": "256684",
"Score": "0",
"Tags": [
"python-3.x",
"functional-programming"
],
"Title": "Python Stack Datastructure"
}
|
256684
|
<p>"Find minimum path sum" in a 2D grid, is a very popular question which is solved by dynamic programming. But what if instead of the minimum sum value, we return all the actual paths that lead to the minimum sum path? This was an interview question which has been puzzling me.</p>
<p>The original problem is :</p>
<p>Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.</p>
<p>Ex:</p>
<pre><code>Input: grid =
[[1,3,1]
,[1,5,1]
,[4,2,1]]
output: 7
Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.
</code></pre>
<p>But instead of 7 I want to return [1,3,1,1,1] and all other paths that lead to sum of sum (in this case there is only one path). My current solution has exponential time complexity which is not good. Does anyone has a good solution to this problem?</p>
<p>My current solution:</p>
<pre><code>class Solution {
void DFS(vector<vector<int>>& grid, vector<vector<int>>& dp, int r, int c, vector<int> path, vector<vector<int>>& result, int sum){
int R = grid.size();
int C = grid[0].size();
path.push_back(grid[r][c]);
sum += grid[r][c];
if(r == R -1 && c == C -1){
result.push_back(path);
return;
}
int min_right = INT_MAX;
if(c < C - 1) {
min_right = dp[r][c + 1] + sum;
}
int min_down = INT_MAX;
if(r < R - 1){
min_down = dp[r + 1][c] + sum;
}
if(min_right < min_down){
DFS(grid, dp, r, c + 1, path, result, sum);
}
else if(min_right > min_down){
DFS(grid, dp, r + 1, c, path, result, sum);
}
else{
DFS(grid, dp, r, c + 1, path, result, sum);
DFS(grid, dp, r + 1, c, path, result, sum);
}
}
public:
vector<vector<int>> minPathSum(vector<vector<int>>& grid) {
if(grid.size() == 0){
return 0;
}
int R = grid.size();
int C = grid[0].size();
vector<vector<int>> dp (R, vector<int>(C, 0));
//O(m*n)
for(int i = R - 1; i >= 0; i--){
for(int j = C - 1; j >= 0; j--){
int min_right = INT_MAX;
if(j < C - 1){
min_right = dp[i][j + 1];
}
int min_down = INT_MAX;
if(i < R - 1){
min_down = dp[i + 1][j];
}
int cur_min = min(min_down, min_right);
if(cur_min == INT_MAX) {
cur_min = 0;
}
dp[i][j] = grid[i][j] + cur_min;
}
}
vector<vector<int>> result;
vector<int> path;
int sum;
//O(2^(m+n))
DFS(grid, dp, 0, 0, path, result, sum);
return result;
}
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T22:56:16.800",
"Id": "506837",
"Score": "0",
"body": "You should be able to fine an O(n×m) solution, indeed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T05:45:00.443",
"Id": "506865",
"Score": "0",
"body": "Shouldn't this use Dijkstra's algorithm? I cannot see a DP solution for it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T23:11:10.043",
"Id": "506943",
"Score": "0",
"body": "@AlexisWilke, that is my question. How do you find the solution in O(n*m)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T23:31:51.987",
"Id": "506944",
"Score": "0",
"body": "@Athn forgive my lack of familiarity with the code - is there a specific language used? e.g. c++? If so, please [edit] and add any appropriate tags - including specific language version tags if they exist"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T05:04:37.047",
"Id": "506951",
"Score": "1",
"body": "Please tag with the language used for coding."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T05:04:53.403",
"Id": "506952",
"Score": "0",
"body": "`My current solution has exponential time complexity`/`//O(2^(m+n))` What is this supposed to mean, starting with two obvious parameters for problem size mentioned in the problem description? Can you give an upper bound on the length of the paths to any given element? How many paths to this element are there? Does any path get considered more than once?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T05:08:09.807",
"Id": "506953",
"Score": "0",
"body": "`I want to return [1,3,1,1,1]` You don't - consider a grid filled with 1: You want [r, r, d, d] or something else uniquely specifying paths."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T05:09:45.963",
"Id": "506954",
"Score": "0",
"body": "`all other paths that lead to sum of sum` *all other paths with minimum sum*?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T08:38:12.970",
"Id": "506971",
"Score": "0",
"body": "(The return value is somewhat interesting, but neither `7` nor `[1,3,1,1,1]`.)"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T18:19:37.473",
"Id": "256688",
"Score": "2",
"Tags": [
"algorithm",
"interview-questions"
],
"Title": "Find all of the paths that lead to the minimum sum"
}
|
256688
|
<p>I wrote a 2048 game in JavaScript with an object-oriented paradigm. The game board is presented with a two-dimensional array and each tile holds an integer.</p>
<p>Here is the implementation:</p>
<pre class="lang-js prettyprint-override"><code>class Game {
SIZE = 4
constructor() {
this.board = Array.from({ length: this.SIZE * this.SIZE }, () => 0).reduce(
(arrays, curr) => {
const lastArray = arrays[arrays.length - 1]
if (lastArray.length < this.SIZE) lastArray.push(curr)
else arrays.push([curr])
return arrays
},
[[]]
)
this.isWin = false
this._init()
}
_init() {
const pickedTiles = this._randomlyPick(2)
for (const [row, col] of pickedTiles) {
this.board[row][col] = Game.generateTile()
}
}
static generateTile() {
if (Math.random() > 0.5) return 2
return 4
}
_getEmptyTiles() {
const emptyTiles = []
for (let row = 0; row < this.SIZE; row++) {
for (let col = 0; col < this.SIZE; col++) {
if (this.board[row][col] === 0) emptyTiles.push([col, row])
}
}
return emptyTiles
}
_randomlyPick(numOfItems) {
const emptyTiles = this._getEmptyTiles()
for (let i = 0; i < numOfItems; i++) {
const toSwap = i + Math.floor(Math.random() * (emptyTiles.length - i))
;[emptyTiles[i], emptyTiles[toSwap]] = [emptyTiles[toSwap], emptyTiles[i]]
}
return emptyTiles.slice(0, numOfItems)
}
spawn() {
// randomly spawn empty tiles with 2 or 4
const [emtpyTile] = this._randomlyPick(1)
this.board[emtpyTile[0]][emtpyTile[1]] = Game.generateTile()
}
play(dir) {
if (this.canPlay()) {
switch (dir) {
case Game.moveUp:
this._mergeUp()
break
case Game.moveRight:
this._mergeRight()
break
case Game.moveLeft:
this._mergeLeft()
break
case Game.moveDown:
this._mergeDown()
break
}
this.spawn()
return true
}
return false
}
checkIsWin() {
return this.isWin
}
static peek(array) {
return array[array.length - 1]
}
static zip(arrays) {
const result = []
for (let i = 0; i < arrays[0].length; ++i) {
result.push(arrays.map((array) => array[i]))
}
return result
}
_mergeRowRight(sparseRow) {
const row = sparseRow.filter((x) => x !== 0)
const result = []
while (row.length) {
let value = row.pop()
if (Game.peek(row) === value) value += row.pop()
result.unshift(value)
}
while (result.length < 4) result.unshift(0)
return result
}
_mergeRowLeft(row) {
return this._mergeRowRight([...row].reverse()).reverse()
}
_mergeUp() {
this.board = Game.zip(Game.zip(this.board).map(row => this._mergeRowLeft(row)))
}
_mergeDown() {
this.board = Game.zip(Game.zip(this.board).map(row => this._mergeRight(row)))
}
_mergeRight() {
this.board = this.board.map((row) => this._mergeRowRight(row))
}
_mergeLeft() {
this.board = this.board.map((row) => this._mergeRowLeft(row))
}
canPlay() {
const dirs = [
[0, 1],
[1, 0],
[-1, 0],
[0, -1],
]
const visited = new Set()
for (let row = 0; row < this.SIZE; row++) {
for (let col = 0; col < this.SIZE; col++) {
if (visited.has([row, col].toString())) continue
const tile = this.board[row][col]
if (tile === 2048) {
this.isWin = true
return false
}
if (tile === 0) return true
for (const [dx, dy] of dirs) {
if (this.board[row + dx]?.[col + dy] === tile) return true
}
visited.add([row, col].toString())
}
}
return false
}
}
Game.moveUp = Symbol('moveUp')
Game.moveDown = Symbol('moveUp')
Game.moveLeft = Symbol('moveUp')
Game.moveRight = Symbol('moveUp')
const game = new Game()
console.log(game.board);
game.play(Game.moveUp)
console.log(game.board);
game.play(Game.moveRight)
console.log(game.board);
</code></pre>
<p>Any feedback is welcomed. Specifically, I would like to know:</p>
<ol>
<li>Is it idiomatic in OO to use static methods to store util functions such as <code>zip</code> to flip the board along its diagonal?</li>
<li>Is there a better way to structure the class? I feel like I am not doing a great job at dividing some of the logic of different actions.</li>
<li>Is there any specific design pattern that I can use to improve the class?</li>
<li>Lastly, I am using <code>symbol</code> to present the direction of the move the user can make and attach them as the instance variable to the class. Again I am not sure if this is idiomatic in OO since I am kinda new to this paradigm.</li>
</ol>
|
[] |
[
{
"body": "<h2>Initial feedback</h2>\n<p>The code looks quite clean. It is a very easy to read. There are only a few suggestions, which I have ingrained in the question responses below.</p>\n<h2>Question responses</h2>\n<ol>\n<li><em>Is it idiomatic in OO to use static methods to store util functions such as zip to flip the board along its diagonal.</em></li>\n</ol>\n<p>Yes AFAIK that is true.</p>\n<blockquote>\n<p>Static methods are often used to create utility functions for an application, whereas static properties are useful for caches, fixed-configuration, or any other data you don't need to be replicated across instances.<sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#static_methods_and_properties\" rel=\"nofollow noreferrer\">1</a></sup></p>\n</blockquote>\n<ol start=\"3\">\n<li><p><em>Is there any specific design pattern that I can use to improve the class?</em></p>\n<p>It appears that some of the code uses functional programming techniques - e.g. in the static <code>zip</code> method the <code>map()</code> array method is used.</p>\n<blockquote>\n<pre><code> static zip(arrays) {\n const result = []\n for (let i = 0; i < arrays[0].length; ++i) {\n result.push(arrays.map((array) => array[i]))\n }\n return result\n }\n</code></pre>\n</blockquote>\n<p>That could be taken one step further to use <code>map</code> instead of the outer <code>for</code> loop:</p>\n<pre><code>static zip(arrays) {\n return arrays[0].map((firstCol, i) => arrays.map(array => array[i]));\n}\n</code></pre>\n<p>There are some places where functional programming is used when it doesn't need to be - for example, in the constructor:</p>\n<blockquote>\n<pre><code>this.board = Array.from({ length: this.SIZE * this.SIZE }, () => 0).reduce(\n</code></pre>\n</blockquote>\n<p>This could simply use the Array method <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill\" rel=\"nofollow noreferrer\"><code>.fill()</code></a></p>\n<pre><code>this.board = Array(this.SIZE * this.SIZE).fill(0).reduce(\n</code></pre>\n<p>And the multiplication could be simpler using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Exponentiation\" rel=\"nofollow noreferrer\">ES6 exponentiation operator</a></p>\n<pre><code>this.board = Array(this.SIZE ** 2).fill(0).reduce(\n</code></pre>\n</li>\n<li><p><em>Lastly, I am using symbol to present the direction of the move the user can make and attach them as the instance variable to the class. Again I am not sure if this is idiomatic in OO since I am kinda new to this paradigm.</em></p>\n<p>I honestly haven't seen much usage of <code>Symbol</code> but perhaps that is likely only because it is a newer feature introduced with ES6 <sup><a href=\"https://www.freecodecamp.org/news/how-did-i-miss-javascript-symbols-c1f1c0e1874a/\" rel=\"nofollow noreferrer\">2</a></sup>.</p>\n<p>While they are not technically invalid, perhaps these three lines should be updated</p>\n<blockquote>\n<pre><code>Game.moveDown = Symbol('moveUp')\nGame.moveLeft = Symbol('moveUp')\nGame.moveRight = Symbol('moveUp')\n</code></pre>\n</blockquote>\n<p>like this:</p>\n<pre><code>Game.moveDown = Symbol('moveDown')\nGame.moveLeft = Symbol('moveLeft')\nGame.moveRight = Symbol('moveRight')\n</code></pre>\n<p>If those lines were updated, then the <code>switch</code> statement in method <code>play()</code> can be replaced by this:</p>\n<pre><code>const methodName = '_merge' + dir.description.replace('move', '')\nif (typeof this[methodName === 'function') {\n this[methodName]()\n} \n</code></pre>\n</li>\n</ol>\n<h2>Other feedback</h2>\n<h3>Line endings</h3>\n<p>Perhaps you are using a compiler (e.g. BableJS) or other tool that handles it but unless you fully understand the ways <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Automatic_semicolon_insertion\" rel=\"nofollow noreferrer\">Automatic semicolon insertion</a> can be broken by certain statements, consider adding semi-colons to terminate the lines.</p>\n<h3>2048 is a <a href=\"https://en.m.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">Magic Number</a></h3>\n<p>One could argue that numbers like <code>0.5</code> and <code>2048</code>, even though it is the name of the game, may not have much meaning to anyone reading your code. While those values may never change, consider making them a constant or value that could be supplied via a parameter, in case there would be a need to support such features.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T00:51:37.400",
"Id": "256902",
"ParentId": "256691",
"Score": "3"
}
},
{
"body": "<h2>Symbol</h2>\n<p>A quick answer in regard to the use of <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Symbol\">Symbol</a>.</p>\n<blockquote>\n<p><em>"Lastly, I am using symbol to present the direction of the move the user can make and attach them as the instance variable to the class. Again I am not sure if this is idiomatic in OO since I am kinda new to this paradigm."</em></p>\n</blockquote>\n<p>There are 2 reasons to create a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Symbol\">Symbol</a></p>\n<ol>\n<li>To guarantee uniqueness <code>Symbol("foo") === Symbol("foo");</code> is always false.</li>\n<li>To share unique values between isolated scopes. Eg <code>Symbol.for("foo") === Symbol.for("foo");</code> is true across the global scope. Useful when using modules.</li>\n</ol>\n<h2>Pros</h2>\n<p>See above</p>\n<h2>Cons</h2>\n<ul>\n<li><p>Symbol comes with a very slight overhead approx 5% slower (chrome) than accessing Number so in applications where performance is highly critical they should be avoided.</p>\n</li>\n<li><p>Creating a new symbol <code>Symbol()</code> is 2 orders of magnitude slower than creating a unique number <code>i++</code></p>\n</li>\n<li><p>Symbol can not be serialized. eg <code>JSON.stringify({a: symbol("foo")})</code> creates <code>"{}"</code></p>\n</li>\n<li><p>Due to the nature of global symbols <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/for\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Symbol for\">Symbol.for</a> each symbol created thus, represents an unrecoverable memory assignment of approx 50bytes plus the name length (Unicode) per symbol.</p>\n<p>The same applies to scoped symbols however that memory can be recovered when the scope is de-referenced.</p>\n<p>Care must be taken to <em>not</em> create symbols in loops.</p>\n</li>\n</ul>\n<p>I mention the cons, though they are not applicable in this situation, but rather that using them may become habitual and one can easily get caught out if unaware of the problems.</p>\n<h2>Answering the question</h2>\n<p>Is your use of symbol idiomatic?</p>\n<p>No. The requirement for uniqueness is not there to warrant the added complexity. The need to identify a move can easily be achieved using a set of numbers</p>\n<pre><code>Game.moveUp = 0;\nGame.moveDown = 1;\nGame.moveLeft = 2;\nGame.moveRight = 3;\n</code></pre>\n<p>There is no possibility of a clash as the domain of uniqueness is limited to the 4 entities.</p>\n<p>The first rule of coding. With all things equal the simplest solution is the best.</p>\n<h2>BTW</h2>\n<p>Poor naming.</p>\n<p>If you find a set of variable names all starting with the same name/prefix its a sign that it should be an object.</p>\n<p>Example enumeration using block scoped counter.</p>\n<pre><code>{\n let i = 0;\n Game.moves = {\n up: i++,\n down: i++,\n left: i++,\n right: i++,\n };\n}\n</code></pre>\n<p>Or better as constants</p>\n<pre><code>{\n let i = 0;\n Game.moves = Object.freeze({\n UP: i++,\n DOWN: i++,\n LEFT: i++,\n RIGHT: i++,\n });\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T14:57:32.737",
"Id": "256929",
"ParentId": "256691",
"Score": "5"
}
},
{
"body": "<p>Programming paradigms, like OOP, can be thought of like an art style. Take the impressionism art style for example. This art style is characterized by traits such as visible brush strokes, a tendency to depict ordinary subject matters, etc. The more impressionism traits a work of art has, the more impressionist it is.</p>\n<p>Similarly, a program will lean more towards OOP if it commonly exhibits traits such as encapsulation, polymorphism, and inheritance.</p>\n<p>With that said, let's measure up your program to these three traits I just mentioned.</p>\n<hr />\n<h2>Encapsulation</h2>\n<p>Encapsulation is when we hide implementation details from the outside world, and only allow users to interact with our instance through the means we've provided. For example:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>class EventEmitter {\n #listeners = []\n subscribe(fn) {\n this.#listeners.push(fn)\n }\n trigger(...args) {\n this.#listeners.forEach(fn => fn(...args))\n }\n}\n</code></pre>\n<p>The fact that we're using a list to store the listeners is hidden from the outside world, and can safely be swapped for a set at any without affecting any other code.</p>\n<p>In this example, I used a class, but it's good to recognize that the <em>exact</em> same amount of encapsulation could be achieved using a factory function. the class syntax is not needed at all to make OOP code.</p>\n<p>It's good to note that there are different levels of encapsulation that you can achieve. In the example above, the following things would weaken that class's encapsulation:</p>\n<ul>\n<li>Changing <code>this.#listeners</code> to <code>this.listeners</code>, exposing the data publicly, and allowing direct read and mutation of this internal data.</li>\n<li>Exposing a read-only version of <code>this.#listeners</code> - this is better than allowing mutations, but still not ideal.</li>\n<li>creating a <code>getListeners()</code> function, that simply returns <code>this.#listeners</code>. Many beginner programmers hear that they're never supposed to expose their private members publicly, so they just create a bunch of functions that effectively does the same thing. This does <em>not</em> achieve more encapsalation.</li>\n</ul>\n<p>Note that doing these things isn't necessarily bad (depending on the scenario), they're just not OOP.</p>\n<p>Now let's take a look at your program.</p>\n<p>Your entire program resides in one class. This means the only encapsulation layer that exists is between this class and the little snippet of driver code that uses it. In other words, the internal details to almost the entire program are available to almost the entire program.</p>\n<p>This single encapsulation layer could be improved too. You're exposing a lot of things publicly that could really be private (by which I mean, more things ought to be named with a leading underscore, to indicate that it's an internal detail).</p>\n<p>Here are some members I might consider marking as private with a leading underscore:</p>\n<ul>\n<li>generateTile()</li>\n<li>spawn()</li>\n<li>isWin</li>\n<li>peek()</li>\n<li>zip()</li>\n</ul>\n<h2>Polymorphism</h2>\n<p>A polymorphic function is a function that can take any object that follows a specific interface, and operate on it. An example polymorphic function:</p>\n<pre><code>function attack(enemy, damage) {\n enemy.health -= damage\n if (enemy.health <= 0) enemy.die()\n}\n\nconst slime = { health: 2, die() { console.log('Slime dies') } }\nconst immortalRabbit = { health: 2, die() { this.health = 10 } }\nattack(slime, 3)\nattack(immortalRabbit, 3)\n</code></pre>\n<p>As your program only has one class, then there can't be any kind of polymorphism going on, at least with your own custom classes of objects.</p>\n<h2>Inheritance</h2>\n<p>I won't dwell on this too much, as it often gets overused. Inheritance is unique to OOP, which is why it's an important trait to mention, but you can write perfectly good OOP code without ever touching it. Just as an art style can change over time, so too does the OOP paradigm.</p>\n<h1>Making this code more OOP</h1>\n<p>Each of these traits discussed above are tale-tale signs of OO code. The more of them your code has, the more OO it is. However, don't artificially pump this into your program to achieve OOP - there's a right time, and a wrong time to use these them.</p>\n<p>Encapsulation, for example, is a powerful tool that can be used to greatly simplify a program by hiding away implementation details. But, when used in the wrong places, this same tool can create annoying barriers, and force some nasty workarounds to crop up in the codebase.</p>\n<p>I worked really hard at trying to make your code more OOP, but each time I tried to add encapsulation, or make some aspect exhibit polymorphic behavior, all I ended up doing was complicating the code without any real benefits. In all honesty, I think OOP is just the wrong tool for this job.</p>\n<p>As I've been working at this answer, I've also learned a lot about when it's good to use OOP and when it's not so great. One thing I've come to realize is that the traditional OOP examples aren't actually the examples where OOP really shines. i.e. there's really not private, implementation details to a "square" or a "triangle". Modeling a rectangle as a class with getWidth(), getHeight(), and getArea() doesn't provide much more encapsulation then an object with a <code>{ width: ..., height: ... }</code> shape and a separate function called <code>calculateAreaOfRectangle()</code>.</p>\n<p>UI components, on the other hand, tend to need a lot of encapsulation. It's not a webpage's header's business whether or not its child logo component is in a mouse-hover state or not, nor should it care whether or not its child search-box component has text in it or not.</p>\n<h1>Answering questions</h1>\n<p><strong>Is it idiomatic in OO to use static methods to store util functions such as zip to flip the board along its diagonal?</strong></p>\n<p>For utility functions such as zip(), you certainly can make them static methods of your class (though mark it as private! It's an implementation detail to the class). This is common to do in java, as there's really no other option there. In javascript though, you have other options which can be cleaner, like, just making those into module-level functions.</p>\n<p><strong>Is there a better way to structure the class? I feel like I am not doing a great job at dividing some of the logic of different actions.</strong></p>\n<p>There is one larger simplification I can think of. You could make all of your <code>_mergeLeft/right/up/down</code> functions return the new board, instead of assigning it to <code>this._board</code> - the caller of these merge functions can do that assignment if needed. Doing this would let you redefine canPlay() and checkIsWin() into something like this:</p>\n<pre><code>const WIN_CONDITION = 2048\n\nconst compare2dArray = (arrays1, arrays2) => arrays1.every((row, i) => (\n row.every((value, j) => value === arrays2[i][j])\n))\n\nclass Game {\n // ...\n canPlay() {\n if (this.checkIsWin()) return false\n return (\n compare2dArray(this._mergeLeft(), this._board) &&\n compare2dArray(this._mergeRight(), this._board) &&\n compare2dArray(this._mergeUp(), this._board) &&\n compare2dArray(this._mergeDown(), this._board)\n )\n }\n\n checkIsWin() {\n return this._board.some(row => (\n row.some(value => value >= WIN_CONDITION)\n ))\n }\n}\n</code></pre>\n<p><strong>Is there any specific design pattern that I can use to improve the class?</strong></p>\n<p>None of the OOP design patterns that I know of will really help much with this problem.</p>\n<p><strong>I am using symbol to present the direction of the move the user can make and attach them as the instance variable to the class. Again I am not sure if this is idiomatic in OO since I am kinda new to this paradigm.</strong></p>\n<p>You're effectively emulating an enum with these symbols. I know some javascript programmers like to use symbols this way to make their enums. It doesn't matter too much what you set the values to, as long as they're unique from each other - I normally just set them to different strings (i.e. 'UP' or 'DOWN').</p>\n<p>I would recommend grouping the directions together into a single directions object, as they're all part of the same pseudo-enum.</p>\n<p>In this specific scenario, you're creating this pseduo-enum to distinguish between different directions, then you're using a switch() later on to do different behaviors depending on the chosen direction. You could instead just attach behaviors to the enum values directly, getting rid of the switch all-together. For example:</p>\n<pre><code>class Game {\n static move = {\n up: { _merge: board => Game.zip(Game.zip(board).map(row => Game._mergeRowLeft(row))) },\n down: { _merge: board => Game.zip(Game.zip(board).map(row => Game._mergeRowRight(row))) },\n left: { _merge: board => board.map(row => Game._mergeRowLeft(row)) },\n right: { _merge: board => board.map(row => Game._mergeRowRight(row)) },\n }\n\n play(dir) {\n if (!this.canPlay()) return false\n this._board = dir._merge(this._board)\n this.spawn()\n return true\n }\n}\n</code></pre>\n<h1>Summary</h1>\n<p>It's great that you keep working on the same program, trying to apply different techniques on it to improve its quality. This is one of the best ways to improve your craft, so keep up the good work :).</p>\n<p>(Note that because I've already answered a similar question from the O.P. <a href=\"https://codereview.stackexchange.com/questions/256060/implement-the-merge-functionality-for-2048-with-javascript/256073#256073\">here</a>, I've chosen to just focus on the OOP aspect of their code, as that's the primary reason they're asking the question)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T07:47:00.493",
"Id": "256955",
"ParentId": "256691",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T19:00:18.390",
"Id": "256691",
"Score": "7",
"Tags": [
"javascript",
"object-oriented",
"game",
"functional-programming",
"2048"
],
"Title": "JavaScript OOD: 2048"
}
|
256691
|
<p>I am working with <code>System.Array</code> and I found that the input parameter of <code>ForEach</code> method <code>public static void ForEach<T>(T[] array, Action<T> action);</code> is specified on one dimensional array case. I am trying to generalize this to multidimensional array.</p>
<p><strong>The experimental implementation</strong></p>
<p>Here's the experimental implementation of generalized <code>ForEach</code> method.</p>
<pre><code>class ArrayHelpers
{
public static void ForEach<T>(Array array, in Action<T> action)
where T : unmanaged
{
if (ReferenceEquals(array, null))
{
throw new ArgumentNullException(nameof(array));
}
if (ReferenceEquals(action, null))
{
throw new ArgumentNullException(nameof(action));
}
foreach (T item in array)
{
action.Invoke(item);
}
return;
}
}
</code></pre>
<p><strong>Test cases</strong></p>
<p>The Test cases for one dimensional case, two dimensional case and three dimensional case are as below.</p>
<pre><code>// One dimensional case
Console.WriteLine("One dimensional case");
int[] test = new int[] { 1, 2, 3, 4 };
ArrayHelpers.ForEach<int>(test, ShowSquares);
// two dimensional case
Console.WriteLine("Two dimensional case");
int[,] test2 = { { 0, 1 }, { 2, 3 } };
ArrayHelpers.ForEach<int>(test2, ShowSquares);
// three dimensional case
Console.WriteLine("Three dimensional case");
int[,,] test3 = { { { 0, 1 }, { 2, 3 } }, { { 0, 1 }, { 2, 3 } } };
ArrayHelpers.ForEach<int>(test3, ShowSquares);
/// <summary>
/// Reference: https://docs.microsoft.com/en-us/dotnet/api/system.array.foreach?view=net-5.0
/// </summary>
/// <param name="val">The input value for displaying and calculating square result</param>
private static void ShowSquares(int val)
{
Console.WriteLine("{0:d} squared = {1:d}", val, val * val);
}
</code></pre>
<p>The output of the above tests:</p>
<pre><code>One dimensional case
1 squared = 1
2 squared = 4
3 squared = 9
4 squared = 16
Two dimensional case
0 squared = 0
1 squared = 1
2 squared = 4
3 squared = 9
Three dimensional case
0 squared = 0
1 squared = 1
2 squared = 4
3 squared = 9
0 squared = 0
1 squared = 1
2 squared = 4
3 squared = 9
</code></pre>
<p>I am wondering the things about the potential drawback or risks of this implementation.</p>
<p>All suggestions are welcome.</p>
|
[] |
[
{
"body": "<p>The solution is fine as it easy as it could be but there's a better way to make the access to it - extension method.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public static class ArrayHelpers\n{\n public static void ForEach<T>(this Array array, in Action<T> action)\n {\n if (ReferenceEquals(array, null))\n {\n throw new ArgumentNullException(nameof(array));\n }\n\n if (ReferenceEquals(action, null))\n {\n throw new ArgumentNullException(nameof(action));\n }\n\n foreach (T item in array)\n {\n action.Invoke(item);\n }\n return;\n }\n}\n</code></pre>\n<p>Then the test cases can look like this</p>\n<pre class=\"lang-cs prettyprint-override\"><code>Console.WriteLine("One dimensional case");\nint[] test = new int[] { 1, 2, 3, 4 };\ntest.ForEach<int>(ShowSquares);\n\nConsole.WriteLine("Two dimensional case");\nint[,] test2 = { { 0, 1 }, { 2, 3 } };\ntest2.ForEach<int>(ShowSquares);\n\nConsole.WriteLine("Three dimensional case");\nint[,,] test3 = { { { 0, 1 }, { 2, 3 } }, { { 0, 1 }, { 2, 3 } } };\ntest3.ForEach<int>(ShowSquares);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T06:43:53.437",
"Id": "506870",
"Score": "2",
"body": "Good call on the extensions implementation. I would suggest to rename the class to ArrayExtensions to clearly indicate the fact that is an extensions class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T07:04:57.523",
"Id": "506874",
"Score": "0",
"body": "@Abbas agree. But as for me `ArrayHelpers`, `ArrayTools`, `ArrayUtilities` are fine as `ArrayExtensions`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T20:50:13.260",
"Id": "256693",
"ParentId": "256692",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "256693",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T19:39:55.083",
"Id": "256692",
"Score": "1",
"Tags": [
"c#",
"array",
"generics"
],
"Title": "ForEach Methods Implementation for Multidimensional Array in C#"
}
|
256692
|
<p>I'm working through the CSES problem set as I learn to program, and this solution was accepted, but I'm not quite happy with it. I just know there's a faster way to check whether or not a solution's valid instead of looping through every element, and I'm sure there're plenty more improvements that could be made. Any feedback is appreciated!</p>
<p>Problem: A permutation of integers 1,2,…,n is called beautiful if there are no adjacent elements whose difference is 1.
Given n, construct a beautiful permutation if such a permutation exists.
If there are several solutions, you may print any of them. If there are no solutions, print "NO SOLUTION".</p>
<pre><code>def check_solution(sol):
last = sol[0]
for num in sol:
if num - last == 1 or num - last == -1:
return False
last = num
return True
a = [int(x) for x in range(1, int(input())+1)]
b = []
even = a[1::2]
odd = a[::2]
b.extend(even)
b.extend(odd)
if check_solution(b):
print(*b)
else:
print("NO SOLUTION")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T23:46:14.627",
"Id": "506846",
"Score": "8",
"body": "Please add a problem statement."
}
] |
[
{
"body": "<p>Your list slicing idea is a good one. You could simplify further by doing something\nanalogous with ranges, eliminating most of the need for intermediate variables</p>\n<pre><code>def beautiful_permutation(n):\n odd = list(range(1, n + 1, 2))\n even = list(range(2, n + 1, 2))\n return even + odd\n</code></pre>\n<p>Your validator probably should check more things and can also be simplified by\ntaking advantage of <code>abs()</code>. Optionally, you could express the adjacent-number\ncheck using <code>all()</code> and <code>zip()</code>. We're still looping over the numbers, but\njust more concisely.</p>\n<pre><code>def check_solution(n, sol):\n return (\n # Must not be empty.\n sol and\n # Must cover all intergers 1 through N.\n set(range(1, n + 1)) == set(sol) and\n # No adjacent numbers with difference of 1.\n all(abs(a - b) != 1 for a, b in zip(sol, sol[1:]))\n )\n</code></pre>\n<p>One additional point. The method used to create the sequence nearly ensures\nvalidity. By definition, the individual sub-lists (<code>odd</code> and <code>even</code>) will follow\nthe adjacent-number rule. The only way there can be a problem is at the\njunction point where we glue them together. But our function could directly\nvalidate the issue. If you were to add this and include a preliminary check for\nbad or special inputs (<code>0</code>, <code>1</code>, etc.), you would have a function that,\nat least for practical purposes, is provably correct -- no need for a validator!?!</p>\n<pre><code>if odd and even and abs(even[-1] - odd[0]) != 1:\n return even + odd\nelse:\n return None\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T06:34:05.967",
"Id": "506869",
"Score": "0",
"body": "I think your \"provably correct\" solution is wrong for n=1."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T07:28:58.783",
"Id": "506881",
"Score": "0",
"body": "@KellyBundy Seems like a definitional case. Either way, OP can sort it out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T00:59:28.913",
"Id": "506946",
"Score": "0",
"body": "Super helpful ideas! I've been trying to get these problems done without referencing too much online, and given my lack of experience, that unfortunately will usually lead to an unnecessary function or two."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T00:18:55.323",
"Id": "256702",
"ParentId": "256694",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "256702",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T21:11:44.753",
"Id": "256694",
"Score": "4",
"Tags": [
"python",
"python-3.x"
],
"Title": "Beginner python solution to CSES \"Permutations\""
}
|
256694
|
<p>After a long struggle, I've completed the Heredity project of "CS50's Introduction to Artificial Intelligence". However, I feel like my solution was not the most dignified way of doing it.</p>
<p>So for this particular function that I was working on, the goal is to calculate the joint probability of many events happening, such as one person having 2 genes but not showing the trait and another person having 1 gene and showing the trait.</p>
<p>My completed function below tells you essentially how it works. Basically if the person has no parents listed, I just use the <code>PROBS</code> dictionary to get the probability, while if the person has parents listed, I use the parents' information to find the child's information.</p>
<p>An example <code>people</code> would be this:</p>
<pre><code>{
'Harry': {'name': 'Harry', 'mother': 'Lily', 'father': 'James', 'trait': None},
'James': {'name': 'James', 'mother': None, 'father': None, 'trait': True},
'Lily': {'name': 'Lily', 'mother': None, 'father': None, 'trait': False}
}
</code></pre>
<p>And <code>PROBS</code> looks like this:</p>
<pre><code>PROBS = {
# Unconditional probabilities for having gene
"gene": {
2: 0.01,
1: 0.03,
0: 0.96
},
"trait": {
# Probability of trait given two copies of gene
2: {
True: 0.65,
False: 0.35
},
# Probability of trait given one copy of gene
1: {
True: 0.56,
False: 0.44
},
# Probability of trait given no gene
0: {
True: 0.01,
False: 0.99
}
},
# Mutation probability
"mutation": 0.01
}
</code></pre>
<p>And <code>one_gene</code>, <code>two_genes</code>, and <code>have_trait</code> are just sets containing strings of people's names.</p>
<p>My question is, my solution uses a <code>CHILD_PROB</code> dictionary that I calculated. Is there some way for me to dynamically figure out the child's gene probability without this dictionary by simply doing calculations with the mutation probability and parent gene information? If there is, would it be more or less elegant than my current solution?</p>
<p>See this link for more information on the project: <a href="https://cs50.harvard.edu/ai/2020/projects/2/heredity/" rel="nofollow noreferrer">https://cs50.harvard.edu/ai/2020/projects/2/heredity/</a></p>
<pre class="lang-py prettyprint-override"><code>def joint_probability(people, one_gene, two_genes, have_trait):
"""
Compute and return a joint probability.
The probability returned should be the probability that
* everyone in set `one_gene` has one copy of the gene, and
* everyone in set `two_genes` has two copies of the gene, and
* everyone not in `one_gene` or `two_gene` does not have the gene, and
* everyone in set `have_trait` has the trait, and
* everyone not in set` have_trait` does not have the trait.
"""
return_prob = 1
mut = PROBS["mutation"]
# Probability for child given parent tuple
CHILD_PROB = {
(2, 2): (mut**2, 2*mut*(1-mut), (1-mut)**2),
(2, 1): (0.5*mut, 0.5, (1-mut)*0.5),
(2, 0): (mut*(1-mut), (1-mut)**2 + mut**2, (1-mut)*mut),
(1, 1): (0.25, 0.5, 0.25),
(1, 0): (0.5*(1-mut), 0.5, 0.5*mut),
(0, 0): ((1-mut)**2, 2*mut*(1-mut), mut**2)
}
for person in people.keys():
# Figure out how many genes person should have
if person in one_gene:
genum = 1
elif person in two_genes:
genum = 2
else:
genum = 0
if people[person]["father"] == None:
# Use PROBS if person's parents aren't listed
return_prob *= PROBS["gene"][genum]
else:
parent_genes = {"mother": 0, "father": 0}
# Get parents' genes
for parent_str in parent_genes.keys():
parent = people[person][parent_str]
if parent is not None:
parent_genes[parent_str] = 1 if parent in one_gene else 2 if parent in two_genes else 0
# Try both tuple orders
try:
return_prob *= CHILD_PROB[(parent_genes["mother"], parent_genes["father"])][genum]
except KeyError:
return_prob *= CHILD_PROB[(parent_genes["father"], parent_genes["mother"])][genum]
# Get person's trait probability
if person in have_trait:
return_prob *= PROBS["trait"][genum][True]
else:
return_prob *= PROBS["trait"][genum][False]
return return_prob
<span class="math-container">```</span>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T21:37:25.730",
"Id": "256695",
"Score": "0",
"Tags": [
"python",
"python-3.x",
"ai"
],
"Title": "Is there a better way to calculate joint probability?"
}
|
256695
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.