text stringlengths 1 2.12k | source dict |
|---|---|
python, performance, animation, matplotlib
def animate(frame: int):
th_var = 30
for mov in movers:
mov.start()
mov.steer(radians(random.uniform(-th_var, th_var)))
mov.transit()
mov.update_plot()
return [mv.plt for mv in movers]
ani = FuncAnimation(fig, animate, init_func=init, blit=True)
plt.show()
Answer: Don't import from math when you have Numpy.
I didn't find mpl_use to be necessary.
history, since it's a constant, should be HISTORY.
Don't [i for i in range(history)]; range(history) alone has the same effect since you don't need to mutate the result.
Add PEP484 type hints.
Expanding your colour thus:
r, g, b = colour
is not needed, since you can just use *colour in your list.
You never normalise so I've omitted this from my example code.
Your wrapping code can be greatly simplified by using a single call to np.mod.
From fig, ax = plt.subplots() onward, none of that code should exist in the global namespace and should be moved to functions.
The biggest factor causing apparent slowness is that you've not overridden the default interval=, so the animation appears choppy. A first pass that addresses some of the above:
import random
from typing import Iterator
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from matplotlib.collections import PathCollection
from matplotlib.colors import LinearSegmentedColormap, ListedColormap
HISTORY = 100 # trail size per mover.
HOME_X, HOME_Y = 50, 50
WINDOW_LIMITS = 100
class Mover:
VELOCITY = 0.75
WRAPPING = True
def __init__(self, colour: list[float], window_limits: int) -> None:
# colour = R G B tuple of floats between 0 (black) and 1 (full)
cmap_array = np.empty((HISTORY, 4))
cmap_array[:, :3] = colour
cmap_array[:, 3] = np.linspace(start=1, stop=0, num=HISTORY)
ccmap = LinearSegmentedColormap.from_list(name="", colors=cmap_array) | {
"domain": "codereview.stackexchange",
"id": 43320,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, animation, matplotlib",
"url": null
} |
python, performance, animation, matplotlib
offsets = range(HISTORY)
self.mv = 0., 1. # starting unit vector.
self.mxy = [
[HOME_X] * HISTORY,
[HOME_Y] * HISTORY,
]
self.plt: PathCollection = plt.scatter(*self.mxy, c=offsets, cmap=ccmap)
self.w_limits = window_limits
self.steer(np.radians(random.uniform(-180, 180)))
def start(self) -> None:
x, y = self.mxy # copy most recent state.
x.insert(0, x[0])
y.insert(0, y[0])
if len(x) > HISTORY: # remove the oldest state if too long..
x.pop()
y.pop()
def steer(self, theta: float) -> None:
# theta is in radians
x, y = self.mv
cosa, sina = np.cos(theta), np.sin(theta)
u = x*cosa - y*sina # x1 = x0cos(θ) – y0sin(θ)
v = x*sina + y*cosa # y1 = x0sin(θ) + y0cos(θ)
self.mv = u, v
def transit(self) -> None:
u, v = self.mv
x, y = self.mxy
x[0] += self.VELOCITY * u
y[0] += self.VELOCITY * v
if self.WRAPPING:
self.wrap()
def wrap(self) -> None:
x, y = self.mxy
if x[0] > self.w_limits:
x[0] -= self.w_limits
if y[0] > self.w_limits:
y[0] -= self.w_limits
if x[0] < 0:
x[0] += self.w_limits
if y[0] < 0:
y[0] += self.w_limits
def update_plot(self) -> None:
self.plt.set_offsets(np.array(self.mxy).T)
def make_movers(colours: ListedColormap, mover_count: int = 50) -> Iterator[Mover]:
colour_indices = np.linspace(start=0, stop=colours.N-1, num=mover_count, dtype=int)
for c in colour_indices:
col = colours.colors[c]
yield Mover(col, WINDOW_LIMITS)
def main() -> None:
def init() -> list[plt.Artist]:
ax.set_xlim(0, WINDOW_LIMITS)
ax.set_ylim(0, WINDOW_LIMITS)
return artists | {
"domain": "codereview.stackexchange",
"id": 43320,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, animation, matplotlib",
"url": null
} |
python, performance, animation, matplotlib
def animate(frame: int) -> list[plt.Artist]:
theta = np.radians(30)
for mov in movers:
mov.start()
mov.steer(random.uniform(-theta, theta))
mov.transit()
mov.update_plot()
return artists
fig, ax = plt.subplots()
movers = tuple(make_movers(plt.cm.turbo))
artists = [mv.plt for mv in movers]
ani = FuncAnimation(fig=fig, func=animate, init_func=init, blit=True, interval=10)
plt.show()
if __name__ == '__main__':
main()
A vectorised implementation is possible, but doesn't make much of a difference; the slowest part is matplotlib itself:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from matplotlib.collections import PathCollection
from matplotlib.colors import LinearSegmentedColormap, ListedColormap
from numpy.random import default_rng
HISTORY = 100 # trail size per mover.
HOME_X, HOME_Y = 50, 50
WINDOW_LIMITS = 100
VELOCITY = 0.75
rand = default_rng()
def start_movers(pos: np.ndarray) -> None:
# pos is n_movers * HISTORY * 2, newest first
# shift the data one row down, treating it as a queue
pos[:, 1:, :] = pos[:, :-1, :]
def steer_movers(vel: np.ndarray, theta: float) -> None:
# vel is n_movers * 2
x, y = vel.T
theta = rand.uniform(low=-theta, high=theta, size=vel.shape[0])
cosa, sina = np.cos(theta), np.sin(theta)
u = x*cosa - y*sina
v = x*sina + y*cosa
vel[:, 0] = u
vel[:, 1] = v
def transit_movers(pos: np.ndarray, vel: np.ndarray) -> None:
pos[:, 0, :] += VELOCITY * vel
def wrap_movers(pos: np.ndarray) -> None:
np.mod(pos, WINDOW_LIMITS, out=pos)
class Mover:
def __init__(self, cmap_array: np.ndarray, pos: np.ndarray) -> None:
self.pos = pos
ccmap = LinearSegmentedColormap.from_list(name="", colors=cmap_array)
self.plt: PathCollection = plt.scatter(*self.pos.T, c=range(HISTORY), cmap=ccmap) | {
"domain": "codereview.stackexchange",
"id": 43320,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, animation, matplotlib",
"url": null
} |
python, performance, animation, matplotlib
def update_plot(self) -> None:
self.plt.set_offsets(self.pos)
def make_movers(
colours: ListedColormap,
mover_count: int = 50,
) -> tuple[
np.ndarray, # positions
np.ndarray, # velocities
list[Mover],
]:
pos = np.empty((mover_count, HISTORY, 2))
pos[..., 0] = HOME_X
pos[..., 1] = HOME_Y
vel = np.empty((mover_count, 2))
theta = rand.uniform(low=-np.pi, high=np.pi, size=mover_count)
vel[:, 0] = np.cos(theta)
vel[:, 1] = np.sin(theta)
colour_indices = np.linspace(start=0, stop=colours.N-1, num=mover_count, dtype=int)
cmap_array = np.empty((mover_count, HISTORY, 4))
cmap_array[:, :, :3] = np.array(colours.colors)[colour_indices, np.newaxis, :]
cmap_array[:, :, 3] = np.linspace(start=1, stop=0, num=HISTORY)
movers = []
for i_mover, cmap in enumerate(cmap_array):
movers.append(Mover(cmap_array=cmap, pos=pos[i_mover, ...]))
return pos, vel, movers
def main() -> None:
def init() -> list[plt.Artist]:
ax.set_xlim(0, WINDOW_LIMITS)
ax.set_ylim(0, WINDOW_LIMITS)
return artists
def animate(frame: int) -> list[plt.Artist]:
start_movers(pos)
steer_movers(vel, theta=np.radians(30))
transit_movers(pos, vel)
wrap_movers(pos)
for mov in movers:
mov.update_plot()
return artists
fig, ax = plt.subplots()
pos, vel, movers = make_movers(plt.cm.turbo)
artists = [mv.plt for mv in movers]
ani = FuncAnimation(fig=fig, func=animate, init_func=init, blit=True, interval=10)
plt.show()
if __name__ == '__main__':
main() | {
"domain": "codereview.stackexchange",
"id": 43320,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, animation, matplotlib",
"url": null
} |
python, performance, animation, matplotlib
if __name__ == '__main__':
main()
A different style of animation is possible where you don't cull old points based on your queueing code and instead disable blit and draw over your old data, but this quickly hits scalability limits once enough data build up:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from matplotlib.collections import PathCollection
from matplotlib.colors import LinearSegmentedColormap, ListedColormap
from numpy.random import default_rng
HOME_X, HOME_Y = 50, 50
WINDOW_LIMITS = 100
VELOCITY = 0.75
rand = default_rng()
def steer_movers(vel: np.ndarray, theta: float) -> None:
# vel is n_movers * 2
x, y = vel.T
theta = rand.uniform(low=-theta, high=theta, size=vel.shape[0])
cosa, sina = np.cos(theta), np.sin(theta)
u = x*cosa - y*sina
v = x*sina + y*cosa
vel[:, 0] = u
vel[:, 1] = v
def transit_movers(pos: np.ndarray, vel: np.ndarray) -> None:
pos += VELOCITY * vel
def wrap_movers(pos: np.ndarray) -> None:
np.mod(pos, WINDOW_LIMITS, out=pos)
def make_movers(
colours: ListedColormap,
mover_count: int = 50,
) -> tuple[
np.ndarray, # positions
np.ndarray, # velocities
LinearSegmentedColormap, # colour map, non-history-based
]:
pos = np.empty((mover_count, 2))
pos[:, 0] = HOME_X
pos[:, 1] = HOME_Y
vel = np.empty((mover_count, 2))
theta = rand.uniform(low=-np.pi, high=np.pi, size=mover_count)
vel[:, 0] = np.cos(theta)
vel[:, 1] = np.sin(theta)
colour_indices = np.linspace(start=0, stop=colours.N-1, num=mover_count, dtype=int)
cmap_array = np.ones((mover_count, 4))
cmap_array[:, :3] = np.array(colours.colors)[colour_indices, :]
cmap = LinearSegmentedColormap.from_list(name="", colors=cmap_array)
return pos, vel, cmap
def main() -> None:
def init() -> list[plt.Artist]:
ax.set_xlim(0, WINDOW_LIMITS)
ax.set_ylim(0, WINDOW_LIMITS)
return [] | {
"domain": "codereview.stackexchange",
"id": 43320,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, animation, matplotlib",
"url": null
} |
python, performance, animation, matplotlib
def animate(frame: int) -> list[plt.Artist]:
steer_movers(vel, theta=np.radians(30))
transit_movers(pos, vel)
wrap_movers(pos)
scatter: PathCollection = plt.scatter(
*pos.T,
c=range(pos.shape[0]),
cmap=cmap,
)
return [scatter]
fig, ax = plt.subplots()
pos, vel, cmap = make_movers(plt.cm.turbo)
ani = FuncAnimation(fig=fig, func=animate, init_func=init, blit=False, interval=10)
plt.show()
if __name__ == '__main__':
main() | {
"domain": "codereview.stackexchange",
"id": 43320,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, animation, matplotlib",
"url": null
} |
c, strings, memory-management, c99, oauth
Title: OAuth implementation for Puredata
Question: I am managing an OAuth implementation for Puredata (Pd), which is written in C. OAuth can accept RSA keys, but Pd cannot send messages with newlines, so placing private keys will come as a list of strings with spaces acting as separators.
Basically this function looks into the different parts of the block and adds either a newline or a space at the end, such that -----BEGIN PRIVATE KEY----- will end up in one line, while A7qVvdqxevEuUkW4K+2KdMXmnQbG9Aa7k7eBjK1S+0LYmVjPKlJGNXHDGuy5Fw/d 7rjVJ0BLB+ubPK8iA/Tw3hLQgXMRRGRXXCn8ikfuQfjUS1uZSatdLB81mydBETlJ will end up in separate ones.
Some functions, types and constants, that are used here: MAXPDSTRING: the maximum length of a string, t_atom: message part, atom_string(*t_atom src, *char dest, size_t max_length): convert src to dest with a max_length.
static char *string_create(size_t *const newl, const size_t strl) {
char *gen;
/* newl is not the length of the string, but the memory size */
(*newl) = 1 + strl;
gen = getbytes((*newl) * sizeof(char));
if (gen == NULL) {
pd_error(0, "not enough memory.");
return gen;
}
return memset(gen, 0x00, (*newl));
}
static void oauth_set_rsa_key(t_oauth *const oauth, const int argc, t_atom *const argv) {
char temp[MAXPDSTRING];
size_t rsa_key_len = 1; /* Accomodate NULL terminator */
short use_newline = 0; | {
"domain": "codereview.stackexchange",
"id": 43321,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, strings, memory-management, c99, oauth",
"url": null
} |
c, strings, memory-management, c99, oauth
for (int i = 1; i < argc; i++) {
atom_string(argv + i, temp, MAXPDSTRING);
rsa_key_len += strlen(temp) + 1; /* Each section + 1 for space or newline */
}
oauth->oauth.rsa_key = string_create(&oauth->oauth.rsa_key_len, rsa_key_len);
for (int i = 1; i < argc; i++) {
atom_string(argv + i, temp, MAXPDSTRING);
if (strncmp(temp, "-----", 5) == 0 && strlen(oauth->oauth.rsa_key) > 1) {
/* Cutoff trailing space and add newline */
memset(oauth->oauth.rsa_key + strlen(oauth->oauth.rsa_key) - 1, 0x00, 1);
strcat(oauth->oauth.rsa_key, "\n");
use_newline = 0;
}
if (strlen(temp) >= 5 && strncmp(temp + strlen(temp) - 5, "-----", 5) == 0) {
use_newline = 1;
}
strcat(oauth->oauth.rsa_key, temp);
if (i < argc - 1) {
if (use_newline == 1) {
/* This gets flagged as possible buffer overflow */
strcat(oauth->oauth.rsa_key, "\n");
} else {
/* This also */
strcat(oauth->oauth.rsa_key, " ");
}
}
}
}
Static analysis in Coverity does flag strcat(oauth->oauth.rsa_key, "\n"); as possible buffer overflow, but I cannot see the possible overflow here. What am I missing?
I could not provoke a buffer overflow by arbitrary data containing any combinations of -, spaces or anything.
Answer: Almost certainly, Coverity is simply looking for all uses of strcat, strcpy, sprintf, etc., and flagging them as "potential buffer overflow" no matter what the context. You can check that by adding some code to your project that does something simple and obviously correct like
char *p = malloc(10);
strcpy(p, "12345");
strcat(p, "6789");
free(p);
or
char *mystrdupdot(const char *s) {
char *p = malloc(strlen(s) + 2);
strcpy(p, s);
return strcat(p, ".");
}
If Coverity flags those strcpys or strcats as buffer overflows, then you've got your answer. | {
"domain": "codereview.stackexchange",
"id": 43321,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, strings, memory-management, c99, oauth",
"url": null
} |
c, strings, memory-management, c99, oauth
If Coverity flags those strcpys or strcats as buffer overflows, then you've got your answer.
memset(oauth->oauth.rsa_key + strlen(oauth->oauth.rsa_key) - 1, 0x00, 1);
That is a very weird way of saying
oauth->oauth.rsa_key[strlen(oauth->oauth.rsa_key)-1] = '\0';
Also, you should probably look for a way to stop recomputing strlen every time through this loop. | {
"domain": "codereview.stackexchange",
"id": 43321,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, strings, memory-management, c99, oauth",
"url": null
} |
php, object-oriented, comparative-review, database
Title: Insert row into database using static or non-static method
Question: I would like to know if there are any benefits of one of the following 2 methods which insert an object into a database
The first function calls the Model method statically, creating a new instance of the Insert function on the call.
foreach ($model_data as $data) {
$row = \Models\ModelData::createRow($data, $u->dname, $w_reason, $comment);
$insert = \Models\ModelData::Insert($row);
$insert_obj = new \stdClass();
$insert_obj->d_name = $data->{'Data Name'};
$insert_obj->status = $insert;
$insert_array[] = $insert_obj;
}
This version of the function calls the Model method non-statically.
foreach ($model_data as $data) {
$row = \Models\ModelData::createRow($data, $u->dname, $w_reason, $comment);
$insert_result = $row->Insert();
$insert_obj = new \stdClass();
$insert_obj->d_name = $data->{'Data Name'};
$insert_obj->status = $insert_result;
$insert_array[] = $insert_obj;
}
With the Model method being called non-statically, there is no need for an argument to be passed in.
public function Insert(): bool
But with the Model being created via a static method, it requires the argument.
public static function Insert(MyObject $object): bool
Is there a major benefit to one of these over the other?
Answer:
I think, in "Object-oriented programming", it makes perfect sense to explicitly craft your scripts to handle objects. The ability to chain methods together can help to make your code less verbose.
$row and $insert_result are single-use variables, so I would not bother declaring it.
Rather than forming an individual object, then declaring the properties, then pushing the object into the result array, I recommend the more brief syntax of populating the object inside of the push syntax. | {
"domain": "codereview.stackexchange",
"id": 43322,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, object-oriented, comparative-review, database",
"url": null
} |
php, object-oriented, comparative-review, database
Suggested, untested code:
foreach ($model_data as $data) {
$insert_array[] = (object) [
'd_name' => $data->{'Data Name'},
'status' => (\Models\ModelData::createRow($data, $u->dname, $w_reason, $comment))->Insert()
];
}
While the above snippet doesn't quite fit neatly in the Stack Exchange text area, it does comply with the recommended line width limits described by PSR-12.
Alternatively, if you prefer to declare $row to lessen the line width, then you can use:
foreach ($model_data as $data) {
$row = \Models\ModelData::createRow($data, $u->dname, $w_reason, $comment);
$insert_array[] = (object) [
'd_name' => $data->{'Data Name'},
'status' => $row->Insert()
];
}
Ultimately, unless you have a valid reason to have Insert as a static method, I'd not recommend it. By the way, methods should start with a lowercase letter for PSR-12 compliance. | {
"domain": "codereview.stackexchange",
"id": 43322,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, object-oriented, comparative-review, database",
"url": null
} |
javascript, typescript, observer-pattern, webcomponent
Title: Typescript simple observable state and web component
Question: I've been experimenting with wiring up a vanilla web component in a reactive manner to a state box. The goal is that when something changes on the state object, the web component reacts. I realize that there are frameworks and libraries for this, but I want to understand fundamentally what goes on underneath. After two decades on server stuff, I want to branch out. I also wonder if we really need more dependencies if this is simple and straight-forward enough.
My approach is this:
A base class that extends HTMLElement that can declaratively (via attribute in the markup) specify what data to watch.
A state base class that is used to facilitate subscription to changes and notifications back to the subscribers.
An attribute to decorate properties that you want to watch on those classes derived from the state base class.
First, the state base class:
class StateBase {
constructor() {
this._subs = new Map<string, Array<Function>>();
}
private _subs: Map<string, Array<Function>>;
subscribe(propertyName: string, eventHandler: any) {
if (!this._subs.has(propertyName))
this._subs.set(propertyName, new Array<Function>());
var callbacks = this._subs.get(propertyName);
callbacks.push(eventHandler);
}
notify(propertyName: string) {
var callbacks = this._subs.get(propertyName);
if (callbacks)
for (let i of callbacks) {
i();
}
}
} | {
"domain": "codereview.stackexchange",
"id": 43323,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, typescript, observer-pattern, webcomponent",
"url": null
} |
javascript, typescript, observer-pattern, webcomponent
The subscribe method is called by the web component base with the name of the property to monitor and a reference to its update mechanism. Of course, you could arbitrarily subscribe to any method on an instance. I'm using a Map as a dictionary of callback method arrays, one item for each property. notify is called by the decorator when a property value changes. Instances of this class have to be in the global (window) scope so the web components can find it.
Here's the attribute/decorator function:
const WatchProperty = (target: any, memberName: string) => {
let currentValue: any = target[memberName];
Object.defineProperty(target, memberName, {
set(this: any, newValue: any) {
console.log("watchProperty called on " + memberName + " with value " + newValue);
currentValue = newValue;
this.notify(memberName);
},
get() {return currentValue;}
});
};
The part I don't understand well, but learned about on SO, is Object.defineProperty taking the target, which is a prototype, to get to the actual instance of the state box. It works though. The important part is that it calls notify on the aforementioned base state class.
Here's the web component base:
abstract class ElementBase extends HTMLElement {
// Derived class constructor must call super("IDofTemplateHTML") first.
constructor(templateID: string) {
super();
this.attachShadow({ mode: 'open' });
var el = document.getElementById(templateID) as HTMLTemplateElement;
if (!el)
throw Error(`No template found for ID '{templateID}'. Must pass the ID of the template in constructor to base class, like super('myID');`)
const template = el.content;
this.shadowRoot.appendChild(template.cloneNode(true));
} | {
"domain": "codereview.stackexchange",
"id": 43323,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, typescript, observer-pattern, webcomponent",
"url": null
} |
javascript, typescript, observer-pattern, webcomponent
connectedCallback() {
var attr = this.getAttribute('caller');
if (!attr)
throw Error("There is no 'caller' attribute on the component.");
var varAndProp = this.parseCallerString(attr);
var state = window[varAndProp[0]];
var delegate = this.update.bind(this);
state.subscribe(varAndProp[1], delegate);
}
update() {
console.log("update called start");
var attr = this.getAttribute('caller');
if (!attr)
throw Error("There is no 'caller' attribute on the component.");
var varAndProp = this.parseCallerString(attr);
var externalValue = window[varAndProp[0]][varAndProp[1]];
this.updateUI(externalValue);
console.log("update called end - " + externalValue);
}
private parseCallerString(caller: string): [string, string] {
var segments = caller.split(".");
if (segments.length != 2)
throw Error("caller attribute must follow 'globalVariable.property' format.");
return [segments[0], segments[1]];
}
// Use this.shadowRoot in the implementation to manipulate the DOM as needed in response to the new data.
abstract updateUI(data: any);
} | {
"domain": "codereview.stackexchange",
"id": 43323,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, typescript, observer-pattern, webcomponent",
"url": null
} |
javascript, typescript, observer-pattern, webcomponent
Importantly, your constructor has to take in the ID of the template. I imagine I could also include the template in the derived class, but it depends on how you like to organize and encapsulate things. I'd rather have the markup not in the code. The constructor sets up the shadowRoot from the template. connectedCallback takes the declarative caller attribute on the component instance and uses it to register the update method with the base state class. update again parses the caller attribute to find the state and its property value. Finally it calls the abstract updateUI method that the derived web component has to implement.
OK, so here are a concrete implementation examples deriving from the base classes:
class TestState extends StateBase {
constructor() {
super();
this.texty = "";
this.numbery = 0;
}
@WatchProperty
texty: string;
@WatchProperty
numbery: number;
}
class TestElement extends ElementBase {
constructor() {
super("pf-test");
}
updateUI(data) {
this.shadowRoot.querySelector("h1").innerHTML = data;
}
}
And here's a page where it all comes together:
<!DOCTYPE html>
<html>
<head>
<title>TypeScript Hello Web</title>
</head>
<body>
<script src="dist/test.js"></script> <!-- has all of the above stuff -->
<script>
var state = new TestState();
customElements.define('pf-test', TestElement);
document.addEventListener("DOMContentLoaded", () => {
state.subscribe("texty", () => {
console.log("Call me for texty!");
});
state.subscribe("numbery", () => {
console.log("anon call for numbery");
});
state.texty = "first change";
state.numbery = 42;
state.texty = "second change!";
state.numbery = 123;
});
</script> | {
"domain": "codereview.stackexchange",
"id": 43323,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, typescript, observer-pattern, webcomponent",
"url": null
} |
javascript, typescript, observer-pattern, webcomponent
<template id="pf-test">
<div>
<h1>original</h1>
</div>
</template>
<pf-test caller="state.texty">
</pf-test>
<pf-test caller="state.numbery">
</pf-test>
</body>
</html>
As you can guess, when the page is all done, there's a line that says "second change!" and another that says "123."
I'm not sure what specific feedback I seek, because I've spent so little time in TypeScript and front-end code in general. I'm interested in:
Style problems.
Syntax around member modifiers (public/private), appropriate use of var/let/const which I'm still learning.
General portability and reuse.
Potential gotchas or performance issues.
Sensible error checking.
Accusations that this entire approach sucks. :)
Thank you in advance!
EDIT: You can follow along with my changes on the Github:
https://github.com/jeffputz/ts-observable-web-component | {
"domain": "codereview.stackexchange",
"id": 43323,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, typescript, observer-pattern, webcomponent",
"url": null
} |
javascript, typescript, observer-pattern, webcomponent
Answer: It looks like you have learned a lot from it. I want to concentrate on your points you've listed on what you're looking for in terms of this review.
Style
Probably the two biggest things that grabs my attention are, that you've decided to leave out parenthesis on most of the if-statements and that most of the time you're using the var keyword.
So leaving out the curly braces is a potential gotcha, but I think you are aware of this - linters like ESLint or Prettier will help you with that, if desired. In general, this looks good to me (more about the var stuff in the syntax section, where you explicitly asked for it).
Syntax
Mainly the var keyword has been used - it can be used but should be avoided. let and const are the better alternatives.
As a quick recap, when using the var keyword, the interpreter moves all variables declared that way to the top of their scopes - regardless where they are placed. Each variable is mutable and can be redeclared (var), whereas variables using the let keyword are mutable but cannot be redeclared and const is not mutable at all once assigned:
var x = "foo"; // ✅
var x = "15"; // ✅
let y = "10";
let y = "15"; // ❌
y = "15"; // ✅
const z = "10";
z = "5"; // ❌
This means, avoid var, use const wherever possible unless you need to mutate a variable - then there is let!
A few things I'd to differently codewise:
Adding the event handler to the callback array (the first code block is taken from your posting, below how this code could be transformed).
// Using discouraged var keyword
var callbacks = this._subs.get(propertyName);
callbacks.push(eventHandler);
// Using const keyword
const callbacks = this._subs.get(propertyName);
callbacks.push(eventHandler);
// The variable can be safely inlined as its not used afterwards
this._subs.get(propertyName).push(eventHandler); | {
"domain": "codereview.stackexchange",
"id": 43323,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, typescript, observer-pattern, webcomponent",
"url": null
} |
javascript, typescript, observer-pattern, webcomponent
Using the spread syntax is helpful - read more about it at MDN (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax):
// Original code
var segments = caller.split(".");
if (segments.length != 2)
throw Error("caller attribute must follow 'globalVariable.property' format.");
return [segments[0], segments[1]];
// Refactored using spread syntax
const segments = caller.split(".");
if (segments.length != 2)
throw Error("caller attribute must follow 'globalVariable.property' format.");
return [...segments];
Note: I should be perfectly fine to just return segments here, there is no need to create a whole new array!
Portability and reuse
As is, the portability seems to be just fine. Reusing this code is also perfectly doable. I'm wondering though, there are checks in the code, that the caller is of length 2 - this implies a limitation of the state. For example, using this as a global application state, where many different domains come together, it all has to be on the top-level. This does not feel right and might be a thing to be considered.
Misc
Since this is TypeScript code, I'd like to mention, that there are a few any usages. Yes, it's tempting to use them, but try to be precise as possible, because most of the time it's the root of all evil. When there is no specific type I can come up with, I use unknown first. For example looking at the function signature of subscribe
subscribe(propertyName: string, eventHandler: any)
I am allowed to pass in anything I'd like. So let's assume I put in the number 5. Later in the code, the "callbacks" are retrieved and the assumption is, that all of them are a function.
notify(propertyName: string) {
var callbacks = this._subs.get(propertyName);
if (callbacks)
for (let i of callbacks) {
i();
}
}
During runtime, this will break and TypeScript didn't warn us about it. This can easily be fixed by adjusting the type to: eventHandler: () => void. | {
"domain": "codereview.stackexchange",
"id": 43323,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, typescript, observer-pattern, webcomponent",
"url": null
} |
python
Title: List to Dictionary Function Project - Automate the Boring Stuff Chapter 5
Question: This is the List to Dictionary Function for Fantasy Game Inventory project in Chapter 5.
The project is as follows:
Write a function named addToInventory(inventory, addedItems), where
the inventory parameter is a dictionary representing the player’s
inventory (like in the previous project) and the addedItems parameter
is a list like dragonLoot. The addToInventory() function should return
a dictionary that represents the updated inventory. Note that the
addedItems list can contain multiples of the same item.
I believe I've filled the requirements but I wondered if I was doing something inefficiently.
My code:
def display_inventory(inventory):
total_items = 0
print ("Inventory:")
for item in inventory.keys():
print(str(inventory[item]) + ' ' + item)
total_items += inventory[item]
print("Total number of items: " + str(total_items))
def addToInventory(inventory, addedItems):
for item in addedItems:
if item in inventory:
inventory[item] += 1
else:
inventory.setdefault(item, 1)
inv = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby', 'torch']
addToInventory(inv, dragonLoot)
display_inventory(inv) | {
"domain": "codereview.stackexchange",
"id": 43324,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
display_inventory(inv)
Answer: Put all code in functions. Even the usage-demo code. This is one of many
bug-avoidance and testability-supporting habits that experienced programmers
adopt.
Should the function return a new inventory or modify the current one? The
text says we should "return a dictionary", but the suggested function name
implies that we should modify/update the current inventory. This distinction is
crucial in software engineering, and it's unfortunate that the book is so
confused on this topic. Your code updates the current inventory (and returns
None). Absent a compelling reason to do otherwise, one should prefer
functions that return new data rather than functions that modify data they are
given. There are many reasons for no-mutation as the default approach when
writing functions, and I would encourage you to learn more about them.
If you need to count things, consider using a Counter. Python includes
a dict-like data structure designed explicitly for counting things.
Displaying an inventory: take better advantage dict, print, and sum.
Your code to display an inventory is overly complex. The print() function
automatically converts its arguments to str, so you don't need to
bother with that. It seems handier to iterate over both keys and values.
And there's no need to add up the values yourself: let sum() do the work.
Pick a naming convention. Some of your code doesThis and some of it
does_this. I see the latter more often in Python. Here's the code I ended
up with.
import sys
from collections import Counter
def main():
inv_initial = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
dragon_loot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby', 'torch']
inv_new = updated_inventory(inv_initial, dragon_loot)
display_inventory(inv_initial, 'initial')
display_inventory(inv_new, 'new')
def updated_inventory(inventory, added):
c = Counter(inventory)
c.update(added)
return dict(c) | {
"domain": "codereview.stackexchange",
"id": 43324,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
def display_inventory(inventory, label = ''):
total = sum(inventory.values())
print(f'Inventory: {label} (total: {total})')
for item, n in inventory.items():
print(f' {item}: {n}')
if __name__ == '__main__':
main() | {
"domain": "codereview.stackexchange",
"id": 43324,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
c++, stl
Title: Reading a list of names, counting them and ordering them
Question: I would like to know does this code follow common best practices in C++ using STL.
Goal of the code:
There are 10 players that were playing a game 1000 times. Each time someone has won they have put winners name into the binary file data.bin. Each name takes 20 bytes of data in the binary file and uses \0 as a string terminator.
This program uses that file as an input and prints out ranked list of each player's scores.
Here is my code:
#include <iostream>
#include <fstream>
#include <map>
#include <algorithm>
#include <vector>
using std::map, std::string, std::ifstream, std::ios, std::string, std::cerr, std::vector, std::pair, std::sort, std::cout;
constexpr size_t NAME_SIZE=20;
const char* FILE_NAME = "data.bin";
constexpr int FILE_NOT_OPENED = 1;
struct zuint { uint16_t val = 0; };
int main() {
char tmp[NAME_SIZE];
map<string, zuint > points;
ifstream file(FILE_NAME, ios::in | ios::binary);
if(!file){
cerr << "File not opened. 'data.bin' probably does not exist." << "\n";
exit(FILE_NOT_OPENED);
}
while (!file.eof()) {
file.read(tmp, NAME_SIZE);
points[tmp].val++;
}
file.close();
vector<pair<string, zuint>> pointscpy(points.begin(), points.end());
points.clear();
sort(
pointscpy.begin(),
pointscpy.end(),
[](pair<string, zuint> v1, pair<string, zuint> v2) {
return v1.second.val > v2.second.val;
}
);
for(int i=0;i<pointscpy.size(); i++){
cout << i + 1 << ". " << pointscpy[i].first << ": " << pointscpy[i].second.val << "\n";
}
return EXIT_SUCCESS;
} | {
"domain": "codereview.stackexchange",
"id": 43325,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, stl",
"url": null
} |
c++, stl
return EXIT_SUCCESS;
}
Answer: That long line of using is problematic. First, it's far too long (it's not even sorted, which might explain why std::string appears twice). Secondly, it looks like you've been told to avoid using namespace std; but have heard only half the reason it's a bad idea. Those many usings tend to obscure which identifiers in your code are from the library and which are your own. I really recommend you drop that habit and start referring to things by their full names most of the time.
size_t and uint16_t are never defined. I'm guessing you meant std::size_t and std::uint16_t (the latter from <cstdint> header). It's not clear why you need an exactly-16-bit type for this simple counting - what's wrong with std::uint_fast16_t? Or even a plain unsigned int? Other identifiers not defined include exit (presumably std::exit from <cstdlib>) and EXIT_SUCCESS (also from <cstdlib>).
The zuint structure doesn't seem to provide any benefit over using the integer type directly.
The tmp array doesn't need to be scoped to the whole function - it can be temporary, as the name suggests, within the read loop.
No need to write two separate literal strings to std::cerr - combine them into a single string:
std::cerr << "File not opened. 'data.bin' probably does not exist.\n"; | {
"domain": "codereview.stackexchange",
"id": 43325,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, stl",
"url": null
} |
c++, stl
Perhaps consider std::perror (from <cstdio>) as an alternative error reporting function which provides more information.
The loop is flawed (testing for eof before reading is a known anti-pattern). When istream::read() fails, we haven't populated tmp and shouldn't be adding an entry. Even when it fails, we're not defensive against malformed data (missing final null character). It's better to read into an oversize buffer and supply the null even if it's absent in the input.
Consider using std::unordered_map instead of std::map when we don't care about the order of its elements. That will likely be more performant when there are many different names in the file.
We can save writing long types in full, by taking advantage of auto.
The comparator we pass to std::sort can avoid copying strings, by accepting references to pairs.
We don't need to return success value at the end of main() - the main function is magic, and simply running off the end implies a return value of 0.
Modified code
#include <algorithm>
#include <cerrno>
#include <cstdlib>
#include <cstring> // for strerror()
#include <fstream>
#include <iostream>
#include <unordered_map>
#include <vector>
constexpr std::size_t name_size = 20;
const char* file_name = "data.bin";
int main()
{
std::ifstream file(file_name, std::ios::in | std::ios::binary);
if (!file) {
std::cerr << file_name << ": " << std::strerror(errno) << '\n';
return EXIT_FAILURE;
}
std::unordered_map<std::string, unsigned int> points;
{
char name[name_size + 1];
name[name_size] = '\0';
while (file.read(name, name_size)) {
++points[name];
}
}
if (!file.eof()) {
std::cerr << file_name << ": " << std::strerror(errno) << '\n';
return EXIT_FAILURE;
}
std::vector<std::pair<std::string, unsigned int>>
pointscpy(points.begin(), points.end()); | {
"domain": "codereview.stackexchange",
"id": 43325,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, stl",
"url": null
} |
c++, stl
std::sort(pointscpy.begin(), pointscpy.end(),
[](auto const& v1, auto const& v2) {
return v1.second > v2.second;
});
int i = 0;
for (auto const& p: pointscpy) {
std::cout << ++i << ". " << p.first << ": " << p.second << '\n';
}
}
Future directions
Instead of hard-coding the file name in the program, accept it as a run-time argument, and/or accept input on the standard input stream so that it can be used as a filter. | {
"domain": "codereview.stackexchange",
"id": 43325,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, stl",
"url": null
} |
python, beginner, python-3.x, tic-tac-toe
Title: A Simple Tic-Tac-Toe Game
Question: I wrote a simple tic-tac-toe game in Python. I'm pretty much a novice, but I do have some experience with coding other things in Python. I just wanted to see if I was capable of writing a simple tic-tac-toe game, since I never really went through that rite of passage. I realized it wasn't that difficult for me, but I think I'm lacking knowledge to take me to the next level. My code utilizes a lot of if-else statements and I feel like I could do a better job with using functions. Here is the code:
table = {
"a1": " ",
"a3": " ",
"a2": " ",
"b1": " ",
"b2": " ",
"b3": " ",
"c1": " ",
"c2": " ",
"c3": " ",
}
def check_win(letter):
if table["a1"] == letter and table["a2"] == letter and table["a3"] == letter:
print(f"Player {letter} wins")
return False
elif table["b1"] == letter and table["b2"] == letter and table["b3"] == letter:
print(f"Player {letter} wins")
return False
elif table["c1"] == letter and table["c2"] == letter and table["c3"] == letter:
print(f"Player {letter} wins")
return False
elif table["c1"] == letter and table["b2"] == letter and table["a3"] == letter:
print(f"Player {letter} wins")
return False
elif table["c3"] == letter and table["b2"] == letter and table["a1"] == letter:
print(f"Player {letter} wins")
return False
elif table["a1"] == letter and table["b1"] == letter and table["c1"] == letter:
print(f"Player {letter} wins")
return False
elif table["a2"] == letter and table["b2"] == letter and table["c2"] == letter:
print(f"Player {letter} wins")
return False
elif table["a3"] == letter and table["b3"] == letter and table["c3"] == letter:
print(f"Player {letter} wins")
return False
else:
return True | {
"domain": "codereview.stackexchange",
"id": 43326,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x, tic-tac-toe",
"url": null
} |
python, beginner, python-3.x, tic-tac-toe
game_on = True
display_table = f"""
1 2 3
a | {table["a1"]} | {table["a2"]} | {table["a3"]} |
b | {table["b1"]} | {table["b2"]} | {table["b3"]} |
c | {table["c1"]} | {table["c2"]} | {table["c3"]} |
"""
print(display_table)
count = 0
while game_on:
x_location = input("Player X: Pick a row and column (e.g. a1, a2, etc.): ").lower()
check_x = True
while check_x:
if table[x_location] == " ":
table[x_location] = "X"
count += 1
check_x = False
else:
x_location = input("That is an invalid spot. Please try again: ").lower()
check_x = True
display_table = f"""
1 2 3
a | {table["a1"]} | {table["a2"]} | {table["a3"]} |
b | {table["b1"]} | {table["b2"]} | {table["b3"]} |
c | {table["c1"]} | {table["c2"]} | {table["c3"]} |
"""
print(display_table)
game_on = check_win("X")
if game_on == False:
break
if count >= 9:
print("There is no winner")
break
o_location = input("Player O: Pick a row and column (e.g. a1, a2, etc.): ")
check_o = True
while check_o:
if table[o_location] == " ":
table[o_location] = "O"
count += 1
check_o = False
else:
y_location = input("That is an invalid spot. Please try again: ").lower()
check_o = True
display_table = f"""
1 2 3
a | {table["a1"]} | {table["a2"]} | {table["a3"]} |
b | {table["b1"]} | {table["b2"]} | {table["b3"]} |
c | {table["c1"]} | {table["c2"]} | {table["c3"]} |
"""
print(display_table)
game_on = check_win("O")
if game_on == False:
break | {
"domain": "codereview.stackexchange",
"id": 43326,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x, tic-tac-toe",
"url": null
} |
python, beginner, python-3.x, tic-tac-toe
game_on = check_win("O")
if game_on == False:
break
I'm trying to figure out a way where I can simplify the code in the check_win function. What can I do instead of writing so many lines of different if/elif statements?
I also think I could put the recurring display_table and print(display_table) within another function, but I'm not sure how I could easily update the actual table since it would be local variable within a function.
Any other suggestions for improvement are appreciated.
Answer: Put all code in functions. This is what experienced programmers do, so you
would be wise to adopt the practice even if you don't fully appreciate all of
the reasons yet. After that change, you'll end up with a program having the
following structure. Note that this change requires us to pass the table into
check_win() as an argument, but that's an easy and reasonable change.
def main():
table = {...}
...
def check_win(table, letter):
...
if __name__ == '__main__':
main()
Use functions to eliminate duplication: displaying the table. You
build a display table in several places. Put the code in one
spot: inside a function.
# The function.
def display_table(table):
return f"""
1 2 3
a | {table["a1"]} | {table["a2"]} | {table["a3"]} |
b | {table["b1"]} | {table["b2"]} | {table["b3"]} |
c | {table["c1"]} | {table["c2"]} | {table["c3"]} |
"""
# A usage example:
print(display_table(table)) | {
"domain": "codereview.stackexchange",
"id": 43326,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x, tic-tac-toe",
"url": null
} |
python, beginner, python-3.x, tic-tac-toe
"""
# A usage example:
print(display_table(table))
Use functions to eliminate duplication: handling different players. The
main() functions is basically two large chunks of duplicate code, one for X
and one for O. That means every code edit has to be make in two places, which
is annoying and error-prone. Put the behavior in a function, passing in any
needed parameters as arguments. If we just make that change (and remove the
unnecessary check variable), we get this:
def make_play(table, letter):
location = input(f"Player {letter}: Pick a row and column (e.g. a1, a2, etc.): ").lower()
while True:
if table[location] == " ": # What should you do if location not in table?
table[location] = letter
break
else:
location = input("That is an invalid spot. Please try again: ").lower()
print(display_table(table))
Use a variable to eliminate duplication: tightening up the main logic
further. After that change, you'll notice some more annoying duplication in
main(). In this case, we can deal with the situation by having a player
variable and just toggling back and forth between the players. Again, the boolean flag
isn't really helping much so we can drop it. Note that this method of toggling
the players is fairly crude, but you'll learn about nicer ways as you go
forward with Python. Also note that the count variable is unneeded: just
write a function to take the table and return true or false based on the
whether the dict contains any spaces.
def main():
...
count = 0
player = 'X'
while True:
make_play(table, player)
count += 1
if not check_win(table, player):
break
elif count >= 9: # Not needed. Write a function.
print("There is no winner")
break
else:
player = 'O' if player == 'X' else 'X' | {
"domain": "codereview.stackexchange",
"id": 43326,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x, tic-tac-toe",
"url": null
} |
python, beginner, python-3.x, tic-tac-toe
Use boolean logic or a data structure to eliminate duplication. If
you are following the logic so far, the check_win() function will seem super
annoying at this point: it repeats the same print and return statements eight
times. One approach is to combine the checks into a single logical test:
that at least eliminates the duplicate print and return statements.
Even better is to define a data structure to define the checks.
While you're considering such changes, you might want to alter check_win()
to return true if there's a winner, which makes more sense given the other
edits proposed so far. Also, the printing would be better done in main() than in the win checking code.
# Boolean combination.
def check_win(table, letter):
won = (
(table["a1"] == letter and table["a2"] == letter and table["a3"] == letter) or
(table["b1"] == letter and table["b2"] == letter and table["b3"] == letter) or
etc...
)
if won:
print(f"Player {letter} wins")
return False
else:
return True
# A data structure to drive the logic.
CELL_GROUPS = (
("a1", "a2", "a3"),
("b1", "b2", "b3"),
...
)
def check_win(table, letter):
for cg in CELL_GROUPS:
if all(table[cell] == letter for cell in cg):
print(f"Player {letter} wins") # Do this in main()
return False # Reverse.
return True # Reverse. | {
"domain": "codereview.stackexchange",
"id": 43326,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x, tic-tac-toe",
"url": null
} |
comparative-review, scala
Title: Batching method implementation - Scala
Question: I need to implement a function/method that operates on a sequence of values, and acts kind of like takeWhile, but with 2 differences, first, it doesn't act on a single element, it is performed on a sequence of elements, second, it won't just return after the predicate is satisfied for the first time, it will keep going until all those values inside the main sequence are grouped together. I might've not explained it very well, so let me provide an example. I have these values inside the sequence:
val seq = Seq(1, 4, 2, 4, 2, 5, 6, 7, 1, 9, 2, 3, 4)
And I want to group these values inside some inner sequences, that the sum of all the values inside inner sequences is less than or equal to 10:
val result: Seq[Seq[Int]] = Seq(Seq(1, 4, 2), Seq(4, 2), Seq(5), Seq(6), Seq(7), Seq(1, 9), Seq(2, 3, 4))
Notes:
The order does not matter
Each sequence should be as large as it can be, for instance, first element of the result could've been Seq(1, 4), or Seq(1), but I want it to be the biggest number possible.
I have 2 different implementations, I wanted to know which one is better? Based on performance, readability or anything else.
If anyone also has a better approach, I will be glad to see.
implicit class SeqOps[T](seq: Seq[T]) {
// approach #1
def batchUntil(predicate: Seq[T] => Boolean): Seq[Seq[T]] =
seq.foldLeft[Seq[Seq[T]]](z = Nil)(
(acc, currentElem) => acc.headOption.collect {
case currentAggregator if predicate(currentElem +: currentAggregator) =>
(currentElem +: currentAggregator) +: acc.tail
case _ =>
(currentElem :: Nil) +: acc
}.getOrElse(Seq(currentElem :: Nil))
)
// END of approach #1
// Approach #2
def partitionedUnordered(predicate: Seq[T] => Boolean): Seq[Seq[T]] = partitioningHelper(seq, Nil, Nil)(predicate) | {
"domain": "codereview.stackexchange",
"id": 43327,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "comparative-review, scala",
"url": null
} |
comparative-review, scala
@tailrec
private def partitioningHelper(remainder: Seq[T], acc: Seq[Seq[T]], currentAggregator: Seq[T])(predicate: Seq[T] => Boolean): Seq[Seq[T]] = {
if (remainder.isEmpty) {
if (currentAggregator.isEmpty) acc
else currentAggregator +: acc
}
else {
val newAgg = remainder.head +: currentAggregator
if (predicate(newAgg)) partitioningHelper(remainder.tail, acc, newAgg)(predicate)
else partitioningHelper(remainder.tail, currentAggregator +: acc, remainder.head +: Nil)(predicate)
}
}
}
And if you're wondering about why on earth a human being should do this, is that I need to chunk some load of data into small JSON arrays that each are smaller than 1MB, so imagine an array of Json objects (total 100MB), I need to batch it like:
Seq([first array 970KB], [second array 995KB], ...)
Answer: Both implementations are perfectly reasonable, but they don't always produce the same result.
Seq(9).batchUntil(_.sum < 0) //Seq(Seq(9))
Seq(9).partitionedUnordered(_.sum < 0) //Seq(Seq(9), Seq())
I'm not a fan of long lines, i.e. horizontal code, and I find the nested if...else in the @tailrec approach (#2) rather difficult to parse and reason about.
The foldLeft() approach (#1) can be more concise and, I think, made clearer by utilizing the power of pattern matching.
def batchUntil(predicate: Seq[T] => Boolean): Seq[Seq[T]] =
seq.foldLeft[Seq[Seq[T]]](Seq()) {
case (acc@currentAggregator+:remainder, currentElem) =>
val newAgg = currentElem +: currentAggregator
if (predicate(newAgg)) newAgg +: remainder
else Seq(currentElem) +: acc
case (Seq(), currentElem) => Seq(Seq(currentElem))
} | {
"domain": "codereview.stackexchange",
"id": 43327,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "comparative-review, scala",
"url": null
} |
comparative-review, scala
You'll note that I don't use :: or Nil. Your code indicates some confusion between Seq operations like +:, and List operations using :: and Nil.
Seq is a trait so it's not really a concrete collection type, more like an interface of methods common to multiple real collections such as List and Vector.
Methods such as batchUntil() might take a passed parameter of type Seq[T] to indicate that the calling code can pass any concrete collection type as long as it's a member of the Seq family. Returning a Seq, on the other hand, is seldom advisable. It hides the underlying concrete collection type from the receiver.
It is possible to take multiple collection types and return the same type as received, but that's a bit beyond the scope of this code review. | {
"domain": "codereview.stackexchange",
"id": 43327,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "comparative-review, scala",
"url": null
} |
python, pandas
Title: Create new columns based on existing columns
Question: The code:
excluded_columns = ['sort_id', 'weekday', 'sort']
for pct_col in sort_df.columns:
if pct_col in excluded_columns:
continue
else:
sort_df[pct_col + '_pct'] = (sort_df[pct_col] / sort_df['volume'] * 100)
There are no specific concerns I have with this code, it just looks off. I know pandas is quite liberal when it comes to how you choose to achieve the desired outcome, but I just get a funky smell from this code. How could it be more pythonic/pandonic?
Answer: Don't loop. Pandas is designed to be vectorised, which means that 99% of the time when you imagine an operation to require a loop, that loop should be baked into some Numpy or Pandas call rather than you writing it out.
In your case, let's invent a raft of totally bogus data since you haven't shown anything real. We then exclude columns via a negated isin, vectorise-divide via div, and concatenate to a new dataframe:
import pandas as pd
from numpy.random import default_rng
rand = default_rng(seed=0)
sort_df = pd.DataFrame(
rand.uniform(low=0, high=100, size=(100, 7)),
columns=(
'sort_id', 'weekday', 'sort', 'volume', 'bananas', 'pears', 'apples',
)
)
excluded_cols = {'sort_id', 'weekday', 'sort', 'volume'}
to_divide = sort_df.loc[:, ~sort_df.columns.isin(excluded_cols)].add_suffix('_pct')
percents = to_divide.div(sort_df.volume/100, axis='rows')
sort_df = pd.concat((sort_df, percents), axis='columns')
It's likely that volume missing from excluded_cols is an oversight, since it doesn't make sense to divide it by itself and always get 100%. | {
"domain": "codereview.stackexchange",
"id": 43328,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, pandas",
"url": null
} |
java, csv, homework
Title: Analyzing baby name data in CSV files
Question: First time using code review. I am still a student so there will be a lot to be desired.
Basically as part of the homework we are told what methods to create (Method names are given with their parameters). We essentially are parsing a bunch of files or raw CSV data looking for either specific names at a rank, names at a specific rank, total births, etc. The code does exactly what it is meant to and works but I feel it could seriously be improved if not minimised somehow. Feel free to be as harsh as possible, I am looking for serious feed back.
Examples of the CSV data would be:
2012(Test CSV File)
Sophia,F,10
Emma,F,9
Isabella,F,8
Olivia,F,7
Ava,F,6
Jacob,M,8
Mason,M,7
Ethan,M,7
Noah,M,6
William,M,5
2013 (Test CSV file)
Sophia,F,10
Emma,F,8
Olivia,F,8
Isabella,F,7
Ava,F,6
Noah,M,12
Liam,M,9
Jacob,M,8
Mason,M,8
William,M,7
To clarify the CSV data files do get larger. This is merely for testing purposes.
You may see that a few methods have not been implemented yet, this is merely so that I may adjust it according to any suggestions going forward. The return statements have been slightly modified from the assignment credentials, however we are allowed to do this as part of the "recommendations" is to work with ArrayLists, LinkedHashMaps, TreeMaps, etc.
Could I get some feed back on how I could improve the below code?
import edu.duke.*;
import org.apache.commons.csv.*;
import java.io.*;
import java.util.*;
/*import java.util.Array;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
*/ | {
"domain": "codereview.stackexchange",
"id": 43329,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, csv, homework",
"url": null
} |
java, csv, homework
public class parseBabies{
public static void main(String args[])
{
parseBabies namePopularity = new parseBabies();
//namePopularity.testGetRank();
//namePopularity.testGetName();
// namePopularity.testWhatIsNameInYear();
namePopularity.testYearOfHighestRank();
}
void println(Object obj)
{
System.out.println(obj);
}
public CSVParser parseData(FileResource fr){
// No header row in this CSV data, hence false
CSVParser parser = fr.getCSVParser(false);
return parser;
}
public LinkedHashMap<String,Integer> totalBirths(CSVParser parser)
{
LinkedHashMap<String, Integer> totalsList = new LinkedHashMap<String, Integer>();
int totalFemales = 0;
int totalMales = 0;
int total = 0;
int nameOccurances = 0;
for(CSVRecord record : parser)
{
String firstName = record.get(0);
String gender = record.get(1);
nameOccurances = Integer.parseInt(record.get(2));
if(gender == "M") totalMales += nameOccurances;
if(gender == "F") totalFemales += nameOccurances;
total += nameOccurances;
}
totalsList.put("Females",totalFemales);
totalsList.put("Males",totalMales);
totalsList.put("Total", total);
println("Total females: "+ totalFemales);
println("Total males: "+totalMales);
println("Total births: "+ total);
return totalsList;
}
public List<Map.Entry<String, Integer>> createNameRanks(FileResource fr, String gender)
{
CSVParser parser = parseData(fr); | {
"domain": "codereview.stackexchange",
"id": 43329,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, csv, homework",
"url": null
} |
java, csv, homework
LinkedHashMap<String, Integer> maleRank = new LinkedHashMap<String, Integer>();
LinkedHashMap<String, Integer> femaleRank = new LinkedHashMap<String, Integer>();
LinkedHashMap<String, Integer> allNamesRank = new LinkedHashMap<String, Integer>();
List<Map.Entry<String,Integer>> rankList = new ArrayList<Map.Entry<String, Integer>>();
if(parser == null) return rankList;
for(CSVRecord record : parser){
if(record.get(1).toUpperCase().equals("M")){
maleRank.put(record.get(0), Integer.parseInt(record.get(2)));
}
if(record.get(1).toUpperCase().equals("F")){
femaleRank.put(record.get(0), Integer.parseInt(record.get(2)));
}
allNamesRank.put(record.get(0), Integer.parseInt(record.get(2)));
}
switch(gender){
case("M"):
rankList = sortRankMaps(maleRank);
return rankList;
case("F"):
rankList = sortRankMaps(femaleRank);
return rankList;
default:
rankList = sortRankMaps(allNamesRank);
return rankList;
}
} | {
"domain": "codereview.stackexchange",
"id": 43329,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, csv, homework",
"url": null
} |
java, csv, homework
public List<Map.Entry<String, Integer>> sortRankMaps(LinkedHashMap<String, Integer> names)
{
List<Map.Entry<String, Integer>> rankList = new ArrayList<Map.Entry<String, Integer>>(names.entrySet());
Collections.sort(
rankList,
new Comparator<Map.Entry<String, Integer>>(){
public int compare(Map.Entry<String, Integer> entry1,
Map.Entry<String, Integer> entry2)
{
return -entry1.getValue() + entry2.getValue();
}
});
//println(rankList);
return rankList;
}
public LinkedHashMap<Integer,ArrayList<String>> getRank(FileResource fr, Integer year, String name, String gender)
{
List<Map.Entry<String, Integer>> nameRank = new ArrayList<Map.Entry<String, Integer>>();
ArrayList<String> namesMatched = new ArrayList<String>();
LinkedHashMap<Integer,ArrayList<String>> matches = new LinkedHashMap<Integer,ArrayList<String>>();
if(fr == null){
namesMatched.add("NO MATCHES");
matches.put(0, namesMatched);
return matches;
}
int totalRanks = 0;
int ranking = 0;
nameRank = createNameRanks(fr, gender); | {
"domain": "codereview.stackexchange",
"id": 43329,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, csv, homework",
"url": null
} |
java, csv, homework
int ranking = 0;
nameRank = createNameRanks(fr, gender);
for(Map.Entry<String,Integer> entry : nameRank)
{
totalRanks++;
if(entry.getKey().equals(name))
{
for(Map.Entry<String,Integer> dupValues : nameRank)
{
if(entry.getValue().equals(dupValues.getValue())
&& !entry.getKey().equals(dupValues.getKey()))
{
namesMatched.add(dupValues.getKey());
}
ranking = totalRanks - (namesMatched.size());
}
}
}
namesMatched.add(name);
// println("Names Matched: " + namesMatched + " at rank: "+ranking);
matches.put(ranking, namesMatched);
return matches;
}
public void testGetRank()
{
FileResource fr = new FileResource();
LinkedHashMap<Integer,ArrayList<String>> rank = getRank(fr, 2012, "Mason", "M");
}
public ArrayList<String> getName(Integer year, Integer rank, String gender)
{
FileResource fr = new FileResource();
String nameVsRank = new String();
List<Map.Entry<String, Integer>> nameRank = new ArrayList<Map.Entry<String, Integer>>();
nameRank = createNameRanks(fr, gender);
ArrayList<String> names = new ArrayList<String>();
if(rank > nameRank.size()){
names.add("NO NAME");
return names;
}
int count = 0; | {
"domain": "codereview.stackexchange",
"id": 43329,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, csv, homework",
"url": null
} |
java, csv, homework
int count = 0;
for(Map.Entry<String,Integer> entry : nameRank){
count++;
if(count == rank){
for(Map.Entry<String, Integer> dupEntry : nameRank){
if(entry.getValue().equals(dupEntry.getValue()) && !entry.getKey().equals(dupEntry.getKey()))
names.add(dupEntry.getKey());
}
names.add(entry.getKey());
}
}
return names;
}
public void testGetName()
{
ArrayList<String> nameAtRank = getName(2014, 3, "M");
println("Name at rank : "+ nameAtRank);
}
public ArrayList<String> whatIsNameInYear(FileResource fr, String name, Integer year, Integer newYear, String gender)
{
LinkedHashMap<Integer, ArrayList<String>> nameRank = getRank(fr, year, name, gender);
ArrayList<String> namesAtRank = new ArrayList<String>();
for(Integer key : nameRank.keySet())
{
namesAtRank = getName(year, key, gender);
}
return namesAtRank;
}
public void testWhatIsNameInYear()
{
FileResource fr = new FileResource();
ArrayList<String> nameInYear = whatIsNameInYear(fr,"Isabella", 2012, 2014, "F");
println("Isabella in 2014 is equivalent to: " + nameInYear);
}
public ArrayList<Integer> yearOfHighestRank(Integer year, String name, String gender)
{
DirectoryResource dr = new DirectoryResource();
LinkedHashMap<Integer,ArrayList<String>> nameRank = new LinkedHashMap<Integer, ArrayList<String>>();
ArrayList<Integer> highestRankEver = new ArrayList<Integer>();
int highestRanking = 99999;
int highestRankingYear = year; | {
"domain": "codereview.stackexchange",
"id": 43329,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, csv, homework",
"url": null
} |
java, csv, homework
int highestRanking = 99999;
int highestRankingYear = year;
if(name == null || gender == null){
highestRankEver.add(-1);
return highestRankEver;
}
for(File f : dr.selectedFiles()){
FileResource fr = new FileResource(f);
nameRank = getRank(fr, year, name, gender);
println("FileResource: "+fr);
println("Name Rank: " + nameRank);
for(Map.Entry<Integer, ArrayList<String>> entries : nameRank.entrySet())
{
//highestRanking = entries.getKey();
println("Entries: " + entries);
println("Entries key: " + entries.getKey());
if(entries.getKey() < highestRanking)
{
highestRanking = entries.getKey();
highestRankingYear = year;
println("Highest Rank so Far: "+ highestRanking + ", "+ highestRankingYear);
}
}
year++;
}
println("HighestRank: "+ highestRanking +" in year: "+highestRankingYear);
highestRankEver.addAll(Arrays.asList(highestRanking, highestRankingYear));
return highestRankEver;
}
public void testYearOfHighestRank(){
ArrayList<Integer> mostPopularYear = yearOfHighestRank(2012,"Mason","M");
println("Most Popular Year: " +mostPopularYear);
}
} | {
"domain": "codereview.stackexchange",
"id": 43329,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, csv, homework",
"url": null
} |
java, csv, homework
Answer: This will be difficult to review without access to the edu.duke package so my review will be superficial.
parseBabies is a poor class name: first of all it has non-standard case, and it's made to look like a function when it's a class. Prefer instead BabyParser.
Commented-out code like
//namePopularity.testGetRank();
//namePopularity.testGetName();
// namePopularity.testWhatIsNameInYear();
must be deleted.
The println function should be deleted. It offers nothing over System.out.println. If you're worried about the length of the latter, do a static import for out.
commons-csv includes a get by name. Use that instead of get by index.
Occurances is spelled Occurrences.
totalsList is not a list, so don't call it one. It's a map. But it shouldn't even be a map: the way you're using it, it should be a dedicated class with members of Females, Males and Total. A more flexible and useful method would not look specifically at F and M, but would sum up totals for any gender and return a map of gender string to total.
namesMatched.add("NO MATCHES"); seems like a bad idea, mixing error data in-band with domain data. If you need to indicate that there are no matches, this should probably be done elsewhere.
This loop:
for(Integer key : nameRank.keySet())
{
namesAtRank = getName(year, key, gender);
}
return namesAtRank;
is strange: it reassigns namesAtRank unconditionally for every single entry in nameRank. Surely that isn't necessary, right? If you only care about the last key in the key set (for some arbitrary definition of "last"), there are better ways.
This:
println("HighestRank: "+ highestRanking +" in year: "+highestRankingYear);
should be converted to an out.printf. | {
"domain": "codereview.stackexchange",
"id": 43329,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, csv, homework",
"url": null
} |
python, array, hash-map
Title: Porting PHP's array_push to Python
Question: I am new to Python but not new to PHP. I've started porting PHP APIs to Python hoping to learn the Python language along the way, currently trying to grasp List, Dict, Set, Tuple. I tried writing PHP's array_push() in Python:
def array_push(array: list | dict, *args: any) -> int:
if isinstance(array, list):
for arg in args:
# i wonder why list.append() doesn't take *args
array.append(arg)
return len(array)
elif isinstance(array, dict):
# wouldn't surprise me if there's a significantly faster way to do this,
# but this the first solution I could think of that worked
key = -1
# i tried using key = max(array.keys()), but that breaks if the dict has string keys..
for existingkey in array.keys():
if isinstance(existingkey, int) and existingkey > key:
key = existingkey
for arg in args:
# loop should not be needed because we already started with the highest key?
# while key in array:
key += 1
array[key] = arg
return len(array)
else:
raise TypeError(
"array_push() expects a list or dict as first argument, got " + str(type(array)))
and some tests:
l = ["foo", "bar", "baz"]
array_push(l, 1, "foo", 9, 9)
print(l) # prints ['foo', 'bar', 'baz', 1, 'foo', 9, 9]
d = {5: "five already exist, terrific..", 6: "as does 6..",
"string key": "it has a string key too", 2: "2 comes after 5, hurray"}
array_push(d, 1, "foo", 9, 9)
print(d) # prints {5: 'five already exist, terrific..', 'string key': 'it has a string key too', 2: '2 comes after 5, hurray', 6: 1, 7: 'foo', 8: 9, 9: 9}
array_push(5, 5) # TypeError: array_push() expects a list or dict as first argument, got <class 'int'>
Answer: The list case. As noted in a comment, you can simplify to this:
array.extend(args) | {
"domain": "codereview.stackexchange",
"id": 43330,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, array, hash-map",
"url": null
} |
python, array, hash-map
Answer: The list case. As noted in a comment, you can simplify to this:
array.extend(args)
The dict case. It looks like the goal is to find the max integer key, if
any, which can be done more easily using the max() function. Once
you have that, you can build a range to represent the desired keys
and then zip them together with the values.
# Max integer key, or -9 if none.
gen = (k for k in array if isinstance(k, int))
max_int_key = max(gen, default = -9)
# Initial key for added items.
k = 1 + max(-1, max_int_key)
# Update.
rng = range(k, k + len(args))
array.update(zip(rng, args)) | {
"domain": "codereview.stackexchange",
"id": 43330,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, array, hash-map",
"url": null
} |
python, array, hash-map
# Update.
rng = range(k, k + len(args))
array.update(zip(rng, args))
If you're writing code like this, build on top of a solid testing
foundation. It's good that your question was framed with some example test
cases. However, they are too informal, since they are based on printing and
comments. Mimicking an API, even just for learning, requires some real
diligence to explore edge cases. Do yourself a favor and write some code to
execute those tests automatically. This could take the form of learning how to
use a Python test framework (I would recommend pytest), or just writing some
code of your own to execute the tests and to print loud debugging messages if
the results don't equal expectations (I did the latter while experimenting
with your code).
This PHP-inspired function is in tension with typical Python design. I rarely write
a Python function that mutates its arguments – indeed, I view it as an
anti-pattern and need some fairly strong reasons to deviate from that general
principle. If you have an object that has legitimate needs for mutation, do it
in a proper class, with methods. That, after all, is what the built-in list
and dict classes do: xs.append(...), xs.extend(...), d.update(...), and
so forth – it's mutation via method calls. Functions, by contrast, are at
their best when they leave their arguments unmolested. Of course, there are
exceptions to every rule, and it's fine that you're doing
this mainly to practice. Just recognize that the thing you've
built is unusual from the perspective of an experienced Python
programmer. | {
"domain": "codereview.stackexchange",
"id": 43330,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, array, hash-map",
"url": null
} |
python
Title: Table Printer Project - Automate the Boring Stuff Chapter 6
Question: The project outline:
Write a function named printTable() that takes a list of lists of
strings and displays it in a well-organized table with each column
right-justified. Assume that all the inner lists will contain the same
number of strings.
My code:
def demo():
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David',],
['dogs', 'cats', 'moose', 'goose']]
return tableData
def printTable(tableData):
colWidths = [0] * len(tableData)
for i in range(len(tableData)):
colWidths[i] = len(max(tableData[i], key=len))
for x in range(len(tableData[0])):
for y in range(len(tableData)):
print(tableData[y][x].rjust(colWidths[y]), end=' ')
print(end='\n')
printTable(demo())
This took me a while to get my head around. I ended up using max() which the book hasn't covered yet but otherwise I think this is what the author had in mind.
Ways to make it better?
Answer: One rarely needs to iterate over collections via indexes. Iterate over
the thing itself (the list, tuple, or dict), not the indexes-of-the-thing.
# No.
for i in range(len(table)):
col = table[i]
...
# Yes.
for col in table:
...
# Yes (if you also need the indexes).
for i, col in enumerate(table):
... | {
"domain": "codereview.stackexchange",
"id": 43331,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
# Yes (if you also need the indexes).
for i, col in enumerate(table):
...
Functions should return data, not print. Your book is giving bad direction
by encouraging students to think about functions as printing utilities.
Printing is a trivial operation and has no bearing on the interesting parts of
this exercise -- namely computing the column widths and transposing the data.
The function you write should take data as input (the column-oriented table
data) and should return data (width-padded, row-oriented table data). The
function below illustrates one way to achieve that. Much more important than
the specific code is the general principle: write functions that take data and
return data, not functions that have side effects (like printing). Among other
advantages, a function like this can be easily subjected to automated testing.
def padded_table(table):
widths = [
max(len(cell) for cell in col)
for col in table
]
return [
[cell.rjust(w) for cell, w in zip(row, widths)]
for row in zip(*table) # Transpose the table.
]
Do the printing elsewhere. After writing a sensible data-centric function,
the printing is completely uninteresting.
def main():
table = [
['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David',],
['dogs', 'cats', 'moose', 'goose'],
]
for row in padded_table(table):
print(' '.join(row)) # Super boring!
if __name__ == '__main__':
main() | {
"domain": "codereview.stackexchange",
"id": 43331,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python, beginner, python-3.x, file-system
Title: Automate the Boring Stuff CH 10 - filling in the gaps
Question: This exercise comes from Automate the Boring Stuff CH 10 - second edition. The exercise is called "filling in the gaps," and the instructions are as follows:
Write a program that finds all files with a given prefix, such as spam001.txt, spam002.txt, and so on, in a single folder and locates any gaps in the numbering (such as if there is a spam001.txt and spam003.txt but no spam002.txt). Have the program rename all the later files to close this gap.
I wrote two versions of this exercise. My first version was shorter than the second version, but the problem was that all the logic was contained in a single function. So I rewrote the code to separate it into multiple functions, and the result is posted here below. I have two major concerns with the logic of this program:
I believe that my logic is closer to a functional programming style, but I would like to better understand how I could approach this code from an object-oriented style
I am not sure that how I chose to organize the data is the best approach. This is something that I learned from this forum the last time I posted here, and since I am somewhat of a beginner, I'm attempting to develop a better understanding of data structures and how to organize data properly.
#! python3
# fill_gaps.py -- search a single folder, find gaps in numbered files (ex. spam001.txt, spam003.txt)
# and rename later files to fill in the gaps.
import re, os, shutil
from pathlib import Path
def return_match_object(prefix: str) -> re.Match:
# Remove numbers from prefix using a regex, then separate letters and numbers into groups
return re.compile("(\D*)(\d*)").search(prefix) | {
"domain": "codereview.stackexchange",
"id": 43332,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x, file-system",
"url": null
} |
python, beginner, python-3.x, file-system
def check_user_input(folder: str, regex_mo: re.Match) -> str | bool:
if regex_mo is None:
return "Invalid prefix. Prefix contains no letters or numbers."
elif os.path.isdir(folder) == False:
return "Invalid folder. Argument must be a valid folder path."
else:
return False
def create_file_list(regex_mo: re.Match) -> list:
# Search folder for letters and add matches to a list
letters = regex_mo.group(1)
file_list = [i for i in os.listdir(".") if letters in i]
return file_list
def create_number_list(file_list: list, regex_mo: re.Match) -> list:
# search match_list for numbers and add them to a list
number_list = []
for file_name in file_list:
mo = return_match_object(file_name)
number_list.append(int(mo.group(2)))
return number_list
def fill_gaps(
file_list: list,
number_list: list,
folder: str,
number_prefix_length: int,
letters: str,
) -> list:
# Rename later files to fill in gaps
return_list = []
for index, number in enumerate(number_list, 1):
if index not in number_list:
zeroes_to_add = "0" * (number_prefix_length - len(str(index)))
suffix = Path(folder + "\\" + file_list[0]).suffix
shutil.move(
folder + "\\" + file_list[-1],
folder + "\\" + letters + zeroes_to_add + str(index) + suffix,
)
return_list.append(
"renamed "
+ file_list[-1]
+ " to "
+ letters
+ zeroes_to_add
+ str(index)
+ suffix
)
return return_list | {
"domain": "codereview.stackexchange",
"id": 43332,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x, file-system",
"url": null
} |
python, beginner, python-3.x, file-system
return return_list
def main() -> None:
while True:
folder = input("Please enter a folder to search for files\n")
prefix = input("Please enter a prefix to search for, such as spam000\n")
match_object = return_match_object(prefix)
letters = match_object.group(1)
number_prefix_length = len(match_object.group(2))
# check for valid user input
if type(check_user_input(folder, match_object)) == str:
continue
else:
# main program execution
os.chdir(folder)
file_list = create_file_list(match_object)
number_list = create_number_list(file_list, match_object)
print(
fill_gaps(file_list, number_list, folder, number_prefix_length, letters)
)
break
if __name__ == "__main__":
main()
Answer:
I believe that my logic is closer to a functional programming style
It isn't, and new developers often confuse this with procedural programming; yours is the latter.
Otherwise:
Avoid os and shutil when Path has the same functionality with more convenient representation
This application does not need regular expressions. Globs are more rudimentary, but fit the job. Internally they use regular expressions anyway, but it's still probably a good idea to use the more constrained interface.
I don't think that you should exclude prefixes that have no numbers. And I think that your definition of prefix is a little odd. The word "spam" alone should be your prefix.
check_user_input should not return string-or-bool; it should throw-or-not.
create_file_list would be well-represented by a generator function.
You can replace listdir with glob.
Consider separating your gap identification code from your renaming code.
Example
This example code addresses the above and demonstrates an object-oriented renaming class.
from pathlib import Path
from string import digits
from typing import Iterator, Iterable | {
"domain": "codereview.stackexchange",
"id": 43332,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x, file-system",
"url": null
} |
python, beginner, python-3.x, file-system
class RenamingDir:
SUFFIX_PAT = f'[{digits}]'*3 + '.txt'
def __init__(self, directory: Path, prefix: str) -> None:
self.directory = directory
self.prefix = prefix
def old_numbers(self) -> Iterator[int]:
for file in self.directory.glob(self.prefix + self.SUFFIX_PAT):
number = file.stem.removeprefix(self.prefix)
yield int(number)
def format_names(self, numbers: Iterable[int]) -> Iterator[Path]:
for i in numbers:
yield self.directory / f'{self.prefix}{i:03d}.txt'
def __iter__(self) -> Iterable[tuple[
Path, # original path
Path, # new path
]]:
numbers = sorted(self.old_numbers())
for start, number in enumerate(numbers, start=1):
if start != number:
return zip(
self.format_names(numbers[start-1:]),
self.format_names(range(start, 1 + len(numbers)))
)
return ()
def rename(self) -> None:
for old, new in self:
old.rename(new)
def main() -> None:
while True:
directory = Path(input("Please enter a directory to search for files: "))
if directory.is_dir():
break
prefix = input("Please enter a prefix to search for, such as spam: ")
RenamingDir(directory, prefix).rename()
if __name__ == '__main__':
main() | {
"domain": "codereview.stackexchange",
"id": 43332,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x, file-system",
"url": null
} |
python, object-oriented
Title: Abstract class with different derived signatures in Python
Question: I don't feel too comfortable with the use of object oriented programming and the related advanced topics. That's why I went through this exercise of using Python's abstract class to implement an abstract Ansatz class. (An Ansatz is basically something like a mathematical assumption, i.e. we might assume that our solution looks like a polynomial or like a logistic function).
Since different Ansätze might have different signatures, I wanted to be somewhat generic. Some Ansätze might just get a few scalar parameters, others arrays, yet others a mix of both.
All derived classes need to implement the eval function, which evaluates the Ansatz for a given input.
For all Ansätze, I want to be able to optimally fit the parameters to match some given data. That's why the abstract Ansatz class implements a fit function. I am using scipy here and the curve_fit method to fit the parameters to a function. Since curve_fit expects an array of parameters, I need to transform from my possibly nested and different Ansatz parameter types to a flat array. That's what __flatten_attributes does. The reverse of this function is __set_attributes_from_flat_array.
Since the eval method should not require to retype the parameters, but the curve_fitting requires them to be passed to the function, I created a wrapper for eval called __eval_with_parameters that sets the additional parameters as the class's attributes and then evaluates the Ansatz.
I'm interested in hearing your opinion on whether or not my approach is somewhat sensible. Are there concepts that would have simplified my implementation? Would you have done some typing differently?
Here's Ansatz.py
from abc import ABC, abstractmethod
from typing import Callable, Dict, Tuple, Optional
import matplotlib.pyplot as plt
import numpy as np
import numpy.typing as npt
from scipy.optimize import curve_fit
Array = npt.NDArray[np.float64]
Numeric = npt.ArrayLike | {
"domain": "codereview.stackexchange",
"id": 43333,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, object-oriented",
"url": null
} |
python, object-oriented
Array = npt.NDArray[np.float64]
Numeric = npt.ArrayLike
class Ansatz(ABC):
def __init__(self, **kwargs: Numeric) -> None:
# Store names and number of elements of **kwargs in self._dimensions
self._dimensions: Dict[str, Tuple[int]] = {}
# Set instance attributes
for key, value in kwargs.items():
if np.isscalar(value):
setattr(self, key, value)
self._dimensions[key] = (1,)
else:
value_as_array: npt.NDArray[np.float64] = np.array(value)
setattr(self, key, value_as_array)
self._dimensions[key] = value_as_array.shape
# Vectorized version of the Ansatz
self.__eval_vectorized: Callable[[Array], Array] = np.vectorize(self.eval)
@abstractmethod
def eval(self, x: float) -> float:
"""Evaluate the Ansatz.
Parameters
----------
x : float
Where to evaluate the Ansatz.
Returns
-------
float
The evaluated Ansatz.
"""
pass
def fit(self, x: Array, y: Array, plot: bool = False, *args, **kwargs) -> None:
"""Fit the Ansatz to the data. Overwrite the instance attributes.
Sets the instance attributes to the fitted parameters unless there is
a RuntimeErrror. In that case, revert the instance attributes to the
original values.
Parameters
----------
x : Array
x-values of the data used for fitting.
y : Array
y-values of the data used for fitting.
plot : bool, optional
Whether or not to plot the data and fit, by default False
""" | {
"domain": "codereview.stackexchange",
"id": 43333,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, object-oriented",
"url": null
} |
python, object-oriented
p0 = self.__flatten_attributes()
try:
p_opt, _ = curve_fit(
self.__eval_with_parameters, x, y, p0=p0, *args, **kwargs
)
self.__set_attributes_from_flat_array(p_opt)
if plot:
t = np.linspace(np.min(x), np.max(x), 100)
_, ax = plt.subplots()
ax.plot(x, y, "o", label="data")
ax.plot(t, self.__eval_vectorized(t), "-", label="fit")
ax.set_title(f"{self.__class__.__name__} Ansatz")
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.legend()
plt.show()
except RuntimeError as e:
print(e)
self.__set_attributes_from_flat_array(p0)
def __eval_with_parameters(self, x: Array, *args: float) -> Array:
"""Evaluate the Ansatz with the given parameters.
Changes the instance attributes.
Parameters
----------
x : Array
Where to evaluate the Ansatz.
*args : float
The parameters used to temporarily set the instance attributes to.
Returns
-------
Array
The evaluated Ansatz.
"""
self.__set_attributes_from_flat_array(np.array(args))
return self.__eval_vectorized(x)
def __flatten_attributes(self) -> Array:
"""Return all instance attributes as a flattened array.
Returns
-------
Array
Flat array with all instance attributes.
"""
flat_attributes = np.empty(0)
for key, _ in self._dimensions.items():
attr = getattr(self, key)
if not np.isscalar(attr):
attr = attr.flatten()
flat_attributes = np.append(flat_attributes, attr)
return flat_attributes | {
"domain": "codereview.stackexchange",
"id": 43333,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, object-oriented",
"url": null
} |
python, object-oriented
def __set_attributes_from_flat_array(self, flat_attributes: Array) -> None:
"""Sets the instance attributes from a flattened array.
Parameters
----------
flat_attributes : Numeric
Flat array with attributes to set.
"""
counter = 0
for key, shape in self._dimensions.items():
n_elements = int(np.prod(shape))
attr = flat_attributes[counter : counter + n_elements].reshape(shape)
setattr(self, key, attr)
counter += n_elements
And here are some derived implementations with a few runnable examples (I omitted the comments that describe the different Ansätze).
from typing import Optional
import numpy as np
import numpy.typing as npt
from .Ansatz import Ansatz
Array = npt.NDArray[np.float64]
Numeric = npt.ArrayLike
class Poly(Ansatz):
coefficients: Array
def __init__(
self, order: Optional[int], coefficients: Optional[Numeric] = None
) -> None:
if coefficients is None:
if order is not None:
coefficients = np.zeros(order + 1)
else:
raise ValueError("Either order or coefficients must be given.")
if coefficients is not None and order is not None:
if np.size(coefficients) != order + 1:
raise ValueError(
f"Order of polynomial ({order}) +1 does not match number of coefficients ({np.size(coefficients)})"
)
super().__init__(coefficients=coefficients)
def eval(self, x: float) -> float:
powers_of_x = [x**i for i in range(len(self.coefficients))]
return np.dot(self.coefficients, powers_of_x)
class Exponential(Ansatz):
y0: float
rate: float
def __init__(self, y0: float = 1.0, rate: float = 1.0):
super().__init__(y0=y0, rate=rate)
def eval(self, x: float) -> float:
return self.y0 * np.exp(self.rate * x) | {
"domain": "codereview.stackexchange",
"id": 43333,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, object-oriented",
"url": null
} |
python, object-oriented
def eval(self, x: float) -> float:
return self.y0 * np.exp(self.rate * x)
class Rational(Ansatz):
offset: float
enumerator: Array
denominator: Array
def __init__(
self, offset: float = 0.0, enumerator: Numeric = 1.0, denominator: Numeric = 1.0
):
assert np.size(enumerator) == np.size(denominator)
super().__init__(offset=offset, enumerator=enumerator, denominator=denominator)
def eval(self, x: float) -> float:
powers_of_x = [x**i for i in range(len(self.enumerator))]
return (
np.dot(self.enumerator, powers_of_x) / np.dot(self.denominator, powers_of_x)
) + self.offset
if __name__ == "__main__":
P = Poly(order=2, coefficients=[1, 2, 3])
E = Exponential(y0=1.0, rate=2.0)
R = Rational(offset=1.0, enumerator=[1, 2], denominator=[1, 1])
x = np.linspace(0, 10, 100)
y = np.random.randn(x.shape[0]) + x**2 - x**3 / 10
P.fit(x, y, plot=True)
E.fit(x, y, plot=True)
R.fit(x, y, plot=True)
Thanks in advance for all feedback!
Answer: Pretty good!
Overall you have reasonable types, especially Array (though that should only be declared once). But your use of kwargs and setattr interferes with that type safety. There are type-safe ways around this: one way would be for Rational to be a @dataclass, and for its super to call into fields() or asdict(). Or without dataclasses, maybe __dict__ would work (so long as Rational stores offset, enumerator and denominator as members from its own constructor).
Though it's unlikely for eval to collide with the built-in eval, it's enough to confuse some syntax highlighters etc. Probably best to rename this.
This:
powers_of_x = [x**i for i in range(len(self.enumerator))]
can be vectorised as
powers_of_x = x ** np.arange(len(self.enumerator)) | {
"domain": "codereview.stackexchange",
"id": 43333,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, object-oriented",
"url": null
} |
python, object-oriented
can be vectorised as
powers_of_x = x ** np.arange(len(self.enumerator))
The __main__ guard is not enough to exclude P, etc. from the global namespace. That code should be moved to a main function.
Don't assert in production code; raise an exception instead. | {
"domain": "codereview.stackexchange",
"id": 43333,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, object-oriented",
"url": null
} |
python, python-3.x, chess
Title: Can two knights pieces attack one another from current positions?
Question: I am working on my Python skills and would like some feedback on this problem I have tried to solve. I would like to return a boolean if two knights at their current position can attack each other using standard chess notation example (4,'A')
from itertools import product
class ChessPosition:
def __init__(self, number, letter):
self.x = number
self.y = letter
self.notation_file_value = {
"A": 1,
"B": 2,
"C": 3,
"D": 4,
"E": 5,
"F": 6,
"G": 7,
"H": 8,
}
def get(self):
return self.x, self.notation_file_value.get(self.y)
# get all possible knight moves from current position
def knight_moves(position):
x, y = position
moves = list(product([x - 1, x + 1], [y - 2, y + 2])) + list(
product([x - 2, x + 2], [y - 1, y + 1]))
moves = [(x, y) for x, y in moves if x >= 1 and y >= 1 and x < 8 and y < 8]
return moves
# validate if knights can attack each other from current position
# if chess_position_1 can attack chess_position_2
# then chess_position_2 can attack chess_position_1
def can_attack(chess_position_1, chess_position_2):
k_1 = chess_position_1.get()
k_2 = chess_position_2.get()
for move in knight_moves(k_1):
if move == k_2:
return True
return False
# True
print(can_attack(ChessPosition(2, "C"), ChessPosition(4, "D")))
# False
print(can_attack(ChessPosition(6, "A"), ChessPosition(5, "B"))) | {
"domain": "codereview.stackexchange",
"id": 43334,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, chess",
"url": null
} |
python, python-3.x, chess
# False
print(can_attack(ChessPosition(6, "A"), ChessPosition(5, "B")))
Answer: It's kind of a stretch to apply OOP here, but fine. Keeping it, you should type-hint your number and letter arguments. Consider re-phrasing your notation_file_value as a subtraction of two character ordinals.
Your algorithm can be greatly simplified. Don't generate all moves - instead, just subtract the destination and source being checked, and if they're either (2, 1) or (1, 2) in an absolute sense, that's a valid knight move. Also, it's better named a move than an attack, since this logic will apply to non-attack moves.
Convert your prints to simple unit tests.
Suggested
class ChessPosition:
def __init__(self, x: int, y: int) -> None:
self.x, self.y = x, y
@classmethod
def from_grid(cls, row: int, column: str) -> 'ChessPosition':
return cls(row - 1, ord(column) - ord('A'))
def __sub__(self, other: 'ChessPosition') -> tuple[int, int]:
return self.x - other.x, self.y - other.y
def knight_can_reach(source: ChessPosition, dest: ChessPosition) -> bool:
dx, dy = dest - source
return sorted((abs(dx), abs(dy))) == [1, 2]
def test() -> None:
assert knight_can_reach(ChessPosition.from_grid(2, 'C'), ChessPosition.from_grid(4, 'D'))
assert not knight_can_reach(ChessPosition.from_grid(6, 'A'), ChessPosition.from_grid(5, 'B'))
if __name__ == '__main__':
test() | {
"domain": "codereview.stackexchange",
"id": 43334,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, chess",
"url": null
} |
c++, design-patterns, observer-pattern
Title: Observer Design Pattern in C++ to model magazine subscriptions
Question: My attempt at a observer design pattern (I know using namespace std isn't good). I'm very new to design patterns. Everything is inline with class definition. Please tell me if I'm doing anything wrong or if there is anything that can be improved. Does subscriber (observer) need to store info from update function? Also, is operator== ok for comparing and finding correct subscriber with name or should I use getname()?
Base:
class Subscriber
{
string name;
public:
Subscriber(string name) : name(name) {}
virtual void update(string title, double price) = 0;
string getname() const {return name;}
bool operator==(string name) {
if (this->name == name)
return true;
return false;
}
virtual ~Subscriber() {};
};
Derived:
class PaidSubscriber : public Subscriber
{
public:
PaidSubscriber(string name) : Subscriber(name) {}
void update(string title, double price) {
cout << "\nPaid Subscriber: " << getname() << endl;
cout << "New Issue: " << title << endl;
if (price > 0)
cout << "Price: $" << std::fixed << setprecision(2) << price << endl;
else
cout << "Price: FREE";
};
};
class VIPSubscriber : public Subscriber
{
public:
VIPSubscriber(string name) : Subscriber(name) {}
void update(string title, double price) {
cout << "\nVIP Subscriber: " << getname() << endl;
cout << "New Issue: " << title << endl;
if (price-10 > 0)
cout << "Price: $" << std::fixed << setprecision(2) << price-10 << endl;
else
cout << "Price: FREE";
};
}; | {
"domain": "codereview.stackexchange",
"id": 43335,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, design-patterns, observer-pattern",
"url": null
} |
c++, design-patterns, observer-pattern
class FreeSubscriber : public Subscriber
{
public:
FreeSubscriber(string name) : Subscriber(name) {}
void update(string title, double price) {
cout << "\nFree Subscriber: " << getname() << endl;
cout << "New Issue: " << title;
if (price > 0) {
cout << " (preview only)" << endl;
cout << "Upgrade to Paid Subscriber!" << endl;
}
else
cout << endl;
};
};
Subject:
class Magazine
{
string currissue;
double currprice;
list<Subscriber*>sublist;
public:
enum SubscriberType {SUB_FREE, SUB_PAID, SUB_VIP};
Magazine(string currissue, double currprice) : currissue(currissue), currprice(currprice) {}
void subscribe(string name, SubscriberType subtype) {
Subscriber *sub;
switch(subtype) {
case SUB_FREE:
sub = new FreeSubscriber(name);
break;
case SUB_PAID:
sub = new PaidSubscriber(name);
break;
case SUB_VIP:
sub = new VIPSubscriber(name);
break;
default:
return;
}
sublist.push_back(sub);
}
void unsubscribe(string name)
{
for (auto it = sublist.begin(); it != sublist.end(); it++) {
if (**it == name) {
sublist.erase(it);
break;
}
}
}
void changeissue(string name, double price) {
this->currissue = name;
this->currprice = price;
}
void notify()
{
for (auto sub : sublist)
sub->update(currissue, currprice);
}
~Magazine() {
for (auto sub : sublist)
delete sub;
}
}; | {
"domain": "codereview.stackexchange",
"id": 43335,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, design-patterns, observer-pattern",
"url": null
} |
c++, design-patterns, observer-pattern
Main:
int main()
{
Magazine nationalgeographic("Lions", 5.34);
nationalgeographic.subscribe("Ivy Parks", Magazine::SUB_PAID);
nationalgeographic.subscribe("Mike Gopher", Magazine::SUB_FREE);
nationalgeographic.subscribe("Stan Shunpike", Magazine::SUB_VIP);
nationalgeographic.notify();
nationalgeographic.changeissue("Elephants", 15.23);
nationalgeographic.notify();
}
Answer: Answers to your questions
I know using namespace std isn't good [...] Please tell me if I'm doing anything wrong or if there is anything that can be improved.
Well you already said it yourself: don't use using namespace std, especially not for anything you would put into a header file.
Does subscriber (observer) need to store info from update function?
That depends on what the observer needs to do. If you just want to print some information like in your example, there is no need to store anything.
Also, is operator== ok for comparing and finding correct subscriber with name or should I use getname()?
I recommend using getname(). Use operator== primarily to compare two objects of the same type to each other. So I would rewrite it to:
bool operator==(const Subscriber& other) const {
return this->name == other.name;
}
However, there is not much use for this in your code, so you could also consider removing it.
Return booleans directly
Instead of writing:
if (foo)
return true;
else
return false;
You can write this instead:
return foo; | {
"domain": "codereview.stackexchange",
"id": 43335,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, design-patterns, observer-pattern",
"url": null
} |
c++, design-patterns, observer-pattern
You can write this instead:
return foo;
Use '\n' instead of std::endl
Prefer using '\n' instead of std::endl; the latter is equivalent to the former, but also forces the output to be flushed, which is usually not necessary and impacts performance.
Pass strings by const reference where appropriate
A std::string can be a large object that allocates memory on the heap. By passing them by value to other functions, a copy has to be made. If you only need to read from the string, that copy is unnecessary and just reduces performance. To avoid this, pass them by const reference instead. For example:
class Subscriber
{
std::string name;
public:
Subscriber(const std::string& name) : name(name) {}
...
};
If you can use C++17, then even better would be to use std::string_view to pass strings.
Avoid manual new and delete
Manually calling new and delete makes it easy for errors to slip into your code. For example, if you unsubscribe a Subscriber, you only erase its pointer in sublist, you forgot to actually delete the Subscriber object. So avoid manual new and delete whenever you can. In the case of the list of subscribers, you could make it a list of std::unique_ptrs:
std::list<std::unique_ptr<Subscriber>> sublist;
Your subscribe() function could be changed to:
void subscribe(const std::string& name, SubscriberType subtype) {
std::unique_ptr<Subscriber> sub;
switch (subtype) {
case SUB_FREE:
sub = std::make_unique<FreeSubscriber>(name);
break;
...
}
sublist.push_back(std::move(sub));
}
Although there are nicer solutions which I will show below.
In notify(), you need to ensure you use a reference:
for (auto& sub: sublist)
sub->update(currissue, currprice); | {
"domain": "codereview.stackexchange",
"id": 43335,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, design-patterns, observer-pattern",
"url": null
} |
c++, design-patterns, observer-pattern
And ~Magazine() can now be removed completely; when sublist is destroyed, it will in turn destroy all std::unique_ptrs, which in turn will delete the objects they hold.
Simplifying subscribe()
The problem with subscribe() is that it not only has to add a subscriber to the list, it also needs to create a new subscriber object based on subtype. If you add lots of different subscriber types, that means this function will grow a lot as well. It would be nice to keep this function small and only have to deal with adding a subscriber to the list. Ideally, it looks like:
void subscribe(std::unique_ptr<Subscriber>&& sub) {
sublist.push_back(std::move(sub));
}
Then in main() you would have to write:
nationalgeographic.subscribe(std::make_unique<PaidSubscriber>("Ivy Parks"));
In a way, that just moves the problem to the caller. A possible way to make the caller simpler as well is to still have subscribe() create the Subscriber objects, but then to make it a template to avoid code repetition:
template<class SubscriberType>
void subscribe(const std::string& name) {
sublist.push_back(std::make_unique<SubscriberType>(name));
};
Then the caller looks like:
nationalgeographic.subscribe<PaidSubscriber>("Ivy Parks");
Merge changeissue() and notify()
Whenever a new issue is released by the magazine, you always want to notify the subscribers. So it doesn't make sense to have two separate functions that you need to call. I would create one function instead:
void release_issue(const std::string& issue, double price) {
for (auto& sub: sublist)
sub->update(issue, price);
}
With this, you also no longer need the member variables currissue and currprice, and the constructor can be removed. You would use it like so:
Magazine nationalgeographic;
nationalgeographic.subscribe<PaidSubscriber>("Ivy Parks");
...
nationalgeograpic.release_issue("Lions", 5.34);
nationalgeograpic.release_issue("Elephants", 15.23); | {
"domain": "codereview.stackexchange",
"id": 43335,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, design-patterns, observer-pattern",
"url": null
} |
python, python-3.x, exception, wordle
Title: Wordle guesser, breaking out of loop by raising exception
Question: After many years away from writing in Python, I am getting back into it. Specifically, I am trying to teach myself dataclasses. As an exercise I wrote a Wordle-solving program. I downloaded the list of possible Wordle solutions and began writing.
There are two functions. The first simply asks for a five-letter string from the user that indicates what the result of our last guess was. "b" for a bad letter, "y" for a yellow letter, "g" for a green letter. It then updates our list of "bad" and "yellow" letters accordingly. If we get a 'ggggg' result indicating we've guessed the word successfully, we simply stop.
The second function loops through the list of Wordle solutions and tests them against the results we've gathered so far and produces a new guess.
I struggled a long time with this second function. Does the current word contain all "yellow" letters but not in all the positions those individual letters have been tried? Does the current word have all the right "green" letters? Is it absent of all letters that have already been deemed "bad"?
I eventually came up with the idea of raising an exception every time our guess fails a test. If we get through the loop and no exceptions have been raised, we have a new guess.
I'm not entirely happy with this and would welcome suggestions on how to make a better testing loop. Also, any other comments you have on my code, constructive or otherwise, I'd love to hear.
#!/usr/bin/python3
"""Generages guesses for the daily Wordle puzzle."""
import sys
from dataclasses import dataclass
from re import match | {
"domain": "codereview.stackexchange",
"id": 43336,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, exception, wordle",
"url": null
} |
python, python-3.x, exception, wordle
def get_result(last_results):
"""Find out from the user what the result of our last guess was."""
# Keep asking for a result until we get a response that is five characters long
# and consists of only the letters b, g, and y
last_results.result = input("Result: ")
while not (
match("^[ygb]+$", last_results.result) and len(last_results.result) == 5
):
last_results.result = input("Result: ")
# Five g's means we've solved it
if last_results.result == "ggggg":
sys.exit()
# Iterate over the result. Every letter that got a "b" is added to the bad
# letters string. A letter that got a "y" gets added to the yellow letters
# dict, along with what position it was tried in.
for position in range(5):
if last_results.result[position] == "b":
last_results.bad += last_results.guess[position]
elif last_results.result[position] == "y":
last_results.yellow.setdefault(last_results.guess[position], []).append(
position
)
return last_results | {
"domain": "codereview.stackexchange",
"id": 43336,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, exception, wordle",
"url": null
} |
python, python-3.x, exception, wordle
def new_guess(last_guess):
"""Generate a new guess based on the results of our previous guesses."""
# Create a class that allows us to cleanly break out of the loop if
# we discover this word doesn't meet the criteria we're looking for.
class NextWord(Exception):
"""Do-nothing class that simply catches an exception"""
try_next_word = NextWord()
while True:
word = words.pop(0)
try:
for position in range(5):
# Is this letter in our bad letters list?
bad = word[position] in last_guess.bad
# Is this letter in our list of yellow letters?
yellow = word[position] in last_guess.yellow.keys()
# Have we already tried this yellow letter in this position?
tried_here = yellow and position in last_guess.yellow.get(
word[position]
)
# Was the last result for this position "g"?
green = last_guess.result[position] == "g"
# Does the letter in this position match what was in this position
# in our last guess?
matching = word[position] == last_guess.guess[position]
if bad and not green and not yellow:
raise try_next_word
if green and not matching:
raise try_next_word
if yellow and tried_here:
raise try_next_word
# Make certain all our yellow letters are in this word
for yellow_letter in last_guess.yellow.keys():
if yellow_letter not in word:
raise try_next_word
# If this word hasn't failed any of the above tests, we have a new guess
last_guess.guess = word
break
# If the "try_next_word" exception was raised during the above tests,
# continue on to the next word
except NextWord: | {
"domain": "codereview.stackexchange",
"id": 43336,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, exception, wordle",
"url": null
} |
python, python-3.x, exception, wordle
# continue on to the next word
except NextWord:
continue
return last_guess | {
"domain": "codereview.stackexchange",
"id": 43336,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, exception, wordle",
"url": null
} |
python, python-3.x, exception, wordle
with open("/home/localr/coding/5lw.txt", encoding="utf-8") as word_source:
word_list = word_source.read()
words = word_list.split()
@dataclass
class ResultsOfGuesses:
"""Class for keeping track of our current guess, the last result
of our guess, and which letters we've used in our guesses."""
guess: str
result: str
bad: str
yellow: dict
# First guess is always 'dealt'
results = ResultsOfGuesses("dealt", "", "", {})
# Get the result from testing our guess and generate a new guess
while True:
print(results.guess)
results = get_result(results)
results = new_guess(results)
Answer: Program structure
The flow of control leaves a lot to be desired.
Exceptions should be used for exceptional situations, not as a kind of break or goto. Raising an exception incurs a rather large overhead, since the interpreter has to encode the stack trace information with the exception. (Ruby, unlike Python, does have a throw-catch feature for jumping around your code in addition to raise-rescue for exceptions, but even in Ruby, using throw-catch is bad style.)
An even more egregious problem with your flow control is the use of sys.exit(). The use of sys.exit() is rarely justifiable. It makes the code harder to understand, and it also prevents the function that contains the sys.exit() call from being reused.
Reading lines from a file
Python has built-in support for reading line-oriented data:
For reading lines from a file, you can loop over the file object. This is memory efficient, fast, and leads to simple code
… so this would be preferable to word_list.split():
with open("5lw.txt", encoding="utf-8") as word_source:
words = [line.rstrip() for line in word_source]
Hard-coding the word length
You hard-code 5 in several places. The word length should only be mentioned in one place.
By the way,
match("^[ygb]+$", last_results.result) and len(last_results.result) == 5 | {
"domain": "codereview.stackexchange",
"id": 43336,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, exception, wordle",
"url": null
} |
python, python-3.x, exception, wordle
match("^[ygb]+$", last_results.result) and len(last_results.result) == 5
… could be better written as
fullmatch("[ygb]{5}", last_results.result)
List manipulation
list.pop(0) should be avoided: removing the first item in a list requires all subsequent elements to be moved into the hole. Popping the last item from the list is much more efficient.
Handling repeated letters
The way repeated letters are indicated is a subtle point which is not very well explained in the official Wordle rules. (I actually messed this up in my initial post, worse than you did, since you at least tried to handle it with if bad and not green and not yellow:.)
This page explains Wordle's behaviour better:
If you repeat a letter more than it appears, then the excess will be highlighted in grey.
For example, suppose that the secret word is "eerie". If we run your program, it will go like this:
dealt
Result: bgbbb
feens
Result: bgybb
beigy
⋮
However, "beigy" is a bad guess, since the feedback for "\$\color{gray}{\textrm{f}}\color{green}{\textrm{e}}\color{orange}{\textrm{e}}\color{gray}{\textrm{n}}\color{gray}{\textrm{s}}\$" tells you that there are at least two occurrences of "e" in the word (one of which is in the second position, one of which is not in the third position). An example of an appropriate guess would be "verve".
Suggested solution
What exactly does a "bad", "yellow", or "good" clue mean? Instead of a ResultsOfGuesses dataclass that contains various bits of information, why not use a dataclass for each type of clue, such that the clue object knows how to accept or reject a word?
from dataclasses import dataclass
import re
@dataclass
class GreenFilter:
letter: str
pos: int
def __call__(self, word):
return word[self.pos] == self.letter
@dataclass
class YellowFilter:
letter: str
pos: int
min_count: int
def __call__(self, word):
return word[self.pos] != self.letter and sum(1 for c in word if c == self.letter) >= self.min_count | {
"domain": "codereview.stackexchange",
"id": 43336,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, exception, wordle",
"url": null
} |
python, python-3.x, exception, wordle
@dataclass
class BadFilter:
letter: str
max_count: int
def __call__(self, word):
return sum(1 for c in word if c == self.letter) <= self.max_count
def main():
with open('words', encoding="utf-8") as word_source:
words = [line.rstrip() for line in word_source]
# Tweak the preferred order of guesses
words.reverse()
words.remove('dealt')
words.append('dealt')
while words:
guess = words.pop()
print(guess)
while True:
feedback = input("Result: ")
if re.fullmatch("[gyb]{5}", feedback):
break
filters = [
GreenFilter(guess[pos], pos)
for pos, clue in enumerate(feedback)
if clue == "g"
]
# "Yellow" clues indicate guessed letters, in excess of any green
# clues for that letter, which are in the wrong position.
for pos, clue in enumerate(feedback):
if clue == "y":
filters.append(
YellowFilter(guess[pos], pos, 1 + sum(guess[pos] == f.letter for f in filters))
)
# "Bad" clues indicate guessed letters which occur too many
# times.
filters += [
BadFilter(guess[pos], sum(guess[pos] == f.letter for f in filters))
for pos, clue in enumerate(feedback)
if clue == "b"
]
if all(isinstance(f, GreenFilter) for f in filters):
break
words = [w for w in words if all(f(w) for f in filters)]
else:
print("Error: no known solution!")
if __name__ == '__main__':
main() | {
"domain": "codereview.stackexchange",
"id": 43336,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, exception, wordle",
"url": null
} |
python, matrix
Title: Validator for 0/1 entries in a matrix
Question: I build a function(A kind of puzzle) that counts from a matrix the number of valid count (Explanation below).
The matrix is made up of 0,1.
Input-
a matrix- list of lists
row number
column number
Output-
valid count.
Valid Count - This is the number of cells that are in the same row and column that we got in the Input. where there is the digit 1 so the digit zero is not between them (between matrix[row][col] to those other cells).
for example-
matrix = [[1,0,1,1],[0,1,1,1],[1,0,1,0]]
valid_count(matrix, 0, 0) → 1
valid_count(matrix, 1, 0) → 0
valid_count(matrix, 1, 2) → 5
valid_count(matrix, 1, 1) → 3
I wrote a function that works properly, the problem is that it is a bit long and not elegant in my opinion.
I would love advice for improving runtime, shortening the code and writing it in a more elegant way.
my code:
def valid_count(matrix, row, col):
if matrix[row][col] == 0:
return 0
else:
return 1 + valid_count_row_helper(matrix, row, col) + valid_count_col_helper(matrix, row, col)
def valid_count_row_helper(matrix, row, col):
# This function checks if there are valid cells along the requested row (we received in the input)
count = 0
for i in range(row + 1, len(matrix)): # checking from matrix[row][col] to matrix[len(matrix)][col] -going up
if matrix[i][col] != 0:
count += 1
else:
break
for j in range(1,row+1):
if matrix[row - j][col] != 0: # checking from matrix[row][col] to matrix[0][col] -going down
count += 1
else:
break
return count | {
"domain": "codereview.stackexchange",
"id": 43337,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, matrix",
"url": null
} |
python, matrix
def valid_count_col_helper(matrix, row, col):
# This function checks if there are valid cells along the requested column (we received in the input)
count = 0
for i in range(col + 1, len(matrix[0])): # checking from matrix[row][col] to matrix[row][len(matrix[0])] -going up
if matrix[row][i] != 0:
count += 1
else:
break
for j in range(1,col+1):
if matrix[row][col - j] != 0: # checking from matrix[row][col] to matrix[row][0] -going down
count += 1
else:
break
return count
Answer: You already know the primary problem with your code: repetition.
You have written reasonable code that is not difficult to understand.
The problem is that you have four nearly identical chunks of code.
Below is a listing of the key differences. If one focuses narrowly
on the existing syntax, it's not easy to envision a way to write
more general code that would handle the four situations.
for i in range(row + 1, len(matrix)):
if matrix[i][col] != 0:
for j in range(1,row+1):
if matrix[row - j][col] != 0:
for i in range(col + 1, len(matrix[0])):
if matrix[row][i] != 0:
for j in range(1,col+1):
if matrix[row][col - j] != 0:
Step back and try to describe the needed behavior more abstractly. When
faced with a situation like that, it often helps to step away from the details
of syntax and instead try to understand the essence of the problem. We have a
starting location: (row, col). From that location, we want to find the
contiguous sequences of ones by looking in each direction: right, left, down,
up.
Representing directions: use a data structure. In grid problems like this,
direction of travel can often be represented by row and column location-change.
DIRECTIONS = (
(0, 1), # Right
(0, -1), # Left
(1, 0), # Down
(-1, 0), # Up
) | {
"domain": "codereview.stackexchange",
"id": 43337,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, matrix",
"url": null
} |
python, matrix
Exploring in all directions to compute the total. We just need to sum up
the counts obtained from each direction and then make an adjustment to counteract
the quadruple-counting of the starting location.
def valid_count(matrix, row, col):
tot = sum(
count_ones(matrix, row, col, dr, dc)
for dr, dc in DIRECTIONS
)
return max(0, tot - 3)
Counting ones. Once we have the idea to represent direction via row/col
change values, implementing the code to do the counting is fairly
straightforward: it's just a while loop that stops on the first non-one, which
can occur when we hit a zero or when we run off the edge of the matrix. Because
it's tedious to write code for the matrix boundary checks, it often helps in
problems like this to write a small utility (similar in spirit to dict.get)
to retrieve matrix values without having to worry about IndexError. That
utility can also handle our other need: we do not want to support negative
indexes.
def count_ones(matrix, row, col, dr, dc):
n = 0
while get(matrix, row, col):
n += 1
row += dr
col += dc
return n
def get(matrix, row, col):
try:
return 0 if min(row, col) < 0 else matrix[row][col]
except IndexError:
return 0 | {
"domain": "codereview.stackexchange",
"id": 43337,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, matrix",
"url": null
} |
java, design-patterns, factory-method
Title: Abstract Factory Pattern Implementation
Question: I implemented the Abstract Factory design pattern as follows.
Concrete Implementation
interface VideoExporter {
void exportVideo();
}
interface AudioExporter {
void exportAudio();
}
class HQVideoExporter implements VideoExporter {
@Override
public void exportVideo() {
System.out.println("Exporting HQ video");
}
}
class HQAudioExporter implements AudioExporter {
@Override
public void exportAudio() {
System.out.println("Exporting HQ Audio");
}
}
class LQVideoExporter implements VideoExporter {
@Override
public void exportVideo() {
System.out.println("Exporting LQ video");
}
}
class LQAudioExporter implements AudioExporter {
@Override
public void exportAudio() {
System.out.println("Exporting LQ Audio");
}
}
enum QUALITY_TYPE {
LOW, HIGH
}
Factory Class
class ExporterFactory {
static VideoExporter createVideoExporter(QUALITY_TYPE quality_type) {
return switch (quality_type) {
case LOW -> new LQVideoExporter();
case HIGH -> new HQVideoExporter();
};
}
static AudioExporter createAudioExporter(QUALITY_TYPE quality_type) {
return switch (quality_type) {
case LOW -> new LQAudioExporter();
case HIGH -> new HQAudioExporter();
};
}
}
Client code
VideoExporter videoExporter = ExporterFactory.createVideoExporter(QUALITY_TYPE.HIGH);
AudioExporter audioExporter = ExporterFactory.createAudioExporter(QUALITY_TYPE.LOW);
videoExporter.exportVideo();
audioExporter.exportAudio(); | {
"domain": "codereview.stackexchange",
"id": 43338,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, design-patterns, factory-method",
"url": null
} |
java, design-patterns, factory-method
In the above implementation, createVideoExporter and createAudioExporter are exposed to the client code. I think this is not an abstract factory design pattern, it is just a factory design pattern. To make it an Abstract factory pattern do I need to create another interface with the concrete implementations returning similar kinds of codecs like only HQAudioExporter and HQVideoExporter can be created from one implementation, and LQVideoExporter and LQAudioExporter from another implementation, Am I correct?
Answer: This code looks fine, it is indeed an implementation of a factory pattern.
However, why would both Audio and Video be in the same factory? Apart from having the same responsibility to export something, they probably won't have much in common.
You already have two interfaces, you should also have two factories. | {
"domain": "codereview.stackexchange",
"id": 43338,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, design-patterns, factory-method",
"url": null
} |
javascript, html, css
Title: Add and delete books into this bookshelf vanilla javascript project
Question: In this project I was supposed to add and delete books by author and title by pressing the submit and delete button.
There is a video that illustrates how my project works.
I did it using two functions which saves the added books into an array of objects. I'm just starting to learn how to code so I'm looking for some other approaches to improve my way of thinking.
With nothing else to say other than thanks, this is the code I used:
const form = document.querySelector(".form");
const library = document.querySelector(".library");
const inputAuthor = document.querySelector(".input-author");
const inputBook = document.querySelector(".input-book");
const errormessage = document.querySelector(".errormessage");
let storedBooks = JSON.parse(localStorage.getItem("books"));
let bookShelf = [];
let filter = [];
let counter ="0"
function libraryBooks(object) {
return `<div class="${object.author}">
<h1>${object.book}</h1>
<p>${object.author}</p>
<hr>
<button class="remove">
remove
</button>
</div>`
}
function remove() {
if(bookShelf.length>0){
const removebtn = document.querySelectorAll(".remove");
removebtn.forEach(element => element.addEventListener("click", ()=> {
let parentNodeClass = element.parentNode.className;
element.parentNode.remove()
console.log(parentNodeClass)
bookShelf = bookShelf.filter(x => x.author !== parentNodeClass)
localStorage.setItem('books', JSON.stringify(bookShelf))
console.log("book", bookShelf)
console.log("store", storedBooks)
}))
}
} | {
"domain": "codereview.stackexchange",
"id": 43339,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, html, css",
"url": null
} |
javascript, html, css
function add() {
if(inputAuthor.value != "" && inputBook.value != ""){
currentBook = []
currentBook.push (
{
author: inputAuthor.value,
book: inputBook.value
}
)
filter = bookShelf.filter(x => x.book === currentBook[0].book)
if(filter.length > 0){
errormessage.style.display ="unset"
inputAuthor.value = ""
inputBook.value = ""
setTimeout(()=>errormessage.style.display = "none",3000)
return
}
bookShelf.push (
{
author: inputAuthor.value,
book: inputBook.value
}
)
if(bookShelf.length>0) {
currentBook.forEach(book => library.insertAdjacentHTML('beforeend', libraryBooks(book)))
}
}
inputAuthor.value = ""
inputBook.value = ""
localStorage.setItem('books', JSON.stringify(bookShelf))
}
form.addEventListener("submit", function(event) {
event.preventDefault();
add()
remove()
}
)
if(storedBooks !== null){
console.log("entré")
bookShelf = storedBooks
bookShelf.forEach(book => {
library.insertAdjacentHTML('beforeend', libraryBooks(book))
remove()
})
}
.form {
display: flex;
flex-direction: column;
gap: 24px;
max-width: 300px;
}
.errormessage {
display: none;
color: red;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./style.css">
<title>Document</title>
</head>
<body>
<h1>Aweasome Books</h1>
<section class="library">
</section>
<form class = "form">
<input class="input-author" type="text" placeholder="Author">
<input class="input-book" type="text" placeholder="book">
<button type="submit">
Add
</button>
</form>
<div class="errormessage">Book was added previously on your bookshelf </div>
<script src="./app.js"></script>
</body>
</html> | {
"domain": "codereview.stackexchange",
"id": 43339,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, html, css",
"url": null
} |
javascript, html, css
Answer: Just to start, the code snippet is not working so I can't really tell what your piece of software looks like upfront. But based on the code you shared, there are some things that I think can be improved. First is the way you structure your logic. You should avoid nested conditions (if else) if possible since it dilutes the way your code appears to others. One way you can avoid this is to use guards and early returns. You ought to use your if else statements appropriately by first identifying the worst-case scenarios and creating a condition (guard) to handle them. The way you do it is by putting them on top of all the remaining logic. That way, you can easily tell what that method is trying to do by removing the confusing part. | {
"domain": "codereview.stackexchange",
"id": 43339,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, html, css",
"url": null
} |
c++, c++20
Title: Using std::variant with std::ranges algorithms
Question: I have some predicate objects that take some value and return the result of some criteria. (My real implementation is more complex, this is only a minimal example):
Run on Compiler Explorer
struct PredEven
{
bool passes(int x) const { return x%2 == 0; }
};
struct PredGreaterThan
{
int limit;
bool passes(int x) const { return x > limit; }
};
using Predicate = std::variant<PredEven, PredGreaterThan>;
I store objects of these types in a std::array and now want to test some value against all of these.
The straight-forward implementation would be this:
const std::array<Predicate, 2> predicates = {PredEven{}, PredGreaterThan{3}};
const int valToTest = 4;
bool allPassed1 = true;
for(const auto& var : predicates)
{
allPassed1 &= std::visit([&valToTest](const auto& p){ return p.passes(valToTest); }, var);
}
However, I really should be using std::all_of for this. Better yet, the ranges version:
const bool allPassed2 = std::ranges::all_of(predicates, [&valToTest](const auto& var)
{ return std::visit([&valToTest](const auto& p){ return p.passes(valToTest); }, var); });
This code is concise but rather hard to read (and to format). Particularly the nested lambda isn't great. It does have the advantage that the result can be const.
Is there any way to get rid of the nested lambda or make this more readable?
Answer: The easiest thing to do is to hide away the complexity in a function or class. One possibility is to create a function that returns the nested lambda, like so:
static auto passes(auto valToTest) {
return [valToTest](const auto& var) {
return std::visit([&valToTest](const auto& p) {
return p.passes(valToTest);
}, var);
};
}
const bool allPassed3 = std::ranges::all_of(predicates, passes(valToTest)); | {
"domain": "codereview.stackexchange",
"id": 43340,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20",
"url": null
} |
c++, c++20
const bool allPassed3 = std::ranges::all_of(predicates, passes(valToTest));
There are other ways to reduce the amount of lambdas perhaps, like using std::bind and/or creating a class that has an operator(), but in the end that will probably be equally or even more hard to read as lambdas are basically shorthand for that. | {
"domain": "codereview.stackexchange",
"id": 43340,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20",
"url": null
} |
c#, async-await
Title: Async/await in Parallel.ForEach
Question: I have a Timer:
var QueryReportTimer = new Timer(QueryReportTimerCallback, null, TimeSpan.Zero, TimeSpan.FromSeconds(15));
The important part here is the method QueryReportTimerCallback.
I have a few doubts here:
Is it ok to have an async void method? In general it is not, but how can I avoid this when the timer callback is delegate public delegate void TimerCallback(object state);?
Is it ok to have await inside Parallel.ForEach?
Method QueryReportTimerCallback:
private async void QueryReportTimerCallback(object state)
{
if (await semaphoreQueryReportSlim.WaitAsync(10))
{
try
{
if (machineConfigurations != null)
{
await Task.Factory.StartNew(() =>
Parallel.ForEach(machineConfigurations.Where(x => x.QueryReport), async (configuration) =>
{
if (configuration.IsConnectionValid)
{
var queryReport = new QueryReport(configuration, ReportConfigurations, fileContainer, applicationConfiguration, logger);
await QueryAReport(configuration, queryReport);
}
})
);
}
}
catch (Exception e)
{
logger.LogError(e, e.Message);
}
finally
{
semaphoreQueryReportSlim.Release();
}
}
}
Answer:
Is it ok to have an async void method?
Referencing Async/Await - Best Practices in Asynchronous Programming
As already stated in the OP async void should be avoided as much as possible.
The one exception to that rule being for event handlers, which can be the loophole to achieving the desired behavior while still having the ability to catch and handle any thrown exceptions.
Create an event
event EventHandler QueryReportCallbackEvent = delegate { }; | {
"domain": "codereview.stackexchange",
"id": 43341,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, async-await",
"url": null
} |
c#, async-await
to be raised by the timer callback
private void QueryReportTimerCallback(object state) {
QueryReportCallbackEvent(this, EventArgs.Empty);
}
The event handler allows async void, so now you can safely do
private async void QueryReportCallbackEventHandler(object sender, EventArgs e) {
if (await semaphoreQueryReportSlim.WaitAsync(10))
await queryReportsCore();
}
Is it ok to have await inside Parallel.ForEach?
NO!!!!
The async lambda
async (configuration) => ...
will be converted to async void which takes us right back to what was said in the beginning. async void BAD!!!
Instead refactor that lambda out into its own method that returns a Task
private async Task HandleReport(MachineConfiguration configuration) {
if (configuration.IsConnectionValid) {
var queryReport = new QueryReport(configuration, ReportConfigurations, fileContainer, applicationConfiguration, logger);
await QueryAReport(configuration, queryReport);
}
}
and this will now allow for the use of Task.WhenAll with all the machine configurations retrieved from the query.
var tasks = machineConfigurations
.Where(x => x.QueryReport)
.Select(configuration => HandleReport(configuration));
await Task.WhenAll(tasks);
This actually removes the need for the Paralell.ForEach.
Here is the complete code for what was described above.
//CTOR
public MyClass() {
QueryReportCallbackEvent += QueryReportCallbackEventHandler;
var QueryReportTimer = new Timer(QueryReportTimerCallback, null, TimeSpan.Zero, TimeSpan.FromSeconds(15));
}
event EventHandler QueryReportCallbackEvent = delegate { };
private void QueryReportTimerCallback(object state) {
QueryReportCallbackEvent(this, EventArgs.Empty);
}
private async void QueryReportCallbackEventHandler(object sender, EventArgs e) {
if (await semaphoreQueryReportSlim.WaitAsync(10))
await queryReportsCore();
} | {
"domain": "codereview.stackexchange",
"id": 43341,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, async-await",
"url": null
} |
c#, async-await
private async Task queryReportsCore() {
try {
if (machineConfigurations != null) {
var tasks = machineConfigurations
.Where(x => x.QueryReport)
.Select(configuration => HandleReport(configuration));
await Task.WhenAll(tasks);
}
} catch (Exception e) {
logger.LogError(e, e.Message);
} finally {
semaphoreQueryReportSlim.Release();
}
}
private async Task HandleReport(MachineConfiguration configuration) {
if (configuration.IsConnectionValid) {
var queryReport = new QueryReport(configuration, ReportConfigurations, fileContainer, applicationConfiguration, logger);
await QueryAReport(configuration, queryReport);
}
}
Lastly take note of how the functions were broken down into smaller chunks that allowed for cleaner, more easy to read code. | {
"domain": "codereview.stackexchange",
"id": 43341,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, async-await",
"url": null
} |
python, strings, parsing, regex
Title: Text splitter using Regular Expressions in Python
Question: I have been provided a text splitter class that will take a text input and use re.sub to make replacements when matches are found and also splits sentences up and stores them in a list.
I had an idea to improve the code by storing the expressions in a list and iterating over the list and for each expression looking for a match in the given text. However different replacements are made depending on the expression so not sure how that would work.
What improvements could be made to the code to simplify it? Also am I missing any limitations to the code I could improve?
import re
alphabets = "([A-Za-z])"
prefixes = "(Mr|St|Mrs|Ms|Dr)[.]"
suffixes = "(Inc|Ltd|Jr|Sr|Co)"
starters = "(Mr|Mrs|Ms|Dr|He\s|She\s|It\s|They\s|Their\s|Our\s|We\s|But\s|However\s|That\s|This\s|Wherever)"
acronyms = "([A-Z][.][A-Z][.](?:[A-Z][.])?)"
websites = "[.](com|net|org|io|gov|uk)"
digits = "([0-9])"
urls = "((http|https)\:\/\/)[a-zA-Z0-9\.\/\?\:@\-_=#]+\.([a-zA-Z]){2,6}([a-zA-Z0-9\.\&\/\?\:@\-_=#])*"
class TextSplitter: | {
"domain": "codereview.stackexchange",
"id": 43342,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, strings, parsing, regex",
"url": null
} |
python, strings, parsing, regex
class TextSplitter:
@classmethod
def split_into_sentences(self, text):
text = " " + text + " "
text = text.replace("\n"," ")
for match in re.compile(urls).finditer(text):
text = text.replace(match.group(0), match.group(0).replace('.', '<prd>'))
text = re.sub(prefixes,"\\1<prd>",text)
text = re.sub(websites,"<prd>\\1",text)
text = re.sub(digits + "[.]" + digits,"\\1<prd>\\2",text)
if "Ph.D" in text: text = text.replace("Ph.D.","Ph<prd>D<prd>")
text = re.sub("\s" + alphabets + "[.] "," \\1<prd> ",text)
text = re.sub(acronyms+" "+starters,"\\1<stop> \\2",text)
text = re.sub(alphabets + "[.]" + alphabets + "[.]" + alphabets + "[.]","\\1<prd>\\2<prd>\\3<prd>",text)
text = re.sub(alphabets + "[.]" + alphabets + "[.]","\\1<prd>\\2<prd>",text)
text = re.sub(" "+suffixes+"[.] "+starters," \\1<stop> \\2",text)
text = re.sub(" "+suffixes+"[.]"," \\1<prd>",text)
text = re.sub(" " + alphabets + "[.]"," \\1<prd>",text)
if "”" in text: text = text.replace(".”","”.")
if "\"" in text: text = text.replace(".\"","\".")
if "!" in text: text = text.replace("!\"","\"!")
if "?" in text: text = text.replace("?\"","\"?")
# ellipses
for match in re.compile(r"(\.)(\.+)").finditer(text):
text = text.replace(match.group(0), (len(match.group(0)) * '<prd>') + '<stop>')
text = text.replace(".",".<stop>")
text = text.replace("?","?<stop>")
text = text.replace("!","!<stop>")
text = text.replace("<prd>",".")
sentences = text.split("<stop>")
sentences = [s.strip() for s in sentences]
sentences = [s for s in sentences if not len(s) == 0]
print(text)
print(sentences)
return sentences
text = "This is a test sentence! This is sentence two. I am sentence three?"
TextSplitter.split_into_sentences(text) | {
"domain": "codereview.stackexchange",
"id": 43342,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, strings, parsing, regex",
"url": null
} |
python, strings, parsing, regex
TextSplitter.split_into_sentences(text)
The code produces the following output:
This is a test sentence!<stop> This is sentence two.<stop> I am sentence three?<stop>
['This is a test sentence!', 'This is sentence two.', 'I am sentence three?'] | {
"domain": "codereview.stackexchange",
"id": 43342,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, strings, parsing, regex",
"url": null
} |
python, strings, parsing, regex
Answer: Include spaces after commas. It's a virtually costless habit and it helps
with code readability and editability.
Constants are typically named with uppercase. Your program begins with
several constants. Format their names accordingly: ALPHABETS, PREFIXES,
etc.
If you use the same value repeatedly, declare it as a constant. For
example STOP = '<stop>' or PRD = '<prd>'. This is a good typo/bug avoidance
habit to adopt.
Don't use classes without a reason. The simplest, most natural way to
organize programs is with well-designed functions. Don't add classes to the
picture unless you have a good reason. In the current code, TextSplitter
isn't doing anything, as illustrated by the fact that self is never used. [A
separate issue: the first argument to a classmethod is usually named cls,
not self, because the method receives the class, not an instance, as its
argument. In your case, staticmethod would have been more appropriate, since
you never use self or cls. But since TextSplitter isn't doing anything,
none of that matters.]
Functions should be focused. Your function is doing two major things: (1)
a bunch of search-replace operations, and (2) splitting into sentences. Split
that behavior into two separate functions: for example, normalize_text()
and split_into_sentences().
Functions should return data, not print. Whenever it's practical to do
so, functions should return data, not cause side-effects like printing. Do
the printing elsewhere -- typically the outer edge of the program where there
is as little algorithmic complexity as possible. Data-oriented functions
can be conveniently tested and debugged. Side-effect-oriented functions are
a hassle in those regards.
def main():
text = '...'
normalized = normalize_text(text)
sentences = split_into_sentences(normalized)
print(normalized)
print(sentences)
if __name__ == '__main__':
main() | {
"domain": "codereview.stackexchange",
"id": 43342,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, strings, parsing, regex",
"url": null
} |
python, strings, parsing, regex
if __name__ == '__main__':
main()
Your conditional checks are not doing anything. They all check for
a prerequisite that is already embedded in the replacement operation.
They are the moral equivalent of if X in TEXT, replace X with Y.
Just try to perform the replacement directly.
Alternative ways to split into sentences. Because empty strings
are false, you don't need to check their length to reject them.
Instead, you can just write [s for s in sentences if s]. Alternatively,
and this is neither better nor worse, you could use the built-in
filter():
STOP = '<stop>'
def split_into_sentences(text):
m = map(str.strip, text.split(STOP))
return list(filter(None, m)) | {
"domain": "codereview.stackexchange",
"id": 43342,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, strings, parsing, regex",
"url": null
} |
python, strings, parsing, regex
Disclaimer. I did not think about the details of your regular expressions
or the various text replacements. I don't have enough context about your
broader goals to give specific advice on that front.
Should you try to generalize the replacement behavior? You asked about this and your question is a good one. For
example, one could define a little Replacer class that would take various
optional parameters like regex, search, and replace. The
class would define its __call__(self, text) method to perform the appropriate
type of replacing operation, depending on which parameters were provided. Then
you would define a REPLACERS constant consisting of a sequence of those
Replacer instances. And the normalize_text() function would just iterate
over REPLACERS, calling each one with text as its argument: for r in REPLACERS: text = r(text). Note that with this callable-based implementation,
any ordinary function that takes and returns text can also
operate successfully as a "Replacer", so any unusual replacement
needs can be defined via tiny utility functions.
Is all of that worth the trouble? Maybe, if this
code is part of a bigger project and you anticipate further growth and
elaboration of the kinds of replacements occurring. Or
maybe, if you want to try to implement it as a learning exercise.
But absent those motivations, the normalize_text()
function (after the other edits suggested above) is just a linear sequence of
about 25 steps that is fairly easy to understand, so I probably would not
bother with such a refactoring. | {
"domain": "codereview.stackexchange",
"id": 43342,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, strings, parsing, regex",
"url": null
} |
c#, enum, extension-methods, circular-list
Title: Naming a method that gets the next enum value or starts from the beginning if the given value is the last
Question: I'm struggling to find a proper name for a specific method (in code named NameOfExtension), and would also like some feedback about its implementation.
I am writting an extension method that must return the next enum value given a specific enum item (order is given by GetValues method). If it reaches the end, it should continue from the beginning:
public static T NameOfExtension<T>(this T enumItem)
where T : Enum
{
List<T> items = GetValues<T>().ToList();
int idx = items.IndexOf(enumItem);
if (idx + 1 < items.Count)
{
return items[idx + 1];
}
return items[0];
}
Since we are using an old version of .Net framework (4.72) and can't use .Net6 right now, I had to implement this extension as well:
public static IEnumerable<T> GetValues<T>()
where T : Enum
{
return Enum.GetValues(typeof(T)).Cast<T>();
}
Answer: The key phrase you're looking for here is cyclic(al) (I prefer cyclic over cyclical but this is subjective). My suggestion is therefore GetNextCyclicValue.
You can also simplify your code by using the % modulo operator, as its output very neatly aligns with a zero-based index.
public static T GetNextCyclicValue<T>(this T enumItem)
where T : Enum
{
List<T> values = GetValues<T>().ToList();
int currentIndex = values.IndexOf(enumItem);
int nextIndex = (currentIndex + 1) % values.Count;
return values[nextIndex];
}
Or if you want to condense it:
public static T GetNextCyclicValue<T>(this T enumItem)
where T : Enum
{
List<T> values = GetValues<T>().ToList();
return values[(values.IndexOf(enumItem) + 1) % values.Count];
} | {
"domain": "codereview.stackexchange",
"id": 43343,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, enum, extension-methods, circular-list",
"url": null
} |
javascript, algorithm, numerical-methods
Title: Calculate the value of PI in JS
Question: I have created an algorithm which calculates the value of PI in JavaScript.
Can this algorithm to be improved?
let PI = 0;
for(let i=0; i<80; i++){
let numerator = Math.pow(factorial(i), 2) * Math.pow(2, i+1);
let denominator = factorial((2 * i + 1));
PI += numerator / denominator;
}
function factorial(n){
return(n<2)?1:factorial(n-1)*n;
}
console.log("Value of pi: " + PI);
Answer: There's no need to recalculate the factorials and powers from scratch each time around the loop. Remember the last values and just multiply to get the next value.
Approximate idea (untested, and by a Javascript novice, so likely containing some mistakes):
let PI = 0;
let top = 1;
let pow2 = 2;
let denominator = 1;
for (let i = 1; i <= 80; i++) {
PI += top * top * pow2 / denominator;
top *= i;
pow2 *= 2;
denominator *= (2 * i) * (2 * i + 1);
} | {
"domain": "codereview.stackexchange",
"id": 43344,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, algorithm, numerical-methods",
"url": null
} |
c#, performance, asp.net-core, entity-framework-core
Title: Get a list of the 25 most popular items on an E-Commerce site
Question: I have a few lines where I am trying to get a list of the 25 most popular Items sold on an E-Commerce web site. The code works but I would like hints on how to optimize it.
var ecommerceItems = await _context.BmaEcItems
.Select(e => e.Itemnmbr)
.ToListAsync();
IList<PopularItem> popularItems = new List<PopularItem>();
foreach (var item in ecommerceItems)
{
var pi = new PopularItem
{
ItemNumber = item,
QuantitySold = await _context.OrderDetails.Where(e => e.Itemnmbr == item).SumAsync(e => Convert.ToInt32(e.Quantity))
};
popularItems.Add(pi);
}
var itemList = popularItems.OrderByDescending(e => e.QuantitySold).Select(e => e.ItemNumber).Take(25).ToList(); | {
"domain": "codereview.stackexchange",
"id": 43345,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, asp.net-core, entity-framework-core",
"url": null
} |
c#, performance, asp.net-core, entity-framework-core
BmaEcItems is a list of all items sold via the E-Commerce web site (It is a subset of a master inventory list). OrderDetails is a list of the details of the sales orders (This is a list of all item details sold and includes items not on the BmaEcItems list).
Any hints are appreciated.
UPDATE
As requested:
public partial class BmaEcItem : INotifyPropertyChanged
{
public string Itemnmbr { get; set; }
public string ExtendedDesc { get; set; }
public bool? Featured { get; set; }
public string Metadata1 { get; set; }
public string Metadata2 { get; set; }
public string Metadata3 { get; set; }
public string Metadata4 { get; set; }
public string Metadata5 { get; set; }
public string Metadata6 { get; set; }
public int DefaultStockCount { get; set; }
public bool? DisplayOnEcommerce { get; set; }
public string Metadata7 { get; set; }
public string Metadata8 { get; set; }
public string Metadata9 { get; set; }
public string Metadata10 { get; set; }
public string Metadata11 { get; set; }
public string Metadata12 { get; set; }
public string Metadata13 { get; set; }
public string Metadata14 { get; set; }
public string Metadata15 { get; set; }
public string Metadata16 { get; set; }
public string Metadata17 { get; set; }
public string Metadata18 { get; set; }
public string Metadata19 { get; set; }
public string Metadata20 { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
[Table("SOP10200")]
public class OrderDetail : INotifyPropertyChanged
{
[Key]
[Column("SOPTYPE")]
[EnumDataType(typeof(OrderType))]
public OrderType Soptype { get; set; } | {
"domain": "codereview.stackexchange",
"id": 43345,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, asp.net-core, entity-framework-core",
"url": null
} |
c#, performance, asp.net-core, entity-framework-core
[Key]
[Column("SOPNUMBE")]
[StringLength(21)]
public string Sopnumbe { get; set; }
[Key]
[Column("LNITMSEQ")]
public int Lnitmseq { get; set; }
[Key]
[Column("CMPNTSEQ")]
public int Cmpntseq { get; set; }
[Required]
[Column("ITEMNMBR")]
[StringLength(31)]
public string Itemnmbr { get; set; }
[Required]
[Column("ITEMDESC")]
[StringLength(101)]
public string Itemdesc { get; set; }
[Column("NONINVEN")]
public short Noninven { get; set; }
[Column("DROPSHIP")]
public short Dropship { get; set; }
[Required]
[Column("UOFM")]
[StringLength(9)]
public string Uofm { get; set; }
[Required]
[Column("LOCNCODE")]
[StringLength(11)]
public string Locncode { get; set; }
[Column("UNITCOST", TypeName = "numeric(19, 5)")]
public decimal Unitcost { get; set; }
[Column("ORUNTCST", TypeName = "numeric(19, 5)")]
public decimal Oruntcst { get; set; }
[Column("UNITPRCE", TypeName = "numeric(19, 5)")]
public decimal Unitprce { get; set; }
[Column("ORUNTPRC", TypeName = "numeric(19, 5)")]
public decimal Oruntprc { get; set; }
[Column("XTNDPRCE", TypeName = "numeric(19, 5)")]
public decimal Xtndprce { get; set; }
[Column("OXTNDPRC", TypeName = "numeric(19, 5)")]
public decimal Oxtndprc { get; set; }
[Column("REMPRICE", TypeName = "numeric(19, 5)")]
public decimal Remprice { get; set; }
[Column("OREPRICE", TypeName = "numeric(19, 5)")]
public decimal Oreprice { get; set; }
[Column("EXTDCOST", TypeName = "numeric(19, 5)")]
public decimal Extdcost { get; set; }
[Column("OREXTCST", TypeName = "numeric(19, 5)")]
public decimal Orextcst { get; set; }
[Column("MRKDNAMT", TypeName = "numeric(19, 5)")]
public decimal Mrkdnamt { get; set; }
[Column("ORMRKDAM", TypeName = "numeric(19, 5)")]
public decimal Ormrkdam { get; set; }
[Column("MRKDNPCT")]
public short Mrkdnpct { get; set; } | {
"domain": "codereview.stackexchange",
"id": 43345,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, asp.net-core, entity-framework-core",
"url": null
} |
c#, performance, asp.net-core, entity-framework-core
[Column("MRKDNPCT")]
public short Mrkdnpct { get; set; }
[Column("MRKDNTYP")]
public short Mrkdntyp { get; set; }
[Column("INVINDX")]
public int Invindx { get; set; }
[Column("CSLSINDX")]
public int Cslsindx { get; set; }
[Column("SLSINDX")]
public int Slsindx { get; set; }
[Column("MKDNINDX")]
public int Mkdnindx { get; set; }
[Column("RTNSINDX")]
public int Rtnsindx { get; set; }
[Column("INUSINDX")]
public int Inusindx { get; set; }
[Column("INSRINDX")]
public int Insrindx { get; set; }
[Column("DMGDINDX")]
public int Dmgdindx { get; set; }
[Required]
[Column("ITMTSHID")]
[StringLength(15)]
public string Itmtshid { get; set; }
[Column("IVITMTXB")]
public short Ivitmtxb { get; set; }
[Column("BKTSLSAM", TypeName = "numeric(19, 5)")]
public decimal Bktslsam { get; set; }
[Column("ORBKTSLS", TypeName = "numeric(19, 5)")]
public decimal Orbktsls { get; set; }
[Column("TAXAMNT", TypeName = "numeric(19, 5)")]
public decimal Taxamnt { get; set; }
[Column("ORTAXAMT", TypeName = "numeric(19, 5)")]
public decimal Ortaxamt { get; set; }
[Column("TXBTXAMT", TypeName = "numeric(19, 5)")]
public decimal Txbtxamt { get; set; }
[Column("OTAXTAMT", TypeName = "numeric(19, 5)")]
public decimal Otaxtamt { get; set; }
[Column("BSIVCTTL")]
public byte Bsivcttl { get; set; }
[Column("TRDISAMT", TypeName = "numeric(19, 5)")]
public decimal Trdisamt { get; set; }
[Column("ORTDISAM", TypeName = "numeric(19, 5)")]
public decimal Ortdisam { get; set; }
[Column("DISCSALE", TypeName = "numeric(19, 5)")]
public decimal Discsale { get; set; }
[Column("ORDAVSLS", TypeName = "numeric(19, 5)")]
public decimal Ordavsls { get; set; }
[Column("QUANTITY", TypeName = "numeric(19, 5)")]
public decimal Quantity { get; set; }
[Column("ATYALLOC", TypeName = "numeric(19, 5)")] | {
"domain": "codereview.stackexchange",
"id": 43345,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, asp.net-core, entity-framework-core",
"url": null
} |
c#, performance, asp.net-core, entity-framework-core
public decimal Quantity { get; set; }
[Column("ATYALLOC", TypeName = "numeric(19, 5)")]
public decimal Atyalloc { get; set; }
[Column("QTYINSVC", TypeName = "numeric(19, 5)")]
public decimal Qtyinsvc { get; set; }
[Column("QTYINUSE", TypeName = "numeric(19, 5)")]
public decimal Qtyinuse { get; set; }
[Column("QTYDMGED", TypeName = "numeric(19, 5)")]
public decimal Qtydmged { get; set; }
[Column("QTYRTRND", TypeName = "numeric(19, 5)")]
public decimal Qtyrtrnd { get; set; }
[Column("QTYONHND", TypeName = "numeric(19, 5)")]
public decimal Qtyonhnd { get; set; }
[Column("QTYCANCE", TypeName = "numeric(19, 5)")]
public decimal Qtycance { get; set; }
[Column("QTYCANOT", TypeName = "numeric(19, 5)")]
public decimal Qtycanot { get; set; }
[Column("QTYONPO", TypeName = "numeric(19, 5)")]
public decimal Qtyonpo { get; set; }
[Column("QTYORDER", TypeName = "numeric(19, 5)")]
public decimal Qtyorder { get; set; }
[Column("QTYPRBAC", TypeName = "numeric(19, 5)")]
public decimal Qtyprbac { get; set; }
[Column("QTYPRBOO", TypeName = "numeric(19, 5)")]
public decimal Qtyprboo { get; set; }
[Column("QTYPRINV", TypeName = "numeric(19, 5)")]
public decimal Qtyprinv { get; set; }
[Column("QTYPRORD", TypeName = "numeric(19, 5)")]
public decimal Qtyprord { get; set; }
[Column("QTYPRVRECVD", TypeName = "numeric(19, 5)")]
public decimal Qtyprvrecvd { get; set; }
[Column("QTYRECVD", TypeName = "numeric(19, 5)")]
public decimal Qtyrecvd { get; set; }
[Column("QTYREMAI", TypeName = "numeric(19, 5)")]
public decimal Qtyremai { get; set; }
[Column("QTYREMBO", TypeName = "numeric(19, 5)")]
public decimal Qtyrembo { get; set; }
[Column("QTYTBAOR", TypeName = "numeric(19, 5)")]
public decimal Qtytbaor { get; set; }
[Column("QTYTOINV", TypeName = "numeric(19, 5)")]
public decimal Qtytoinv { get; set; } | {
"domain": "codereview.stackexchange",
"id": 43345,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, asp.net-core, entity-framework-core",
"url": null
} |
c#, performance, asp.net-core, entity-framework-core
[Column("QTYTOINV", TypeName = "numeric(19, 5)")]
public decimal Qtytoinv { get; set; }
[Column("QTYTORDR", TypeName = "numeric(19, 5)")]
public decimal Qtytordr { get; set; }
[Column("QTYFULFI", TypeName = "numeric(19, 5)")]
public decimal Qtyfulfi { get; set; }
[Column("QTYSLCTD", TypeName = "numeric(19, 5)")]
public decimal Qtyslctd { get; set; }
[Column("QTYBSUOM", TypeName = "numeric(19, 5)")]
public decimal Qtybsuom { get; set; }
[Column("EXTQTYAL", TypeName = "numeric(19, 5)")]
public decimal Extqtyal { get; set; }
[Column("EXTQTYSEL", TypeName = "numeric(19, 5)")]
public decimal Extqtysel { get; set; }
[Column(TypeName = "datetime")]
public DateTime ReqShipDate { get; set; }
[Column("FUFILDAT", TypeName = "datetime")]
public DateTime Fufildat { get; set; }
[Column("ACTLSHIP", TypeName = "datetime")]
public DateTime Actlship { get; set; }
[Required]
[Column("SHIPMTHD")]
[StringLength(15)]
public string Shipmthd { get; set; }
[Required]
[Column("SALSTERR")]
[StringLength(15)]
public string Salsterr { get; set; }
[Required]
[Column("SLPRSNID")]
[StringLength(15)]
public string Slprsnid { get; set; }
[Required]
[Column("PRCLEVEL")]
[StringLength(11)]
public string Prclevel { get; set; }
[Required]
[Column("COMMNTID")]
[StringLength(15)]
public string Commntid { get; set; }
[Column("BRKFLD1")]
public short Brkfld1 { get; set; }
[Column("BRKFLD2")]
public short Brkfld2 { get; set; }
[Column("BRKFLD3")]
public short Brkfld3 { get; set; }
[Column("CURRNIDX")]
public short Currnidx { get; set; }
[Required]
[Column("TRXSORCE")]
[StringLength(13)]
public string Trxsorce { get; set; }
[Required]
[Column("SOPLNERR")]
[MaxLength(4)]
public byte[] Soplnerr { get; set; }
[Column("ORGSEQNM")]
public int Orgseqnm { get; set; }
[Required] | {
"domain": "codereview.stackexchange",
"id": 43345,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, asp.net-core, entity-framework-core",
"url": null
} |
c#, performance, asp.net-core, entity-framework-core
[Column("ORGSEQNM")]
public int Orgseqnm { get; set; }
[Required]
[Column("ITEMCODE")]
[StringLength(15)]
public string Itemcode { get; set; }
[Column("PURCHSTAT")]
public short Purchstat { get; set; }
[Column("DECPLQTY")]
public short Decplqty { get; set; }
[Column("DECPLCUR")]
public short Decplcur { get; set; }
[Column("ODECPLCU")]
public short Odecplcu { get; set; }
[Column("QTYTOSHP", TypeName = "numeric(19, 5)")]
public decimal Qtytoshp { get; set; }
[Column("XFRSHDOC")]
public byte Xfrshdoc { get; set; }
[Column("EXCEPTIONALDEMAND")]
public byte Exceptionaldemand { get; set; }
[Required]
[Column("TAXSCHID")]
[StringLength(15)]
public string Taxschid { get; set; }
[Column("TXSCHSRC")]
public short Txschsrc { get; set; }
[Required]
[Column("PRSTADCD")]
[StringLength(15)]
public string Prstadcd { get; set; }
[Required]
[StringLength(65)]
public string ShipToName { get; set; }
[Required]
[Column("CNTCPRSN")]
[StringLength(61)]
public string Cntcprsn { get; set; }
[Required]
[Column("ADDRESS1")]
[StringLength(61)]
public string Address1 { get; set; }
[Required]
[Column("ADDRESS2")]
[StringLength(61)]
public string Address2 { get; set; }
[Required]
[Column("ADDRESS3")]
[StringLength(61)]
public string Address3 { get; set; }
[Required]
[Column("CITY")]
[StringLength(35)]
public string City { get; set; }
[Required]
[Column("STATE")]
[StringLength(29)]
public string State { get; set; }
[Required]
[Column("ZIPCODE")]
[StringLength(11)]
public string Zipcode { get; set; }
[Required]
[Column("CCode")]
[StringLength(7)]
public string Ccode { get; set; }
[Required]
[Column("COUNTRY")]
[StringLength(61)]
public string Country { get; set; }
[Required]
[Column("PHONE1")]
[StringLength(21)] | {
"domain": "codereview.stackexchange",
"id": 43345,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, asp.net-core, entity-framework-core",
"url": null
} |
c#, performance, asp.net-core, entity-framework-core
public string Country { get; set; }
[Required]
[Column("PHONE1")]
[StringLength(21)]
public string Phone1 { get; set; }
[Required]
[Column("PHONE2")]
[StringLength(21)]
public string Phone2 { get; set; }
[Required]
[Column("PHONE3")]
[StringLength(21)]
public string Phone3 { get; set; }
[Required]
[Column("FAXNUMBR")]
[StringLength(21)]
public string Faxnumbr { get; set; }
public short Flags { get; set; }
[Column(TypeName = "numeric(19, 5)")]
public decimal BackoutTradeDisc { get; set; }
[Column(TypeName = "numeric(19, 5)")]
public decimal OrigBackoutTradeDisc { get; set; }
[Required]
[Column("GPSFOINTEGRATIONID")]
[StringLength(31)]
public string Gpsfointegrationid { get; set; }
[Column("INTEGRATIONSOURCE")]
public short Integrationsource { get; set; }
[Required]
[Column("INTEGRATIONID")]
[StringLength(31)]
public string Integrationid { get; set; }
[Required]
[Column("CONTNBR")]
[StringLength(11)]
public string Contnbr { get; set; }
[Column("CONTLNSEQNBR", TypeName = "numeric(19, 5)")]
public decimal Contlnseqnbr { get; set; }
[Column("CONTSTARTDTE", TypeName = "datetime")]
public DateTime Contstartdte { get; set; }
[Column("CONTENDDTE", TypeName = "datetime")]
public DateTime Contenddte { get; set; }
[Required]
[Column("CONTITEMNBR")]
[StringLength(31)]
public string Contitemnbr { get; set; }
[Required]
[Column("CONTSERIALNBR")]
[StringLength(21)]
public string Contserialnbr { get; set; }
[Column("BULKPICKPRNT")]
public byte Bulkpickprnt { get; set; }
[Column("INDPICKPRNT")]
public byte Indpickprnt { get; set; }
[Column("ISLINEINTRA")]
public byte Islineintra { get; set; }
[Required]
[Column("SOFULFILLMENTBIN")]
[StringLength(15)]
public string Sofulfillmentbin { get; set; }
[Column("MULTIPLEBINS")] | {
"domain": "codereview.stackexchange",
"id": 43345,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, performance, asp.net-core, entity-framework-core",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.