text stringlengths 1 2.12k | source dict |
|---|---|
javascript, strings, unit-testing, regex
let text = 'adam';
let search = 'adm';
let replace = 'ev';
let expected = 'eve';
let actual = tr(text, search, replace, flags);
expect(actual).to.be.equal(expected);
});
});
describe('with ds flags', () => {
before(() => {
flags = 'ds';
});
it('should produce a function that transliterates abba to p when search is ab and replacement is p', () => {
let text = 'abba';
let search = 'ab';
let replace = 'p';
let expected = 'p';
let actual = tr(text, search, replace, flags);
expect(actual).to.be.equal(expected);
});
});
});
describe('characters that would need escaping e.g. "()[]{}..."', () => {
describe('without flags', () => {
it('should produce a function that transliterates ( to ) when search [({< is and replacement is ])}>', () => {
let text = '(';
let search = '[({<';
let replace = '])}>';
let expected = ')';
let actual = tr(text, search, replace);
expect(actual).to.be.equal(expected);
});
it('should produce a function that transliterates ()abc to [)qbc when search is (a and replacement is [q', () => {
let text = '()abc';
let search = '(a';
let replace = '[q';
let expected = '[)qbc';
let actual = tr(text, search, replace);
expect(actual).to.be.equal(expected);
});
});
describe('with s flag', () => {
beforeEach(() => {
flags = 's';
});
it('should produce a function that transliterates () to ( when search is [](){}<> and replacement is [[(({{<<', () => {
let text = '()';
let search = '[](){}<>';
let replace = '[[(({{<<';
let expected = '(';
let actual = tr(text, search, replace, flags);
expect(actual).to.be.equal(expected);
});
});
});
describe('with d flag', () => {
beforeEach(() => {
flags = 'd';
});
it('should produce a function that transliterates ()[] to ){} when search is []( and replacement is {}', () => { | {
"domain": "codereview.stackexchange",
"id": 44725,
"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, strings, unit-testing, regex",
"url": null
} |
javascript, strings, unit-testing, regex
let text = '()[]';
let search = '[](';
let replace = '{}';
let expected = '){}';
let actual = tr(text, search, replace, flags);
expect(actual).to.be.equal(expected);
});
});
describe('with ds flags', () => {
beforeEach(() => {
flags = 'ds';
});
it('should produce a function that transliterates ()a to (a when search is [](){}<> and replacement is [[(({{<<', () => {
let text = '()a';
let search = '[](){}<>';
let replace = '[[(({{<<';
let expected = '(a';
let actual = tr(text, search, replace, flags);
expect(actual).to.be.equal(expected);
});
it('should produce a function that transliterates ()a to ( when search is [](){}<>\\0-\\377 and replacement is [[(({{<<', () => {
let text = '()a';
let search = '[](){}<>\\0-\\377';
let replace = '[[(({{<<';
let expected = '(';
let actual = tr(text, search, replace, flags);
expect(actual).to.be.equal(expected);
});
}); | {
"domain": "codereview.stackexchange",
"id": 44725,
"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, strings, unit-testing, regex",
"url": null
} |
javascript, strings, unit-testing, regex
And the actual function:
export function tr(text, search, replace, flags) {
let escapedObj = _charsNeedEscaping(search);
let escaped = escapedObj.replaced;
let escapedSearch = escapedObj.text;
let replacementRegex = new RegExp('[' + escapedSearch + ']', 'g');
let obj = {};
let pos = 0;
let t = text.replace(replacementRegex, function (chr) {
let r = '';
if (flags) {
if (flags.match(/ds/)) {
r = _dFlag(chr, pos, search, replace, obj, escaped);
if (r) {
let retDeets = _sFlag(chr, pos, search, replace, obj, escaped);
r = retDeets.r;
obj = retDeets.charKeeper;
pos = retDeets.pos;
}
} else if (flags.match(/s/)) {
let retDeets = _sFlag(chr, pos, search, replace, obj, escaped);
r = retDeets.r;
obj = retDeets.charKeeper;
pos = retDeets.pos;
}
else if (flags.match(/d/)) {
r = _dFlag(chr, pos, search, replace, obj, escaped);
}
} else {
let ind = search.indexOf(chr);
r = replace.charAt(ind);
if (r === '') {
r = replace.charAt(replace.length - 1);
}
}
return r;
});
return t;
}
function _dFlag(chr, pos, search, replace, obj) {
let r = '';
if (replace) {
let ind = search.indexOf(chr);
if (replace.length >= ind) {
r = replace.charAt(ind);
}
}
return r;
} | {
"domain": "codereview.stackexchange",
"id": 44725,
"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, strings, unit-testing, regex",
"url": null
} |
javascript, strings, unit-testing, regex
function _sFlag(chr, pos, search, replace, obj, escaped) {
let escapedChrDeets = _charsNeedEscaping(chr);
let escapedChr = escapedChrDeets.text;
let searchRegExp = new RegExp(escapedChr, 'y');
if (escaped) {
pos = search.indexOf(chr);
}
searchRegExp.lastIndex = pos;
let searchMatch = search.match(searchRegExp);
let r = '';
if (searchMatch) {
let searchChr = searchMatch[0];
if (searchChr in obj) {
r = replace.charAt(obj[searchChr]);
if (obj[searchChr]+1 === searchMatch.index) {
r = '';
}
} else {
let replacementIndex = searchMatch.index;
obj[searchChr] = replacementIndex;
r = replace.charAt(replacementIndex);
if (r === '') {
r = searchChr;
} else if (r === replace.charAt(replacementIndex-1)) {
r = '';
}
}
pos++;
} else {
r = replace.charAt(obj[chr]);
if (pos-1 === obj[chr]) {
r = '';
}
pos++;
}
return {
r: r,
pos: pos,
charKeeper: obj
};
}
function _charsNeedEscaping(src) {
let text = src;
let res = {
'text': text,
'replaced': false,
};
if (res.text.match(/\[/) ) {
res.text = res.text.replace(/\[/g, '\\[');
res.replaced = true;
}
if (text.match(/\]/) ) {
res.text = res.text.replace(/\]/g, '\\]');
res.replaced = true;
}
if (res.text.match(/\(/) ) {
res.text = res.text.replace(/\(/g, '\\(');
res.replaced = true;
}
if (text.match(/\)/) ) {
res.text = res.text.replace(/\)/g, '\\)');
res.replaced = true;
}
if (res.text.match(/\</) ) {
res.text = res.text.replace(/\</g, '\\<');
res.replaced = true;
}
if (text.match(/\>/) ) {
res.text = res.text.replace(/\>/g, '\\>');
res.replaced = true;
} | {
"domain": "codereview.stackexchange",
"id": 44725,
"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, strings, unit-testing, regex",
"url": null
} |
javascript, strings, unit-testing, regex
if (res.text.match(/\{/) ) {
res.text = res.text.replace(/\{/g, '\\{');
res.replaced = true;
}
if (text.match(/\}/) ) {
res.text = res.text.replace(/\}/g, '\\}');
res.replaced = true;
}
return res;
}
Answer: Good work with the unit tests! They made it much simpler to check if I broke something when reworking some of your logic.
I've never used Perl, so had to play around with a repl for a while in order to understand the tr function. I may certainly still be missing some functionality here!
While playing with tr, I noticed a couple discrepancies between your version and the built in version.
The s flag doesn't always squash replaced characters.
my $string = '()aa))';
$string =~ tr/()/((/ds;
print "$string\n"; # => (aa(
With tr('()aa))', '()', ((', 'ds') I receive (aa(( instead of the expected (aa(.
Squashing isn't greedy enough.
my $string = 'abbba';
$string =~ tr/b/a/s;
print "$string\n"; # => aaa
With tr('abbba', 'b', 'a', 's') I receive aaaa.
With this in mind I added three new unit tests:
it('Should handle multiple locations for squashed characters', () => {
const expected = '(aa(';
const actual = tr('()aa))', '()', '((', 'ds');
expect(actual).to.equal(expected);
});
it('Should be greedy when squashing replaced characters', () => {
const expected = 'aaa';
const actual = tr('abbba', 'b', 'a', 's');
expect(actual).to.equal(expected);
});
it('Should handle squashing characters with multiple source characters', () => {
const expected = 'aaa';
const actual = tr('abccbba', 'bc', 'a', 's');
expect(actual).to.equal(expected);
});
Now, to your code! | {
"domain": "codereview.stackexchange",
"id": 44725,
"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, strings, unit-testing, regex",
"url": null
} |
javascript, strings, unit-testing, regex
Now, to your code!
In the unit tests, you have a lot of duplication in defining text, search, replace, expected, and actual in every test. I believe it helps the readability to drop text, search, and replace as I did in the new tests shown above. You could further reduce the amount of code by defining an array of tests that you loop through, but there are few enough tests that that may not be helpful here.
I expected to be able to pass in sd or ds flags for the same effect. Order shouldn't matter here.
_sFlag, _dFlag and _charsNeedEscaping don't tell me anything about what the function will do - try to be more descriptive in your variable names. obj is even more cryptic. It's fine to use non-descriptive names in very short functions, but in longer functions, it makes the logic incredibly difficult to follow.
You should lint your code, it helps find potential errors. ESLint points out a few problems with the default configuration.
_dFlag's obj parameter isn't used.
You unnecessarily escape characters in the regular expressions in _charsNeedEscaping, this makes the regex harder to read.
The first thing that stuck out to me when reading through your code is that _charsNeedEscaping is much longer than it needs to be. You can use $& in your replace string to refer to the match text. With this knowledge, _charsNeedEscaping can be trivially written as a single replace statement. I have added a few missing regex special characters that were missing from your function. (Only - and \ are left out)
const escapeRequiredChars = s => s.replace(/[\/^$*+?.()|[\]{}]/g, '\\$&');
Don't unnecessarily quote object keys.
let res = {
'text': text,
'replaced': false,
};
Is equivalent to:
let res = {
text: text,
replaced: false,
};
In this case, since text is named the same as the property name, it can be further simplified to:
let res = {
text,
replaced: false,
}; | {
"domain": "codereview.stackexchange",
"id": 44725,
"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, strings, unit-testing, regex",
"url": null
} |
javascript, strings, unit-testing, regex
There is a str.includes function. When possible, use it instead of /regex/.match. When you just care if a string matches a regex, use /regex/.test instead of /regex/.match.
Don't assign unnecessary variables, t in the tr function is assigned then immediately returned. In _charsNeedEscaping, text is just an alias to src, just rename src to text.
Prefer const to let when possible - this makes it possible to immediately tell when a variable will be redefined and when it won't change.
You might be interested in learning about destructuring, it could help with some of your object handling code.
With all this in mind, here is how I would implement tr. It passes all of your provided tests and the three extra I wrote. I took a slightly different approach than your solution, though the general idea is the same.
const escapeRequiredChars = s => s.replace(/[\/^$*+?.()|[\]{}]/g, '\\$&');
function tr(text, search, replace, flags = '') {
const escaped = escapeRequiredChars(search);
let lastReplaceChar = '';
let lastReplaceEnd = 0;
return text.replace(new RegExp(`([${escaped}])\\1*`, 'g'), (chars, char, offset) => {
// Reset lastReplaceChar after passing something that hasn't been replaced
if (lastReplaceEnd < offset) {
lastReplaceChar = '';
}
lastReplaceEnd = offset + chars.length;
// Find replacement
const replaceIndex = search.indexOf(char);
let replacement = replace[replaceIndex];
if (!replacement) {
if (flags.includes('d')) return '';
replacement = replace[replace.length - 1] || char;
}
// Handle squashing when the squashed character has already been output.
if (lastReplaceChar == replacement && flags.includes('s')) {
return '';
}
lastReplaceChar = replacement;
const returnCount = flags.includes('s') ? 1 : chars.length;
return replacement.repeat(returnCount);
});
} | {
"domain": "codereview.stackexchange",
"id": 44725,
"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, strings, unit-testing, regex",
"url": null
} |
python, classes
Title: Library: Point class
Question: Recently I made a point dataclass and a point_calc class which performs various commonly used algorithms on a point.
from dataclasses import dataclass
import math
EPS = 7./3 - 4./3 -1
#note 7./3 - 4./3 -1: https://stackoverflow.com/questions/19141432/python-numpy-machine-epsilon
@dataclass
class point:
x: float = 0.0
y: float = 0.0
#x first then y (2,3) > (1,4) and (2,4) > (2,3)
def __lt__(self, other) -> bool:
if (abs(self.x - other.x) > EPS):
return self.x < other.x
return self.y < other.y
def __eq__(self, other) -> bool:
return (abs(self.x - other.x) < EPS) and (abs(self.y - other.y) < EPS)
def __str__(self):
return "("+str(point.x)+" ,"+str(point.y)+")"
class point_calc:
def dist(self, point, other, t) -> float: # t=0=euclidean, t=1=manhattan
match t:
case 0:
return math.dist([point.x, point.y], [other.x, other.y])
case 1:
return float(abs(abs(point.x-other.x)+abs(point.y-other.y)))
case _:
raise Exception("No Such Function")
###### HELPER FUNCS ######
def dr(self, d) -> float:
return (d*math.pi)/180
def rd(self, r) -> float:
return (r*180)/math.pi
# assumes theta is in Degrees, if not, just use point_clac.rd() to convert to deg
def rotate(self, point, theta, accuracy = 2) -> tuple:
dr = self.dr
return (round(point.x*math.cos(dr(theta))-point.y*math.sin(dr(theta)), accuracy),
round(point.x*math.sin(dr(theta))+point.y*math.cos(dr(theta)), accuracy))
Is there any suggestions on how it can be improved? Any suggestions will be accepted and any help (or constructive criticism) will be appreciated. | {
"domain": "codereview.stackexchange",
"id": 44726,
"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, classes",
"url": null
} |
python, classes
Answer: Style
You should follow PEP 8 style guide, which would help following along your code when reading it, whether it should be reused by someone else, reviewed, or revisited by yourself in the future, when you are more familiar with Python's conventions.
Things that should be improved here:
Surround top-level imports, classes and function defs with 2 blank lines
Do not leave blank lines between comments and the thing they refer to
Prefer docstrings over comments for documenting functions and classes (see also PEP 257 - Docstring Conventions)
Capitalize your class names
Epsilon
The way you get the float epsilon value feels hacky and isn't immediately clear to what it does. Prefer using sys.float_info.epsilon.
"Static" class
Your point_calc class behaves like a static class in other languages. Such a concept doesn't really exist in Python, and top-level functions would be preferred for this kind of functionality.
Naming
Some of your functions and variable names can use more descriptive names:
rd, dr and t are cryptic and not understandable without understanding the code inside: prefer degrees_to_radians, radians_to_degrees and distance_type
dist and point_calc are needlessly abbreviated: prefer distance and point_calculations
theta (argument of rotate) requires knowledge of some mathematical conventions: prefer angle, or better yet angle_degrees or simply degrees to alleviate the ambiguity over units
rotate is ambiguous: prefer rotate_around_origin | {
"domain": "codereview.stackexchange",
"id": 44726,
"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, classes",
"url": null
} |
python, classes
Don't reinvent the wheel
The math standard library module provide the degrees and radians functions, that you should use instead of rolling your own angle conversion, resulting in shorter code.
Single responsibility
Your dist function can do two different things: calculate the Euclidean distance or the Manhattan distance between two points. Although these concepts are related, you either use one or the other, so make it two different function: euclidean_distance(point_a, point_b) and manhattan_distance(point_a, point_b).
The result will be more readable, both by giving each function a single responsibility, and by eliminating the need for a third argument. The third argument would be especially hard to parse for a human reader at the call site.
In cases where you need such an argument for specifying an option, at least use named constants or an enum to pass to the function, along with a meaningful argument name and complete documentation. I don't believe it applies here, as having separate functions is shorter and more readable.
Exception choice
When you raise an exception, avoid using a generic Exception and use as specific an exception as you can, making error handling easier to use down the line. In your case, a ValueError is probably the best fit for invalid values of t in the dist function (although it can be avoided altogether, see above).
Consistency
Your point class implementation of __lt__ compares distances along the x-axis to EPS but not along the y-axis.
However, the implementation of __eq__ compare the distance along both axes to EPS.
I personally wouldn't compare to EPS in either of these methods, and add a close_to method to the point class: def close_to(self, other, tolerance=EPS). | {
"domain": "codereview.stackexchange",
"id": 44726,
"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, classes",
"url": null
} |
python, python-3.x
Title: Function to flatten nested iterables but not some excepted types
Question: I wrote this function to flatten nested iterables (with arbitrary depth) but refrain from flattening excepted types (for instance, string or tuple):
from typing import Iterable, Tuple, Type
def flatten(item: Iterable, except_types: Type | Tuple[Type] | None = None):
if except_types is not None and isinstance(item, except_types):
yield item
for element in item:
if except_types is not None and isinstance(element, except_types):
yield element
continue
try:
yield from flatten(element, except_types)
except TypeError:
yield element
Therefore it works this way:
>>> list(flatten([(1, 2), [(3, 4), [(5, 6), (7, 8)]]], tuple))
[(1, 2), (3, 4), (5, 6), (7, 8)]
Could this code be made more concise and elegant, and yet easily readable? | {
"domain": "codereview.stackexchange",
"id": 44727,
"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",
"url": null
} |
python, python-3.x
Could this code be made more concise and elegant, and yet easily readable?
Answer: The function fails with strings. If the input includes a str, the
function hits a RecursionError. Strings are often a hassle with functions
like this because even after you flatten a string once (eg, converting "foo"
into a list of characters) the elements in the list are of the same iterable
type that you started with, str. The bottom line is that this kind of
function will need some special logic to terminate when it hits single
characters.
Logic can be simplified if except_types defaults to an empty tuple. It
makes the isinstance() check easier.
When writing a recursive function, resist the temptation to look ahead. You
check types twice, at the start of the function and right before recursing.
That's a common temptation (I saw it dozens of times in coding interviews, for
example) and it almost always leads one down a more difficult path. Much better
is to recurse confidently/blindly and let the function's termination checks at
the start of the function do their job.
def flatten(xs, except_types = ()):
# Terminate for except_types.
if isinstance(xs, except_types):
yield xs
return
# Terminate for single characters.
if isinstance(xs, str) and len(xs) == 1:
yield xs
return
# Terminate for non-iterable.
try:
it = iter(xs)
except TypeError:
yield xs
return
# Iterate and recurse with confidence.
for x in it:
yield from flatten(x, except_types) | {
"domain": "codereview.stackexchange",
"id": 44727,
"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",
"url": null
} |
javascript, regex
Title: Username Validation RegExp
Question: Working through the freeCodeCamp JavaScript curriculum and I found this RegExp task surprisingly tricky (maybe I just don't use RegExp very much).
The parameters are:
Usernames can only use alpha-numeric characters.
The only numbers in the username have to be at the end. There can be zero or more of them at the end. Username cannot start with the number.
Username letters can be lowercase and uppercase.
Usernames have to be at least two characters long. A two-character username can only use alphabet letters as characters.
My logic is that since usernames must start with a letter we can begin with /^[a-zA-Z]/i.
From there, a username can contain either:
1 or more letters, followed by 0 or more numbers at the end of the string
OR
2 or more numbers at the end of the string.
Which lead me to the following RegExp: /^[a-z]([a-z]+\d*$|\d{2,}$)/i. This RegExp works but I don't write that much RegExp so I'm not confident it's as simple or elegant as it could be.
Answer: Your regex looks pretty close to optimal to me, unless I'm missing something. The only adjustments I'd make are:
Write some tests if you haven't already (I did ad-hoc tests that can run in the browser, but preferably use a real library like Jest or Mocha).
Use ?: at the start of a parentheses group that you don't need to capture. This communicates the intent of the grouping more clearly to the reader.
Move $ out of the parens to the end to avoid duplication and improve readability.
const p = /^[a-z](?:[a-z]+\d*|\d{2,})$/i;
const shouldFail = [
"a",
"A2",
"2",
"2a",
"a2a",
"z23a",
"2B2",
"AA45678a",
"",
];
const shouldPass = [
"aa",
"aa2",
"a22",
"AA23",
"aa233",
"zA",
"AAA",
"AA45678",
];
const failures = [];
for (const t of shouldFail) {
if (p.test(t)) {
failures.push(`'${t}' is invalid but was reported as valid`);
}
} | {
"domain": "codereview.stackexchange",
"id": 44728,
"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, regex",
"url": null
} |
javascript, regex
for (const t of shouldPass) {
if (!p.test(t)) {
failures.push(`'${t}' is valid but was reported as invalid`);
}
}
failures.forEach(e => console.error(e));
if (failures.length === 0) {
console.log("All tests passed");
} | {
"domain": "codereview.stackexchange",
"id": 44728,
"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, regex",
"url": null
} |
c++, file, console, file-system, windows
Title: ds - A directory switcher via tags in Windows command line
Question: I have this repository.
The idea is that there is a file tags sitting in the users home directory, and which contains the tag declarations of the format <tag> <directory>. For example, the tags file may look like:
home C:\Users\bob
docs C:\Users\bob\Documents
down C:\Users\bob\Downloads
croot C:\
Now, when the user types ds down, Bob's command line changes the current directory to C:\Users\bob\Downloads.
Also, if there is no match for the input tag, we use Levenshtein distance in order to find the closest tag and use it as the requested tag.
Finally, ds remembers the previous directory. So, when the user types simply ds in the command line, it jumps back and forth between the two most recent directories. This allows, faster transition between two directories.
The main component is the directory tag engine, which follows:
#define _CRT_SECURE_NO_WARNINGS
#include <algorithm>
#include <cctype>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <ostream>
#include <string>
#include <ShlObj.h>
#include <vector>
using std::cerr;
using std::cout;
using std::find_if;
using std::getline;
using std::ifstream;
using std::ios_base;
using std::isspace;
using std::istream;
using std::malloc;
using std::min;
using std::ofstream;
using std::ostream;
using std::size_t;
using std::strcpy;
using std::strlen;
using std::string;
using std::vector;
static const string TAG_FILE_NAME = "tags";
static const string COMMAND_FILE_NAME = "ds_command.cmd";
static const string PREVIOUS_DIRECTORY_TAG_NAME = "previous_directory";
static inline void ltrim(std::string& s) {
s.erase(s.begin(), find_if(s.begin(), s.end(), [](unsigned char ch) {
return !isspace(ch);
}));
}
static inline void rtrim(std::string& s) {
s.erase(find_if(s.rbegin(), s.rend(), [](unsigned char ch) {
return !isspace(ch);
}).base(), s.end());
} | {
"domain": "codereview.stackexchange",
"id": 44729,
"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++, file, console, file-system, windows",
"url": null
} |
c++, file, console, file-system, windows
static inline void trim(std::string& s) {
rtrim(s);
ltrim(s);
}
static char* get_home_directory_name() {
CHAR path[MAX_PATH];
// Load the home path name:
SHGetFolderPathA(NULL, CSIDL_PROFILE, NULL, 0, path);
// Get the length of the home path name:
size_t len = strlen(path);
// Allocate space for the home path name copy:
char* copy_path = new char[len + 1];
// Copy the home path name:
strcpy(copy_path, path);
// Zero-terminate the home path name copy:
copy_path[len] = '\0';
return copy_path;
}
static ifstream get_tag_file_ifstream(string const& tag_file_path) {
ifstream ifs(tag_file_path);
return ifs;
}
static ofstream get_tag_file_ofstream(string const& tag_file_path) {
ofstream ofs(tag_file_path, ios_base::trunc);
return ofs;
}
static ofstream get_command_file_stream(string const& command_file_path) {
ofstream ofs(command_file_path, ios_base::trunc);
return ofs;
}
static size_t levenshtein_distance(string const& str1, string const& str2) {
vector<vector<size_t>> matrix;
// Initialize the matrix setting all entries to zero:
for (size_t row_index = 0; row_index <= str1.length(); row_index++) {
vector<size_t> row_vector;
row_vector.resize(str2.length() + 1);
matrix.push_back(row_vector);
}
// Initialize the leftmost column:
for (size_t row_index = 1; row_index <= str1.length(); row_index++) {
matrix.at(row_index).at(0) = row_index;
}
// Initialize the topmost row:
for (size_t column_index = 1;
column_index <= str2.length();
column_index++) {
matrix.at(0).at(column_index) = column_index;
}
for (size_t column_index = 1;
column_index <= str2.length();
column_index++) {
for (size_t row_index = 1; row_index <= str1.length(); row_index++) {
size_t substitution_cost; | {
"domain": "codereview.stackexchange",
"id": 44729,
"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++, file, console, file-system, windows",
"url": null
} |
c++, file, console, file-system, windows
if (str1.at(row_index - 1) == str2.at(column_index - 1)) {
substitution_cost = 0;
}
else {
substitution_cost = 1;
}
matrix.at(row_index).at(column_index) =
min(min(matrix.at(row_index - 1).at(column_index) + 1,
matrix.at(row_index).at(column_index - 1) + 1),
matrix.at(row_index - 1)
.at(column_index - 1) + substitution_cost);
}
}
return matrix.at(str1.length()).at(str2.length());
}
static string get_current_directory_name() {
char path_name[MAX_PATH];
GetCurrentDirectoryA(MAX_PATH - 1, path_name);
return string(path_name);
}
class DirectoryTagEntry {
private:
string tag;
string dir;
public:
DirectoryTagEntry(string tag_, string dir_) :
tag{ tag_ },
dir{ dir_ }
{
}
string get_tag() const {
return tag;
}
string get_dir() const {
return dir;
}
void set_dir(string const& new_dir) {
dir = new_dir;
}
};
std::ostream& operator << (ostream& os, DirectoryTagEntry const& dte) {
os << dte.get_tag() << " " << dte.get_dir();
return os;
}
std::istream& operator >> (istream& is, vector<DirectoryTagEntry>& entries) {
string tag;
string dir;
is >> tag;
getline(is, dir);
trim(tag);
trim(dir);
DirectoryTagEntry dte(tag, dir);
entries.push_back(dte);
return is;
}
static string get_tag_file_path() {
return get_home_directory_name() + string("\\") + TAG_FILE_NAME;
}
static string get_cmd_file_path() {
return get_home_directory_name() + string("\\") + COMMAND_FILE_NAME;
}
static bool tag_matches_previous_directory_tag(DirectoryTagEntry& entry) {
return entry.get_tag() == PREVIOUS_DIRECTORY_TAG_NAME;
} | {
"domain": "codereview.stackexchange",
"id": 44729,
"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++, file, console, file-system, windows",
"url": null
} |
c++, file, console, file-system, windows
static vector<DirectoryTagEntry>::iterator
find_previous_directory_tag_entry_iterator(
vector<DirectoryTagEntry>& entries) {
return find_if(entries.begin(),
entries.end(),
[](DirectoryTagEntry& entry) {
return tag_matches_previous_directory_tag(entry);
});
}
static void process_previous_no_tag_entry(vector<DirectoryTagEntry>& entries) {
string current_path = get_current_directory_name();
DirectoryTagEntry dte(PREVIOUS_DIRECTORY_TAG_NAME, current_path);
entries.push_back(dte);
ofstream tag_file_ofs = get_tag_file_ofstream(get_tag_file_path());
ofstream cmd_file_ofs = get_command_file_stream(get_cmd_file_path());
size_t index = 0;
for (DirectoryTagEntry const& dte : entries) {
tag_file_ofs << dte.get_tag() << " " << dte.get_dir();
if (index < entries.size() - 1) {
tag_file_ofs << "\n";
}
index++;
}
DirectoryTagEntry current_directory_tag_entry(PREVIOUS_DIRECTORY_TAG_NAME,
get_current_directory_name());
tag_file_ofs << current_directory_tag_entry;
cmd_file_ofs << "echo \"Set previous directory to ^\""
<< current_path
<< "^\".";
tag_file_ofs.close();
cmd_file_ofs.close();
}
static void save_tag_file(vector<DirectoryTagEntry> const& entries,
ofstream& ofs) {
size_t index = 0;
for (DirectoryTagEntry const& entry : entries) {
ofs << entry.get_tag() << " " << entry.get_dir();
if (index < entries.size() - 1) {
ofs << "\n";
}
index++;
}
}
static void process_switch_to_previous(
vector<DirectoryTagEntry>& entries,
vector<DirectoryTagEntry>::iterator
previous_directory_tag_entry_const_iterator) {
string next_directory_path =
(*previous_directory_tag_entry_const_iterator).get_dir();
ofstream cmd_file_ofs = get_command_file_stream(get_cmd_file_path()); | {
"domain": "codereview.stackexchange",
"id": 44729,
"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++, file, console, file-system, windows",
"url": null
} |
c++, file, console, file-system, windows
ofstream cmd_file_ofs = get_command_file_stream(get_cmd_file_path());
cmd_file_ofs << "cd " << next_directory_path;
cmd_file_ofs.close();
string current_directory_path = get_current_directory_name();
(*previous_directory_tag_entry_const_iterator)
.set_dir(current_directory_path);
ofstream tag_file_ofs = get_tag_file_ofstream(get_tag_file_path());
save_tag_file(entries, tag_file_ofs);
tag_file_ofs.close();
}
static void process_previous() {
vector<DirectoryTagEntry> entries;
string tag_file_path = get_tag_file_path();
ifstream ifs = get_tag_file_ifstream(tag_file_path);
while (!ifs.eof() && ifs.good()) {
ifs >> entries;
}
ifs.close();
vector<DirectoryTagEntry>::iterator
previous_directory_tag_entry_iterator =
find_previous_directory_tag_entry_iterator(entries);
if (previous_directory_tag_entry_iterator == entries.cend()) {
process_previous_no_tag_entry(entries);
}
else {
process_switch_to_previous(entries, previous_directory_tag_entry_iterator);
}
}
static void create_previous_tag_entry() {
string current_directory_path = get_current_directory_name();
ifstream ifs = get_tag_file_ifstream(get_tag_file_path());
vector<DirectoryTagEntry> entries;
bool previous_entry_updated = false;
while (!ifs.eof() && ifs.good()) {
string tag;
string dir;
ifs >> tag;
getline(ifs, dir);
trim(tag);
trim(dir);
if (tag == PREVIOUS_DIRECTORY_TAG_NAME) {
dir = current_directory_path;
previous_entry_updated = true;
}
DirectoryTagEntry dte(tag, dir);
entries.push_back(dte);
}
if (!previous_entry_updated) {
DirectoryTagEntry dte(PREVIOUS_DIRECTORY_TAG_NAME,
current_directory_path);
entries.push_back(dte);
}
ifs.close(); | {
"domain": "codereview.stackexchange",
"id": 44729,
"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++, file, console, file-system, windows",
"url": null
} |
c++, file, console, file-system, windows
entries.push_back(dte);
}
ifs.close();
ofstream ofs = get_tag_file_ofstream(get_tag_file_path());
size_t index = 0;
for (DirectoryTagEntry const& entry : entries) {
ofs << entry.get_tag() << " " << entry.get_dir();
if (index < entries.size() - 1) {
ofs << "\n";
}
index++;
}
ofs.close();
}
int main(int argc, char* argv[]) {
if (argc == 1) {
process_previous();
return EXIT_SUCCESS;
}
if (argc != 2) {
ofstream ofs = get_command_file_stream(get_cmd_file_path());
ofs << "@echo off\n";
ofs << "echo|set /p=\"Expected 1 argument. "
<< (argc - 1) << " received.\"\n";
return 1;
}
create_previous_tag_entry();
string target_tag = argv[1];
string tag_file_name = get_tag_file_path();
string cmd_file_name = get_cmd_file_path();
ifstream ifs(tag_file_name);
ofstream ofs = get_command_file_stream(get_cmd_file_path());
size_t best_known_levenshtein_distance = SIZE_MAX;
string best_known_directory;
if (ifs.eof()) {
ofs << "echo|set /p=\"The tag file is empty. Please edit ^\""
<< get_home_directory_name() << "\\tags^\"";
ofs.close();
ifs.close();
return 0;
}
while (!ifs.eof() && ifs.good()) {
string tag;
string dir;
ifs >> tag;
getline(ifs, dir);
trim(tag);
trim(dir);
size_t levenshtein_dist = levenshtein_distance(tag, target_tag);
if (levenshtein_dist == 0) {
best_known_directory = dir;
break;
}
if (best_known_levenshtein_distance > levenshtein_dist) {
best_known_levenshtein_distance = levenshtein_dist;
best_known_directory = dir;
}
}
ofs << "cd " << best_known_directory;
ofs.close();
ifs.close();
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 44729,
"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++, file, console, file-system, windows",
"url": null
} |
c++, file, console, file-system, windows
ofs << "cd " << best_known_directory;
ofs.close();
ifs.close();
return 0;
}
Critique request
Since it looks like 5h17 to me, I would like to read comments on the following topics:
Overall program design,
Naming,
Efficiency,
(How about move semantics),
Const-correctness.
Commenting.
Thank you for your time.
Answer: Reconsider Your Imports
Currently, you’re importing pretty much every identifier from std:: that you use. I actively avoid this for names like string and vector that have been used many times for different things. To paraphrase one great answer I read about this in the past, “Whenever I see std::string, I know that this code is using the STL. When I just see string, I’m not sure.”
My own personal preference is to import identifiers that didn’t originally have std:: in front of them (that is, either older than C++98 or from C99) and that I learned to use without std:: in the ’90s. You never have to worry that someone else’s code uses the names cout or size_t for anything else. The same is not true for find_if. Many other people, though, just use std:: consistently. If you’re not some old fogey who still writes cout because that’s how I’ve done it for thirty years, always using std:: will be easier to remember.
If you do keep the long list of imports, you can turn them into a list instead of one per line:
using std::cerr, std::cout, std::min, std::isspace, std::istream, std::ofstream,
std::ostream, std::size_t; | {
"domain": "codereview.stackexchange",
"id": 44729,
"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++, file, console, file-system, windows",
"url": null
} |
c++, file, console, file-system, windows
Use std::filesystem
There’s been filesystem support in the standard library since C++17 that’s more portable than ShlObj.h, and more modern in many ways. For example, it supports standard strings. Additionally, you’re using 8-bit versions of Windows API calls that don’t support Unicode filenames.
Use RAII. Nobody Normally Needs Naked new
You do a lot of manual memory management. Some of it is forced on you by the Windows API. However, right now, you’re returning a char[] that you allocate with new instead of a std::string, which is just a bug waiting to happen. Worse, you mix malloc, new and array new, which all must be deleted manually with different syntax, with no documentation of which one the user is supposed to be using!
Similarly, you should be using input functions that read into a std::string, or other object that manages is memory with RAII, not a fixed-size buffer.
You should change the Windows API calls to standard library calls if those meet your requirements, and stop returning raw pointers. Never write a delete or free outside a destructor, if you can possibly avoid it. Return either a smart pointer or a container object. Even if you need to free its memory manually before the object can be destroyed, for some reason, you can clear it. | {
"domain": "codereview.stackexchange",
"id": 44729,
"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++, file, console, file-system, windows",
"url": null
} |
c++
Title: Spherical distance (Vincenty distance) between two geographic points
Question: I am trying to speed up the code of a R function that calculates a Moran's I autocorrelation coefficient from very large distance matrices between geographic points. So I am exploring approaches to boost my R code using C++. Unfortunately, I am not at all familiar with C++. I found a very interesting C++ code to compute the spherical distance (Vincenty’s distance) between two geographic points. Here is the link and here is the code:
#include <tuple>
#include <pybind11/pybind11.h>
namespace py = pybind11;
std::tuple<double, double> vinc(double latp, double latc, double longp, double longc) {
constexpr double req = 6378137.0; //Radius at equator
constexpr double flat = 1 / 298.257223563; //flattening of earth
constexpr double rpol = (1 - flat) * req;
double sin_sigma, cos_sigma, sigma, sin_alpha, cos_sq_alpha, cos2sigma;
double C, lam_pre;
// convert to radians
latp = M_PI * latp / 180.0;
latc = M_PI * latc / 180.0;
longp = M_PI * longp / 180.0;
longc = M_PI * longc / 180.0;
const double u1 = atan((1 - flat) * tan(latc));
const double u2 = atan((1 - flat) * tan(latp));
double lon = longp - longc;
double lam = lon;
constexpr double tol = pow(10., -12.); // iteration tolerance
double diff = 1.; | {
"domain": "codereview.stackexchange",
"id": 44730,
"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++",
"url": null
} |
c++
while (abs(diff) > tol) {
sin_sigma = sqrt(pow((cos(u2) * sin(lam)), 2.) + pow(cos(u1)*sin(u2) - sin(u1)*cos(u2)*cos(lam), 2.));
cos_sigma = sin(u1) * sin(u2) + cos(u1) * cos(u2) * cos(lam);
sigma = atan(sin_sigma / cos_sigma);
sin_alpha = (cos(u1) * cos(u2) * sin(lam)) / sin_sigma;
cos_sq_alpha = 1 - pow(sin_alpha, 2.);
cos2sigma = cos_sigma - ((2 * sin(u1) * sin(u2)) / cos_sq_alpha);
C = (flat / 16) * cos_sq_alpha * (4 + flat * (4 - 3 * cos_sq_alpha));
lam_pre = lam;
lam = lon + (1 - C) * flat * sin_alpha * (sigma + C * sin_sigma * (cos2sigma + C * cos_sigma * (2 * pow(cos2sigma, 2.) - 1)));
diff = abs(lam_pre - lam);
}
const double usq = cos_sq_alpha * ((pow(req, 2.) - pow(rpol, 2.)) / pow(rpol ,2.));
const double A = 1 + (usq / 16384) * (4096 + usq * (-768 + usq * (320 - 175 * usq)));
const double B = (usq / 1024) * (256 + usq * (-128 + usq * (74 - 47 * usq)));
const double delta_sig = B * sin_sigma * (cos2sigma + 0.25 * B * (cos_sigma * (-1 + 2 * pow(cos2sigma, 2.)) -
(1 / 6) * B * cos2sigma * (-3 + 4 * pow(sin_sigma, 2.)) *
(-3 + 4 * pow(cos2sigma, 2.))));
const double dis = rpol * A * (sigma - delta_sig);
const double azi1 = atan2((cos(u2) * sin(lam)), (cos(u1) * sin(u2) - sin(u1) * cos(u2) * cos(lam)));
return std::make_tuple(dis, azi1);
}
Unfortunately, the code is not enough fast for me because I work with very large datasets (around 1 million of locations with longitude and latitude coordinates). So, is it possible to speed up this C++ code in order to obtain an execution time of around 0.006 microseconds per function call. Any advice would be greatly appreciated. Thanks so much for your help. | {
"domain": "codereview.stackexchange",
"id": 44730,
"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++",
"url": null
} |
c++
Answer: Some Minor Points First
This looks very good, but there are a couple of trivial changes up front before we get into the real meat.
Do You Really Need Python Bindings?
You include the interface for Python support and then never use it. If this was just a roundabout way to include the math library,
Declare the Standard Headers You Use
Your math functions are in <cmath> or <math.h>. If you #include <math.h>, it just works. If you #include <cmath>, you should also, for maximum portability, import the specific functions you use:
using std::abs, std::atan, std::atan2, std::cos, std::pow, std::sin, std::sqrt;
Most actually-existing compilers let you skip this (although not using std::abs can cause a bug on some).
There is a Standard Way to Get π
You currently use M_PI, which is an extension many compilers add, but not part of the Standard Library. The official way to do it is:
#include <numbers>
constexpr double pi = std::numbers::pi_v<double>;
Avoid pow if Possible
One line in your program has an actual bug related to this:
constexpr double tol = pow(10., -12.); // iteration tolerance
On some compilers, including Clang 16.0.0, this will give you an error that pow is not a constexpr function. Change this to,
constexpr double tol = 1e-12; | {
"domain": "codereview.stackexchange",
"id": 44730,
"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++",
"url": null
} |
c++
Your other uses of pow are either squares or square roots, and would be more efficiently represented as multiplication or sqrt. However, LLVM compilers seem to be able to optimize these calls away.
Put a Decimal Point After Floating-Point Literals
It’s fine to write pi/180 or 1 - flat—up until you accidentally write 1/2, and the compiler gives you the int value 0. Code defensively and be consistent.
(Within reason. I sometimes write pi/2.)
Use constexpr and noexcept Where Appropriate
You will generate better code if you declare your functions constexpr. This tells the compiler that it can aggressively inline the function and fold constants.
Sometimes, you will get an error message saying that something your function does is not allowed because it's constexpr. This is usually, but not always, a statement that the compiler can’t optimize well inside a loop anyway.
So,
constexpr std::tuple<double, double> vinc(double latp, double latc, double longp, double longc) | {
"domain": "codereview.stackexchange",
"id": 44730,
"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++",
"url": null
} |
c++
Prefer a struct to std::tuple
You can give struct members meaningful names instead of trying to remember whether the first or second double in the std::tuple<double, double> is the distance. Also, if you have a couple of different types with the same layout, two different types of struct will have better type safety. (For example, coordinates in different systems.)
Refactor into Smaller Functions
This is more of a personal preference than an optimization, but you can make your code much easier to read, maintain and unit-test by decomposing it into small functions that each do one thing, and composing larger functions from those building-blocks.
Now, Actual Optimizations
Use a Good Compiler and Math Library
For example, Intel’s ICX for x86_64 has better math libraries than either GCC, Clang or MSVC, and can sometimes vectorize a loop that they cannot. In particular, the math libraries GCC and Clang use cannot (as of 2023) vectorize calls to trigonometric functions, but Intel’s can.
Use Appropriate Compiler Options
If you’re running on your own computer, tell the compiler that it’s allowed to use vector instructions! (On Clang, GCC or ICX, you want -march=native, to optimize for the same computer you’re compiling on, unless you are going to run the same binary on a different model of CPU.) By default, the compiler will assume you want the code to be able to run on the lowest common denominator.
You should also enable the version of the standard you want (such as -std=c++20) and turn on whole-program optimizations.
You want to enable all the useful warnings, and rewrite until you get none, unless you have a good reason to turn some warning off. (Disable warnings from system headers, of course.) I normally use -Wall -Wextra -Wpedantic -Wconversion -Wdeprecated.
You can sometimes improve performance with profile-guided optimization. Your compiler manual will tell you more.
Lay Out Your Data for Efficiency | {
"domain": "codereview.stackexchange",
"id": 44730,
"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++",
"url": null
} |
c++
Lay Out Your Data for Efficiency
To enable SIMD, you want your inputs and outputs arranged in arrays the same size (a structure-of-arrays). Here’s a wrapper function that calls yours on every element of the four input arrays, and writes them to the two output arrays.
#include <cassert>
#include <concepts>
#include <cstddef>
#include <ranges> | {
"domain": "codereview.stackexchange",
"id": 44730,
"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++",
"url": null
} |
c++
namespace ranges = std::ranges;
using std::size_t;
template<typename InputT, typename OutputT>
requires ranges::input_range<InputT> &&
ranges::range<OutputT> &&
std::same_as<ranges::range_value_t<InputT>, double> &&
std::same_as<ranges::range_value_t<OutputT>, double> &&
ranges::sized_range<InputT> &&
ranges::sized_range<OutputT> &&
ranges::random_access_range<InputT> &&
ranges::random_access_range<OutputT>
void vincs( OutputT& dists,
OutputT& azims,
const InputT& latps,
const InputT& longps,
const InputT& latcs,
const InputT& longcs ) noexcept
{
const size_t n = ranges::size(dists);
/* It is a logic error for the input and output arrays not to be the same size! */
assert( ranges::size(azims) == n &&
ranges::size(latps) == n &&
ranges::size(longps) == n &&
ranges::size(latcs) == n &&
ranges::size(longcs) == n );
for (size_t i = 0; i < n; ++i) {
const auto [dist, azim] = vinc( latps[i], latcs[i], longps[i], longcs[i] );
dists[i] = dist;
azims[i] = azim;
}
} | {
"domain": "codereview.stackexchange",
"id": 44730,
"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++",
"url": null
} |
c++
This sample code has some requires clauses that amount to, “The input and output types must behave like arrays of double.” You can pass it a double[1000], a std::vector<double>, a std::array<double>, a std::span, a std::ranges::subrange, a std::valarray, or so on. If you know what one type you actually need, you could make it a lot shorter.
Edit: In your post, you say your actual problem needs to work on pairs of geographic locations from the same array, meaning that you actually want to work on two slices of the same array, which you advance in a double loop, and write the results to a matrix.
Write Static Single Assignments
The way to speed up most scientific computations is to vectorize your loops. Fortunately, this one is “embarrassingly parallel”: each computation pf the ith outputs depends only on the ith inputs. That will let us use a lot of tricks.
Once you have the right data structures set up, getting the compiler to optimize well can get complicated. But here’s the best general, introductory advice I have.
The body of your loop should consist entirely of const or constexpr variable declarations, and one return statement. On the right-hand side of your assignments, call only built-in operators, ? expressions, and constexpr functions that follow the same restrictions themselves. All computations should depend only on a single element of each of your input arrays, constants, and loop indices if you are using them. As of 2023, compilers are very good at optimizing code that follows those rules. (I’ll give an example at the end.)
The part of the algorithm that doesn’t work for is the while loop where you re-run the computation until the difference is less than your error tolerance. I haven’t tested, but you might be able to get a speedup from running a fixed number of iterations instead. If the computation runs the same number of times for each element, the compiler might be able to run them in parallel.
Parallelize with OpenMP | {
"domain": "codereview.stackexchange",
"id": 44730,
"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++",
"url": null
} |
c++
Parallelize with OpenMP
The one line of code that will speed up your scientific computations the most is #pragma omp parallel for. (You might try adding simd.) This will have multiple threads execute your loop in parallel.
This loop is embarrassingly-parallel enough that the compiler doesn’t need any extra hints to be able to do it.
#include <cassert>
#include <concepts>
#include <cstddef>
#include <omp.h>
#include <ranges> | {
"domain": "codereview.stackexchange",
"id": 44730,
"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++",
"url": null
} |
c++
namespace ranges = std::ranges;
using std::size_t;
template<typename InputT, typename OutputT>
requires ranges::input_range<InputT> &&
ranges::range<OutputT> &&
std::same_as<ranges::range_value_t<InputT>, double> &&
std::same_as<ranges::range_value_t<OutputT>, double> &&
ranges::sized_range<InputT> &&
ranges::sized_range<OutputT> &&
ranges::random_access_range<InputT> &&
ranges::random_access_range<OutputT>
void vincs( OutputT& dists,
OutputT& azims,
const InputT& latps,
const InputT& longps,
const InputT& latcs,
const InputT& longcs ) noexcept
{
const size_t n = ranges::size(dists);
/* It is a logic error for the input and output arrays not to be the same size! */
assert( ranges::size(azims) == n &&
ranges::size(latps) == n &&
ranges::size(longps) == n &&
ranges::size(latcs) == n &&
ranges::size(longcs) == n );
# pragma omp parallel for schedule(static)
for (size_t i = 0; i < n; ++i) {
const auto [dist, azim] = vinc( latps[i], latcs[i], longps[i], longcs[i] );
dists[i] = dist;
azims[i] = azim;
}
}
There are two lines added to this version: #include <omp.h> and #pragma omp parallel for schedule(static) (which divides the input arrays into equal sections and assigns each section to a different thread). Most compilers also need a flag to enable OpenMP. For most compilers other than Microsoft’s, that’s -fopenmp.
Use an Alias for the Element Type
A comment by J.H. made me realize that you might consider changing the precision of the elements. This is much easier if you refer to it as something like elem_t and write, at the top of the file,
using elem_t = double; | {
"domain": "codereview.stackexchange",
"id": 44730,
"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++",
"url": null
} |
c++
You can now test changing it to another type, and back, in one place. The code below could operate on eight float values at once, if you don’t need double precision.
Putting it All Together
For demonstration purposes, I wrote an extremely dumbed-down version that only calculates spherical distance, with no correction for the eccentricity of the Earth. This code is untested and certainly will have at least one bug somewhere. I share it as a demonstration of what modern compilers can do.
#include <cassert>
#include <cmath>
#include <concepts>
#include <cstddef>
#include <numeric>
#include <omp.h>
#include <ranges>
namespace ranges = std::ranges;
using std::acos, std::cos, std::sin, std::size_t;
using elem_t = double;
struct coord_spherical {
elem_t r;
elem_t theta;
elem_t phi;
};
struct coord_cart3 {
elem_t x;
elem_t y;
elem_t z;
};
constexpr elem_t pi = std::numbers::pi_v<elem_t>;
constexpr elem_t r = 6378.0; // Equatorial radius of the Earth.
constexpr coord_spherical spherical_from_lat_long( const elem_t latitude,
const elem_t longitude
) noexcept
{
return coord_spherical{ r,
longitude*pi/180.0f,
pi/2 - latitude*pi/180.8f };
}
constexpr coord_cart3 unit_sphere_cart3(const coord_spherical sp) noexcept
{
const elem_t sin_phi = sin(sp.phi);
return coord_cart3{ cos(sp.theta)*sin_phi,
sin(sp.theta)*sin_phi,
cos(sp.phi) };
}
constexpr elem_t dot_product( const coord_cart3 u,
const coord_cart3 v
) noexcept
{
return u.x*v.x + u.y*v.y + u.z*v.z;
} | {
"domain": "codereview.stackexchange",
"id": 44730,
"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++",
"url": null
} |
c++
constexpr elem_t sphere_dist( const elem_t lat1,
const elem_t long1,
const elem_t lat2,
const elem_t long2
) noexcept
{
return r * acos(dot_product(
unit_sphere_cart3(spherical_from_lat_long(lat1, long1)),
unit_sphere_cart3(spherical_from_lat_long(lat2, long2))));
}
template<typename InputT, typename OutputT>
requires ranges::input_range<InputT> &&
ranges::range<OutputT> &&
std::same_as<ranges::range_value_t<InputT>, elem_t> &&
std::same_as<ranges::range_value_t<OutputT>, elem_t> &&
ranges::sized_range<InputT> &&
ranges::sized_range<OutputT> &&
ranges::random_access_range<InputT> &&
ranges::random_access_range<OutputT>
void sphere_dists( OutputT& dists,
const InputT& latps,
const InputT& longps,
const InputT& latcs,
const InputT& longcs
) noexcept
{
const size_t n = ranges::size(dists);
/* It is a logic error for the input and output arrays not to be the same size! */
assert( ranges::size(latps) == n &&
ranges::size(longps) == n &&
ranges::size(latcs) == n &&
ranges::size(longcs) == n );
# pragma omp parallel for simd schedule(static)
for (size_t i = 0; i < n; ++i) {
dists[i] = sphere_dist( latps[i], longps[i], latcs[i], longcs[i] );
}
}
using data_t = elem_t[1000];
extern const data_t latps, latcs, longps, longcs;
extern data_t dists;
int main()
{
sphere_dists( dists, latps, longps, latcs, longcs );
} | {
"domain": "codereview.stackexchange",
"id": 44730,
"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++",
"url": null
} |
c++
ICX 2022.2.1 with the flags -std=c++20 -march=x86-64-v3 -O3 -fp-model=fast -static -fiopenmp compiles the loop to this assembly code:
.LBB1_3: # =>This Inner Loop Header: Depth=1
mov r15, rsp
vbroadcastsd ymm12, qword ptr [rip + .LCPI1_0] # ymm12 = [1.7453292519943295E-2,1.7453292519943295E-2,1.7453292519943295E-2,1.7453292519943295E-2]
vmulpd ymm10, ymm12, ymmword ptr [rbx + 8*rsi + longps]
vmovupd ymm11, ymmword ptr [rbx + 8*rsi + latps]
vbroadcastsd ymm14, qword ptr [rip + .LCPI1_1] # ymm14 = [1.7376065561890447E-2,1.7376065561890447E-2,1.7376065561890447E-2,1.7376065561890447E-2]
vbroadcastsd ymm15, qword ptr [rip + .LCPI1_2] # ymm15 = [1.5707963267948966E+0,1.5707963267948966E+0,1.5707963267948966E+0,1.5707963267948966E+0]
vfnmadd132pd ymm11, ymm15, ymm14 # ymm11 = -(ymm11 * ymm14) + ymm15
vmovapd ymm0, ymm11
call rbp
vmovapd ymm8, ymm0
vmovapd ymm0, ymm10
call rdi
vmovapd ymm9, ymm0
vmovapd ymm0, ymm10
call rbp
vmovapd ymm10, ymm0
vmovapd ymm0, ymm11
call rdi
vmovapd ymm11, ymm0
vmulpd ymm12, ymm12, ymmword ptr [rbx + 8*rsi + longcs]
vmovupd ymm13, ymmword ptr [rbx + 8*rsi + latcs]
vfnmadd132pd ymm13, ymm15, ymm14 # ymm13 = -(ymm13 * ymm14) + ymm15
vmovapd ymm0, ymm13
call rbp
vmovapd ymm14, ymm0
vmovapd ymm0, ymm12
call rdi
vmovapd ymm15, ymm0
vmovapd ymm0, ymm12
call rbp
vmovapd ymm12, ymm0
vmovapd ymm0, ymm13
call rdi
vmulpd ymm1, ymm12, ymm10
vmulpd ymm2, ymm11, ymm0
vfmadd231pd ymm1, ymm9, ymm15 # ymm1 = (ymm9 * ymm15) + ymm1
vmulpd ymm0, ymm14, ymm8
vfmadd213pd ymm0, ymm1, ymm2 # ymm0 = (ymm1 * ymm0) + ymm2 | {
"domain": "codereview.stackexchange",
"id": 44730,
"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++",
"url": null
} |
c++
vfmadd213pd ymm0, ymm1, ymm2 # ymm0 = (ymm1 * ymm0) + ymm2
call qword ptr [rip + __svml_acos4_l9@GOTPCREL]
vbroadcastsd ymm1, qword ptr [rip + .LCPI1_3] # ymm1 = [6.378E+3,6.378E+3,6.378E+3,6.378E+3]
vmulpd ymm0, ymm0, ymm1
mov rsp, r15
vmovupd ymmword ptr [rbx + 8*rsi + dists], ymm0
add rsi, 4
cmp rsi, r12
jb .LBB1_3 | {
"domain": "codereview.stackexchange",
"id": 44730,
"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++",
"url": null
} |
c++
I’m not going to look at this in-depth, but the main thing to notice here is that all the operations are on ymm registers. That is, the compiler was able to auto-vectorize this version of the loop to use SIMD instructions on four packed doubles at once.
Edit: With the -fiopenmp flag, ICX 2022.2.1 is capable of both multithreading this code and using SIMD, at the same time.
You can try out this code on Godbolt.org and see what changing it around does. | {
"domain": "codereview.stackexchange",
"id": 44730,
"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++",
"url": null
} |
c++, multithreading, poco-libraries
Title: C++ Dynamic Balancer on a Threadpool
Question: I have a Balancer Class in my project which should dynamically increases/decreases the amount of Worker Thread based on the current amount of Messages which are written to an output queue.
For that i have created the following Classes:
Message.h
A message class thats deriving from the Poco::Notification Class because i'm also using the corresponding Poco::NotificationQueue.
class Message : public Poco::Notification {
public:
explicit Message(const std::string& id);
Message(const std::string& id, const std::string& content);
std::string content() const {
return content_;
}
std::string id() const {
return id_;
}
void content(const std::string& content) {
content_ = content;
}
void id(const std::string& id) {
id_ = id;
}
friend bool operator==(const Message& l_message, const Message& r_message);
friend bool operator!=(const Message& l_message, const Message& r_message);
private:
std::string id_;
std::string content_;
};
MessageQueue.h
The MessageQueue.h is just an interface for some queue implementation.
// MessageQueueImpl.h
class Message;
class MessageQueue {
public:
virtual void enqueue(std::unique_ptr<Message> message) = 0;
virtual std::unique_ptr<Message> dequeue() = 0;
virtual int size() const = 0;
virtual void close() = 0;
};
This is the concrete Implementation of that Interface:
class Message;
class MessageQueueImpl : public MessageQueue {
class MessageQueuePimpl;
public:
MessageQueueImpl();
virtual ~MessageQueueImpl();
void enqueue(std::unique_ptr<Message> message) override;
std::unique_ptr<Message> dequeue() override;
int size() const override;
void close() override;
private:
std::unique_ptr<MessageQueuePimpl> pimpl_;
};
// MessageQueueImpl.cpp | {
"domain": "codereview.stackexchange",
"id": 44731,
"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++, multithreading, poco-libraries",
"url": null
} |
c++, multithreading, poco-libraries
private:
std::unique_ptr<MessageQueuePimpl> pimpl_;
};
// MessageQueueImpl.cpp
class MessageQueueImpl::MessageQueuePimpl {
public:
void enqueue(std::unique_ptr<Message> message);
std::unique_ptr<Message> dequeue();
int size() const;
void close();
private:
Poco::NotificationQueue queue_;
};
void MessageQueueImpl::MessageQueuePimpl::enqueue(std::unique_ptr<Message> message) {
auto raw_message = message.release();
queue_.enqueueNotification(raw_message);
}
std::unique_ptr<Message> MessageQueueImpl::MessageQueuePimpl::dequeue() {
auto notification = queue_.waitDequeueNotification();
return std::unique_ptr<Message>(dynamic_cast<Message*>(notification));
}
int MessageQueueImpl::MessageQueuePimpl::size() const {
return queue_.size();
}
void MessageQueueImpl::MessageQueuePimpl::close() {
queue_.wakeUpAll();
}
MessageQueueImpl::MessageQueueImpl() : pimpl_(std::make_unique<MessageQueuePimpl>()) {
}
MessageQueueImpl::~MessageQueueImpl() = default;
void MessageQueueImpl::enqueue(std::unique_ptr<Message> message) {
pimpl_->enqueue(std::move(message));
}
std::unique_ptr<Message> MessageQueueImpl::dequeue() {
return pimpl_->dequeue();
}
int MessageQueueImpl::size() const {
return pimpl_->size();
}
void MessageQueueImpl::close() {
pimpl_->close();
}
Balancer.h
This class uses two of the above described MessageQueues. The first is the input queue and data is written from some other thread into that queue.
The idea is that the Balancer starts additional Threads if the size of the output queue is 3 times in a row greater then 5 times the current amount of running workerthreads.
If the current output queue size is 5 times in a row less then 5 times the current amount of running workerthreads then a thread is stopped.
Also the Balancer makes sure that at least 2 Workers are always running.
Here is the corresponding Code:
class Balancer {
class BalancerPimpl; | {
"domain": "codereview.stackexchange",
"id": 44731,
"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++, multithreading, poco-libraries",
"url": null
} |
c++, multithreading, poco-libraries
public:
Balancer(MessageQueue& input_queue, MessageQueue& output_queue, WorkerPtr worker_prototype);
~Balancer();
void run();
void start();
void stop();
int threadPoolSize() const;
int runningWorker() const;
size_t workerSize() const;
int increasingCounter() const;
int decreasingCounter() const;
private:
std::unique_ptr<BalancerPimpl> pimpl_;
};
// Balancer.cpp
class Balancer::BalancerPimpl {
public:
BalancerPimpl(MessageQueue& input_queue, MessageQueue& output_queue, WorkerPtr worker_prototype);
void run();
void start();
void stop();
int threadPoolSize() const;
int runningWorker() const;
size_t workerSize() const;
int increasingCounter() const;
int decreasingCounter() const;
private:
using WorkerList = std::vector<WorkerPtr>;
static const int LIMIT_MULTIPLIKATOR;
static const int INCREASING_LIMIT;
static const int DECREASING_LIMIT;
static const int THREADPOOL_MIN_CAPACITY;
void addWorker();
int outputQueueUpperLimit() const;
int outputQueueLowerLimit() const;
bool outputQueueAboveUpperLimit() const;
bool outputQueueBelowLowerLimit() const;
void adjustThreadPool();
void startNewThread();
void stopThread();
bool threadsAvailable();
MessageQueue& input_queue_;
MessageQueue& output_queue_;
WorkerPtr worker_prototype_;
Poco::ThreadPool balancer_pool_;
bool is_running_{ true };
WorkerList worker_list_;
int increasing_counter_{ 0 };
int decreasing_counter_{ 0 };
int message_count_from_input_queue_{ 0 };
int message_count_to_output_queue_{ 0 };
};
const int Balancer::BalancerPimpl::LIMIT_MULTIPLIKATOR{ 5 };
const int Balancer::BalancerPimpl::INCREASING_LIMIT{ 3 };
const int Balancer::BalancerPimpl::DECREASING_LIMIT{ 5 };
const int Balancer::BalancerPimpl::THREADPOOL_MIN_CAPACITY{ 2 }; | {
"domain": "codereview.stackexchange",
"id": 44731,
"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++, multithreading, poco-libraries",
"url": null
} |
c++, multithreading, poco-libraries
Balancer::BalancerPimpl::BalancerPimpl(MessageQueue& input_queue, MessageQueue& output_queue, WorkerPtr worker_prototype) : input_queue_{ input_queue }, output_queue_{ output_queue }, worker_prototype_{ std::move(worker_prototype) }, balancer_pool_{ THREADPOOL_MIN_CAPACITY, 16, 1 } {
for (int i = 0; i < balancer_pool_.capacity(); ++i) {
addWorker();
}
}
void Balancer::BalancerPimpl::run() {
while (is_running_) {
adjustThreadPool();
auto message = input_queue_.dequeue();
++message_count_from_input_queue_;
if (message) {
output_queue_.enqueue(std::move(message));
++message_count_to_output_queue_;
}
}
}
void Balancer::BalancerPimpl::start() {
for (int i = 0; i < THREADPOOL_MIN_CAPACITY; i++) {
worker_list_[i]->start();
balancer_pool_.start(*worker_list_[i]);
}
}
void Balancer::BalancerPimpl::stop() {
for (auto& worker : worker_list_) {
if (!worker->stopped()) {
worker->stop();
}
}
is_running_ = false;
output_queue_.close();
balancer_pool_.collect();
balancer_pool_.stopAll();
balancer_pool_.joinAll();
}
int Balancer::BalancerPimpl::runningWorker() const {
return std::count_if(worker_list_.begin(), worker_list_.end(), [](const WorkerPtr& worker) {
return !worker->stopped();
});
}
int Balancer::BalancerPimpl::threadPoolSize() const {
return balancer_pool_.capacity();
}
size_t Balancer::BalancerPimpl::workerSize() const {
return worker_list_.size();
}
int Balancer::BalancerPimpl::increasingCounter() const {
return increasing_counter_;
}
int Balancer::BalancerPimpl::decreasingCounter() const {
return decreasing_counter_;
}
void Balancer::BalancerPimpl::addWorker() {
auto worker_thread = WorkerPtr(worker_prototype_->clone());
worker_list_.push_back(std::move(worker_thread));
}
int Balancer::BalancerPimpl::outputQueueUpperLimit() const {
return runningWorker() * LIMIT_MULTIPLIKATOR;
} | {
"domain": "codereview.stackexchange",
"id": 44731,
"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++, multithreading, poco-libraries",
"url": null
} |
c++, multithreading, poco-libraries
int Balancer::BalancerPimpl::outputQueueLowerLimit() const {
return (runningWorker() - 1) * LIMIT_MULTIPLIKATOR;
}
bool Balancer::BalancerPimpl::outputQueueAboveUpperLimit() const {
return output_queue_.size() >= outputQueueUpperLimit();
}
bool Balancer::BalancerPimpl::outputQueueBelowLowerLimit() const {
return output_queue_.size() < outputQueueLowerLimit();
}
void Balancer::BalancerPimpl::adjustThreadPool() {
if (threadsAvailable() && outputQueueAboveUpperLimit()) {
++increasing_counter_;
if (increasing_counter_ == INCREASING_LIMIT) {
startNewThread();
increasing_counter_ = 0;
}
} else if (threadsAvailable() && increasing_counter_ > 0) {
--increasing_counter_;
}
if (runningWorker() > THREADPOOL_MIN_CAPACITY && outputQueueBelowLowerLimit()) {
++decreasing_counter_;
if (decreasing_counter_ == DECREASING_LIMIT) {
stopThread();
decreasing_counter_ = 0;
}
} else if (runningWorker() > THREADPOOL_MIN_CAPACITY && decreasing_counter_ > 0) {
--decreasing_counter_;
}
}
void Balancer::BalancerPimpl::startNewThread() {
auto stopped_thread = std::find_if(worker_list_.begin(), worker_list_.end(), [](const WorkerPtr& worker) {
return worker->stopped();
});
if (stopped_thread != worker_list_.end()) {
(*stopped_thread)->start();
balancer_pool_.start(**stopped_thread);
}
}
void Balancer::BalancerPimpl::stopThread() {
auto running_thread = std::find_if(worker_list_.rbegin(), worker_list_.rend(), [](const WorkerPtr& worker) {
return !worker->stopped();
});
(*running_thread)->stop();
}
bool Balancer::BalancerPimpl::threadsAvailable() {
return balancer_pool_.available() != 0;
}
Balancer::Balancer(MessageQueue& input_queue, MessageQueue& output_queue, WorkerPtr worker_prototype) : pimpl_{ std::make_unique<BalancerPimpl>(input_queue, output_queue, std::move(worker_prototype)) } {}
Balancer::~Balancer() {
stop();
}
void Balancer::run() {
pimpl_->run();
} | {
"domain": "codereview.stackexchange",
"id": 44731,
"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++, multithreading, poco-libraries",
"url": null
} |
c++, multithreading, poco-libraries
Balancer::~Balancer() {
stop();
}
void Balancer::run() {
pimpl_->run();
}
void Balancer::start() {
pimpl_->start();
}
void Balancer::stop() {
pimpl_->stop();
}
int Balancer::threadPoolSize() const {
return pimpl_->threadPoolSize();
}
int Balancer::runningWorker() const {
return pimpl_->runningWorker();
}
size_t Balancer::workerSize() const {
return pimpl_->workerSize();
}
int Balancer::increasingCounter() const {
return pimpl_->increasingCounter();
}
int Balancer::decreasingCounter() const {
return pimpl_->decreasingCounter();
}
Worker.hpp
The WorkerPtris just a smart pointer to the Worker Prototype. During the startup of the Balancer, 16 clones are created from that Prototype.
class CORE_EXPORT Worker : public Poco::Runnable {
public:
enum class State {
STARTING,
RUNNING,
STOPPING,
STOPPED
};
virtual ~Worker() = default;
Worker() = default;
Worker(const Worker& other) {}
void start();
void run() override;
Worker* clone();
void stop();
bool stopped();
State state() const;
private:
virtual void startImpl() = 0;
virtual void runImpl() = 0;
virtual Worker* cloneImpl() = 0;
virtual void stopImpl() = 0;
State state_{ State::STOPPED };
};
using WorkerPtr = std::unique_ptr<Worker>;
The Code it self works when i run it. But from the testing point of view i have some issues to really test that code. I often had to wait a specific amount of time in the test and often on one day the tests succeed on the other they fail because the amount of time is to short.
I already thought about extracting the handling of the threadpool (starting/stopping threads) into it's own class and add them in the kind of a strategy to the Balancer.
But i'm not quite sure what would be the best. So i'm open for any suggestions. | {
"domain": "codereview.stackexchange",
"id": 44731,
"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++, multithreading, poco-libraries",
"url": null
} |
c++, multithreading, poco-libraries
Answer: This is not helpful
Perhaps you have the idea that a thread is consuming resources, so it is better to not have more running than necessary. While each thread uses some memory (mainly because each thread needs its own stack), if a thread is blocked in a waitDequeueNotification() call, it doesn't consume CPU resources. So no performance is lost if you have a bunch of extra threads that are just blocked all the time. However, you are losing performance by adding/removing threads on demand, and having the Balancer shuffle messages from the input_queue_ to the output_queue_. So this means it is a net loss to use your balancer.
If you are not going to balance, the question is then how big should the thread pool be? Assuming the work each thread has to do is CPU-bound, then using as many threads as there are logical CPU cores is usually best. You could use Poco::Environment::processorCount() for this, or just std::thread::hardware_concurrency() from the standard library.
If it's not CPU-bound, but for example memory bound or disk I/O bound, then throwing more threads at the problem might not help at all. If that is so, also consider the case where messages come in faster than the threads can process them. The output queue will grow in size, you add more threads but it doesn't help, and the output queue will grow even further, and you add even more threads, and so on. At some point adding more threads will even make things worse. | {
"domain": "codereview.stackexchange",
"id": 44731,
"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++, multithreading, poco-libraries",
"url": null
} |
c++, multithreading, poco-libraries
Finally, your balancer also assumes the messages come in at a regular pace. However, what if they come in batches, like 100 messages at once, then nothing for a second. Your balancer will then increase the number of threads a lot, then after the first batch it doesn't get any messages for a second, so adjustThreadPool() is also not called during that second. Then when the first DECREASING_LIMIT messages arrives of the next batch, it will decrease the size of the thread pool, even though it will need to increase the size later in the batch. So your balancer is behaving badly for irregularly spaces messages.
Both Impl and Pimpl?
I think it's overkill to have an abstract base class and a pointer-to-implementation in the derived class. Since the derived class can already be easily hidden, there is no need to use the pimpl idiom as well. The extra indirection will hurt performance.
You can make a free function createMessageQueueImpl() that returns a pointer to a MessageQueue. So in a header file you would just have:
std::unique_ptr<MessageQueue> createMessageQueueImpl(); | {
"domain": "codereview.stackexchange",
"id": 44731,
"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++, multithreading, poco-libraries",
"url": null
} |
c++, multithreading, poco-libraries
And then in a source file, you can have both the definition of class MessageQueueImpl and the aforementioned function:
class MessageQueueImpl: public MessageQueue {
public:
void enqueue(std::unique_ptr<Message> message) override;
std::unique_ptr<Message> dequeue() override;
int size() const override;
void close();
private:
Poco::NotificationQueue queue_;
};
std::unique_ptr<MessageQueue> createMessageQueueImpl() {
return std::make_unique<MessageQueueImpl>();
}
Avoid unnecessary public members
Your Balancer exposes several public member functions which I think should be made private, or possibly even removed completely. For example, why are increasingCounter() and decreasingCounter() public members? Calling this will just interfere with the balancers own counting. Why would you want a caller to be able to get the size of the pool or the number of running workers? Maybe you used this for debugging purposes, but I don't see a use for this in production code.
Why are there both run() and start()? What happens if someone calls run() before every having called start(), and then just one message is sent to the queue. Since no threads are running, this message will never be processed. This also brings me to:
Thread safety issues
run() never terminates on its own, so it looks like stop() has to be called from another thread. That means you will have race conditions because there is no mutex protecting is_running_ and other member variables. For example, run() could just have finished executing:
while (is_running_) {
When is_running_ was still true. Then another thread calls stop() which runs in its entirety, and then the thread running run() continues with the body of the while-statement. This will make it call input_queue_.dequeue(), but what if no more messages are being received at this point? The thread will hang indefinitely. | {
"domain": "codereview.stackexchange",
"id": 44731,
"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++, multithreading, poco-libraries",
"url": null
} |
javascript, typescript, vue.js
Title: Movies App with Vue 3 and TypeScript
Question: I have made a Movies App with Vue 3, TypeScript and The Movie Database (TMDB) API. For aesthetics, I rely on Bootstrap 5.
In src\App.vue I have:
<template>
<TopBar />
<router-view />
<AppFooter />
</template>
<script lang="ts">
import { defineComponent } from 'vue';
// Import components
import TopBar from './components/TopBar.vue';
import AppFooter from './components/AppFooter.vue';
export default defineComponent({
// Register components
components: {
TopBar,
AppFooter
}
});
</script>
<style lang="scss">
.app-logo {
max-height: 25px;
width: auto;
}
// Layout
#app {
min-height: 100vh;
height: auto;
display: flex;
flex-direction: column;
}
</style> | {
"domain": "codereview.stackexchange",
"id": 44732,
"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, vue.js",
"url": null
} |
javascript, typescript, vue.js
The Navbar (src\components\TopBar.vue):
<template>
<nav class="navbar sticky-top navbar-expand-md shadow-sm">
<div class="container-fluid">
<router-link class="navbar-brand" to="/">
<img src="../assets/logo.png" class="app-logo" alt="App Logo">
</router-link>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#mainNavigation" aria-controls="mainNavigation" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="mainNavigation">
<ul class="navbar-nav pe-md-1 navbar-expand-md">
<li class="nav-item">
<router-link class="nav-link" :class="$route.name == 'home' ? 'active':''" to="/">Now Playing</router-link>
</li>
<li class="nav-item">
<router-link class="nav-link" :class="$route.name == 'top_rated' ? 'active':''" to="/top-rated">Top Rated</router-link>
</li>
</ul>
<form ref="searchForm" class="search_form w-100 mx-auto mt-2 mt-md-0">
<div class="input-group">
<input v-on:keyup="debounceMovieSearch" v-model="searchTerm" class="form-control search-box" type="text" placeholder="Search movies...">
<div class="input-group-append">
<button class="btn" type="button">
<font-awesome-icon :icon="['fas', 'search']" />
</button>
</div>
</div>
<div v-if="isSearch" @click="isSearch = false" class="search-results shadow-sm">
<div v-if="this.movies.length">
<router-link v-for="movie in movies.slice(0, 10)" :key="movie.id" :to="`/movie/${movie.id}`">
<SearchItem :movie="movie" />
</router-link>
</div> | {
"domain": "codereview.stackexchange",
"id": 44732,
"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, vue.js",
"url": null
} |
javascript, typescript, vue.js
<div v-else>
<p class="m-0 p-2 text-center">No movies found for this search</p>
</div>
</div>
</form>
</div>
</div>
</nav>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue';
import axios from 'axios';
import env from '../env';
import SearchItem from './SearchItem.vue';
export default defineComponent({
name: 'TopBar',
components: {SearchItem},
data: () => ({
searchForm: ref(null),
isSearch: false,
searchTerm: '',
timeOutInterval: 1000,
movies: []
}),
mounted() {
this.windowEvents();
},
methods: {
windowEvents() {
// Check for click outside the search form
window.addEventListener('click', (event) => {
if (!(this.$refs.searchForm as HTMLFormElement).contains(event.target as Node|null)) {
this.isSearch = false;
}
});
},
debounceMovieSearch() {
setTimeout(this.doMovieSearch, this.timeOutInterval)
},
doMovieSearch() {
if (this.searchTerm.length > 2) {
this.isSearch = true;
axios.get(`${env.api_url}/search/movie?api_key=${env.api_key}&query=${this.searchTerm}`).then(response => {
this.movies = response.data.results;
})
.catch(err => console.log(err));
}
},
}
});
</script>
In the views directory I have the HomeView.vue that displays a list of movies, via the MoviesList.vue component.
In HomeView.vue:
<template>
<div class="container">
<h1 class="page-title">{{ pageTitle }}</h1>
<MoviesList listType="now_playing" />
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import MoviesList from '../components/MoviesList.vue';
export default defineComponent({
name: 'HomeView',
components: {
MoviesList
}, | {
"domain": "codereview.stackexchange",
"id": 44732,
"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, vue.js",
"url": null
} |
javascript, typescript, vue.js
export default defineComponent({
name: 'HomeView',
components: {
MoviesList
},
data: () => ({
pageTitle: "Now Playing"
})
});
</script>
In MoviesList.vue:
<template>
<div class="row list">
<div
v-for="movie in movies"
:key="movie.id"
class="col-xs-12 col-sm-6 col-lg-4 col-xl-3"
>
<MovieCard :movie="movie" :genres="genres" :showRating="true" />
</div>
</div>
</template>
<script lang="ts">
import { defineComponent } from "vue";
import axios from "axios";
import env from "../env";
import MovieCard from "./MovieCard.vue";
export default defineComponent({
name: "MoviesList",
components: { MovieCard },
props: {
listType: {
type: String,
required: true,
},
},
data: () => ({
searchTerm: "",
movies: [],
genres: [],
}),
mounted() {
this.listMovies();
this.getGenres();
},
methods: {
listMovies() {
axios
.get(
`${env.api_url}/movie/${this.$props.listType}?api_key=${env.api_key}`
)
.then((response) => {
this.movies = response.data.results;
})
.catch((err) => console.log(err));
},
getGenres() {
axios
.get(`${env.api_url}/genre/movie/list?api_key=${env.api_key}`)
.then((response) => {
this.genres = response.data.genres;
})
.catch((err) => console.log(err));
},
},
});
</script>
<style scoped lang="scss">
[class*="col-"] {
display: flex;
flex-direction: column;
margin-bottom: 30px;
}
</style>
The above component is reusable. I use it in the Top Rated Movies view, by providing a different value (from the one used on the Homepage view) for the listType prop:
<template>
<div class="container">
<h1 class="page-title">{{ pageTitle }}</h1>
<MoviesList listType="top_rated" />
</div>
</template> | {
"domain": "codereview.stackexchange",
"id": 44732,
"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, vue.js",
"url": null
} |
javascript, typescript, vue.js
<script lang="ts">
import { defineComponent } from "vue";
import MoviesList from "../components/MoviesList.vue";
export default defineComponent({
name: "TopRatedMoviesView",
components: {
MoviesList,
},
data: () => ({
pageTitle: "Top Rated",
})
});
</script>
In src\components\MovieCard.vue I have:
<template>
<div class="movie card" @click="showDetails(movie.id)">
<div class="thumbnail">
<img
:src="movieCardImage"
:alt="movie.title"
class="img-fluid"
/>
</div>
<div class="card-content">
<h2 class="card-title">{{ movie.title }}</h2>
<p class="card-desc">{{ movie.overview }}</p>
<span v-if="showRating" :title="`Score: ${movie.vote_average}`" class="score">{{ movie.vote_average}}</span>
</div>
<div class="card-footer">
<p class="m-0 release">
Release date: {{ dateTime(movie.release_date) }}
</p>
<p v-if="movieGenres" class="m-0 pt-1">
<span class="genre" v-for="genre in movieGenres" :key="genre.id">
{{ genre.name }}
</span>
</p>
</div>
</div>
</template>
<script lang="ts">
import { defineComponent } from "vue";
import moment from "moment";
export default defineComponent({
name: "MovieCard",
props: {
movie: {
type: Object,
required: true,
},
genres: {
type: Object,
required: false,
},
showRating: {
type: Boolean,
default: false,
}
},
data: () => ({
genericCardImage: require("../assets/generic-card-image.png"),
}),
methods: {
dateTime(value: any) {
return moment(value).format("MMMM DD, YYYY");
},
showDetails(movie_id: any) {
let movie_url = `/movie/${movie_id}`;
window.open(movie_url, "_self");
},
},
computed: {
movieCardImage() {
return !this.movie?.backdrop_path
? this.genericCardImage
: `https://image.tmdb.org/t/p/w500/${this.movie?.backdrop_path}`;
}, | {
"domain": "codereview.stackexchange",
"id": 44732,
"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, vue.js",
"url": null
} |
javascript, typescript, vue.js
movieGenres() {
if (this.genres) {
let genres = this.genres;
return this.movie?.genre_ids
.filter((genre_id: number) => genre_id in genres)
.map((genre_id: number) => genres[genre_id])
.filter((genre: { name: string }) => genre.name.length > 0);
} else {
return [];
}
},
},
});
</script>
The app is significantly bigger: there is a Movie details view and an Actor details view, but instead of pasting it all here, I have put together Stackblitz.
Questions
Is there any code redundancy (and ways to reduce it)?
Do you see any bad practices?
Any suggestions for code optimization, modularization and reusability?
Answer: This is feedback from me.
You can create a directive named composite for outside click.
In the movieCard component => you can replace template logic with computed properties. like for the date dateTime(movie.release_date)
Regarding typescript, don't overuse any. movie_id type is defined. It may be a string or number.
In actorDetails, you used useRoute, use is a composable mostly used with composition API. In option API it is better to use this.$route directly.
For reusability, you can use mixin which will handle all the API requests. You can figure out how it can be implemented.
It can be a little awkward but if you use BaseCard with a name for actor and movie.
You can register Axios as a global variable like $api or $axios.
Lastly, I think you need to move from Vue CLI to Vite. Use composition API instead of an option. It gives a lot of flexibility and reusability. Use tailwind (optional). | {
"domain": "codereview.stackexchange",
"id": 44732,
"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, vue.js",
"url": null
} |
c++, file-system
Title: Reading all bytes from a file
Question: I'm basically trying to write a helper function that reads a whole file and returns the data and the number of bytes read.
Can you tell me if is correctly written and used?
#include <iostream>
static char * ReadAllBytes(const char * filename, int * read)
{
ifstream ifs(filename, ios::binary|ios::ate);
ifstream::pos_type pos = ifs.tellg();
int length = pos;
char *pChars = new char[length];
ifs.seekg(0, ios::beg);
ifs.read(pChars, length);
ifs.close();
*read = length;
return pChars;
}
int _tmain(int argc, _TCHAR* argv[])
{
const char * filename = "polar00.map";
int read ;
char * pChars = ReadAllBytes(filename, &read);
delete[] pChars;
return 0;
}
Answer: A few things I would do differently:
static char * ReadAllBytes(const char * filename, int * read)
{
ifstream ifs(filename, ios::binary|ios::ate);
ifstream::pos_type pos = ifs.tellg();
// What happens if the OS supports really big files.
// It may be larger than 32 bits?
// This will silently truncate the value/
int length = pos;
// Manuall memory management.
// Not a good idea use a container/.
char *pChars = new char[length];
ifs.seekg(0, ios::beg);
ifs.read(pChars, length);
// No need to manually close.
// When the stream goes out of scope it will close the file
// automatically. Unless you are checking the close for errors
// let the destructor do it.
ifs.close();
*read = length;
return pChars;
}
How I would do it:
static std::vector<char> ReadAllBytes(char const* filename)
{
std::ifstream ifs(filename, std::ios::binary|std::ios::ate);
std::ifstream::pos_type pos = ifs.tellg();
if (pos == 0) {
return std::vector<char>{};
}
std::vector<char> result(pos);
ifs.seekg(0, std::ios::beg);
ifs.read(&result[0], pos);
return result;
}
Note:
static std::vector<char> ReadAllBytes(char const* filename) | {
"domain": "codereview.stackexchange",
"id": 44733,
"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++, file-system",
"url": null
} |
c++, file-system
return result;
}
Note:
static std::vector<char> ReadAllBytes(char const* filename)
It may seem like an expensive copy operation. But in reality NRVO will make this an in-place operation so no copy will take place (just make sure you turn on optimizations). Alternatively pass it as a parameter:
static void ReadAllBytes(char const* filename, std::vector<char>& result) | {
"domain": "codereview.stackexchange",
"id": 44733,
"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++, file-system",
"url": null
} |
python, beginner, random
Title: Python \ random password generation code
Question: I have written a python program for random password generation and as a newbie I would like my code to be reviewed by professionals and if they have any suggestions to improve it.
import string
import random
letters = string.ascii_letters
digits = string.digits
special_chars = string.punctuation
letters_list = list(letters)
digits_list = list(digits)
special_list = list(special_chars)
many_letter = int(input(f"how many letter ? \n"))
many_digit = int(input(f"how many digits ? \n"))
many_special = int(input(f"how many special chars ? \n"))
#...................................................
password = []
finalpassword = []
counter_l = 0
for l in letters_list :
password.append(random.choice(letters_list))
counter_l += 1
if counter_l == many_letter :
break
counter_d = 0
for d in digits_list :
password.append(random.choice(digits_list))
counter_d += 1
if counter_d == many_digit :
break
counter_s = 0
for s in special_list :
password.append(random.choice(special_list))
counter_s += 1
if counter_s == many_special :
break
p_counter = 0
for p in password :
finalpassword.append(random.choice(password))
p_counter += 1
if p_counter == len(password) :
break
print("".join(finalpassword))
Answer: Don't use random for security
Quoting from the documentation for random:
Warning: The pseudo-random generators of this module should not be used for security purposes. For security or cryptographic uses, see the secrets module. | {
"domain": "codereview.stackexchange",
"id": 44734,
"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, random",
"url": null
} |
python, beginner, random
The pseudo-random number generator implemented by random doesn't provide a truly random output and provides a predictable output, and as such isn't suited for password generation.
The secrets module works similarly to random, but is cryptographically secure.
Bugs
There are multiple bugs in your code caused by improper logic.
Wrong number of characters
I tried generating a password with 1 letter, 5 digits and 1 special character and got 2$32$23: no letter and 2 special characters. Another try gave 54j5614: no special character and 6 digits.
This happens because you first generate an alphabet with the expected number of each character type, then generate the final password by sampling repeatedly that alphabet, instead of generating the final password directly.
Improper loop handling
I tried generating a password with 0 letter, 1 digit and 1 special char and got: tNpoQQ7XQtxcortvERSypXphvNNcWxryttrpfpMyhhfoXpBoBcBBxP. Besides another occurrence of the previous bug (no special char), there are obviously too many letters.
Then I tried 1 letter, 1000 digits and 1 special char and got: |87b07bb17|9. Now, that's way too few digits, or characters overall. Besides the first bug, I expected a 1002-character-long password.
This happens because of the way you handle loops, mixing for loops and manually handling a loop counter.
The first bug is caused because you increment the counter before checking its value, meaning that by the time you check if counter_l == many_letter, counter_l is greater than 0.
The second bug comes from the fact that when you loop over a collection (for d in digits_list:), the code will break out of the loop before the counter reaches the specified amount.
The proper way to execute a loop exactly n times is:
for _ in range(n):
# do stuff | {
"domain": "codereview.stackexchange",
"id": 44734,
"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, random",
"url": null
} |
python, beginner, random
Shorter code, no counter needed. The _ in the above snippet is a valid variable name, and could be anything else, but is usually used in Python to indicate a throwaway variable, one which you don't use the value.
Best practices
Read the documentation for secrets, you will find example code for password generation in the "Recipes and best practices" section.
Try to understand how these simple examples work and why this approach works best, and to adapt them to your specifications.
Other remarks
Index directly into strings
There is no need to convert strings to list to be able to index individual characters. In Python, you can directly index into strings:
>>> 'abcd'[2]
'c'
Unnecessary f-strings
You use f-strings for the input prompts, but don't use string interpolation. These should be simplified to regular strings. | {
"domain": "codereview.stackexchange",
"id": 44734,
"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, random",
"url": null
} |
python, python-3.x, random, console
Title: Python command-line program that generates passwords
Question: I took my code from this answer by me, I found it useful, so I developed it further, and here is the result.
This script generates cryptographically secure passwords. The characters used by the passwords are chosen from the 94 printable ASCII characters that aren't blank characters or control characters.
The characters are split into 4 categories: 26 lowercase letters, 26 UPPERCASE letters, 10 digits and 32 punctuations. Each password must contain UPPERCASE letters, lowercase letters, and digits, with optional punctuations.
The length of the passwords is 8 to 94 inclusive if special characters are allowed, or 8 to 62 if they aren't. The passwords can contain unique characters only and also duplicates, whether passwords will contain duplicate characters is controlled by an optional argument. And the count of characters from each of the categories in the passwords are approximately the same.
Code
import random
import secrets
from functools import reduce
from operator import iconcat
from string import ascii_lowercase, ascii_uppercase, digits, punctuation
from typing import Generator, List
CHARSETS = (
(ascii_lowercase, ascii_uppercase, digits),
(ascii_lowercase, ascii_uppercase, punctuation, digits)
)
COUNTS = (
((3, 36), (2, 10)),
((4, 68), (3, 42), (2, 10))
)
def choose_charset(charset: str, number: int, unique: bool = False) -> List[str]:
if not unique:
return [secrets.choice(charset) for _ in range(number)]
charset = list(charset)
choices = []
for _ in range(number):
choice = secrets.choice(charset)
choices.append(choice)
charset.remove(choice)
return choices | {
"domain": "codereview.stackexchange",
"id": 44735,
"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, random, console",
"url": null
} |
python, python-3.x, random, console
return choices
def split(number: int, symbol: bool = False) -> Generator[int, None, None]:
for a, b in COUNTS[symbol]:
n = max(
2 + secrets.randbelow(
number // a - 1
), number - b
)
number -= n
yield n
if number > 10:
raise ValueError('remaining number is too big')
yield number
def generate_password(length: int, unique: bool = False, symbol: bool = True) -> str:
if not 8 <= length <= (62, 94)[symbol]:
raise ValueError(
'argument `length` should be an `int` between 8 and 94, or between 8 and 62 if symbols are not allowed')
password = reduce(
iconcat,
map(
choose_charset, CHARSETS[symbol],
split(length, symbol), [unique]*4
),
[]
)
random.shuffle(password)
return ''.join(password) | {
"domain": "codereview.stackexchange",
"id": 44735,
"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, random, console",
"url": null
} |
python, python-3.x, random, console
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(
prog='Password_Generator',
description='This program generates cryptographically secure passwords.'
)
parser.add_argument(
'length', type=int,
help='length of the passwords to be generated'
)
unique_parser = parser.add_mutually_exclusive_group(required=False)
unique_parser.add_argument(
'-U', '--unique', dest='unique', action='store_true',
help='specifies passwords should contain unique characters only'
)
unique_parser.add_argument(
'-NU', '--no-unique', dest='unique', action='store_false',
help='specifies passwords should not contain unique characters only'
)
parser.set_defaults(unique=False)
symbol_parser = parser.add_mutually_exclusive_group(required=False)
symbol_parser.add_argument(
'-S', '--symbol', dest='symbol', action='store_true',
help='specifies passwords should contain special characters'
)
symbol_parser.add_argument(
'-NS', '--no-symbol', dest='symbol', action='store_false',
help='specifies passwords should not contain special characters'
)
parser.set_defaults(symbol=True)
parser.add_argument(
'-C', '--count', type=int, default=1,
help='specifies the number of passwords to generate, default 1'
)
namespace = parser.parse_args()
length, unique, symbol, count = [
getattr(namespace, name) for name in ('length', 'unique', 'symbol', 'count')]
for _ in range(count):
print(generate_password(length, unique, symbol))
Help message
PS C:\Users\Xeni> D:\MyScript\password_generator.py -h
usage: Password_Generator [-h] [-U | -NU] [-S | -NS] [-C COUNT] length
This program generates cryptographically secure passwords.
positional arguments:
length length of the passwords to be generated | {
"domain": "codereview.stackexchange",
"id": 44735,
"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, random, console",
"url": null
} |
python, python-3.x, random, console
positional arguments:
length length of the passwords to be generated
options:
-h, --help show this help message and exit
-U, --unique specifies passwords should contain unique characters only
-NU, --no-unique specifies passwords should not contain unique characters only
-S, --symbol specifies passwords should contain special characters
-NS, --no-symbol specifies passwords should not contain special characters
-C COUNT, --count COUNT
specifies the number of passwords to generate, default 1
Example usage
PS C:\Users\Xeni> D:\MyScript\password_generator.py 16 -C 8
1o71NV8{rt*.3l4W
L533*8X1m$9`!w6R
9#0<W4~ZuK#"51Vd
V9y93Y^2B34Go71/
50]9o1]E1&ap6HU#
~42pL"46T'7633zd
6Zw1a9z"F16H7~3Z
2Ab7S<r82o7_KN49
PS C:\Users\Xeni> D:\MyScript\password_generator.py 16 -U -C 8
xt7)kG48O9KW\^0]
Pz02ac51>8_UY43g
6[kYF?0H98Oq3'21
Fp50N>P47n+369A1
9v743R0%V5\2s186
Dbr1%\0a}486TQF;
K?l1Cz;92Wn7|Z54
1a@7]4yBsCx52Y0G
PS C:\Users\Xeni> D:\MyScript\password_generator.py 16 -U -NS -C 8
c0YgQ9C54k86Ff3m
Dwd3W412059ujm8H
17pWJvhyC9b82460
Qs52409Az673R18Z
89R2Pk6z401nN73H
7gDcO30yxG54d86K
i62s1kQC89IuBb45
iw02Zn96Ez1xQY8N
As the program became sufficiently complex I wanted it to be reviewed, in particular this is the first time I have ever used argparse. I would like my code to be more concise and efficient. | {
"domain": "codereview.stackexchange",
"id": 44735,
"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, random, console",
"url": null
} |
python, python-3.x, random, console
Answer: Put all code in functions. Code in functions can be tested, experimented
with, and reorganized much more easily than code floating around at the top
level. Floating code introduces the temptation to rely on global variables,
which can create substantial headaches even at moderate program sizes. Putting
everything in functions forces you to think clearly about how the behavior and
data flow is organized. It's a time-tested practice worth embracing.
Invest a lot more energy in code clarity and readability. I started
experimenting with this code expecting to write a typical review suggesting
improvements on various details, but I was quickly overwhelmed by the
complexity and opacity of the code. A few examples. (1) What is COUNTS? The
constant name is generic, there are no comments to provide clues, the data
structure is is almost (but not quite) parallel to CHARSETS, and the numbers
themselves are not evidently self-explanatory. (2) What is the split()
function's purpose and behavior? Again, the name is generic and a bit puzzling
(what is being split?). There are no docstrings or comments explaining the
intent. Its logic is driven by the mystery numbers in COUNTS, using
completely abstract variable names of a and b. After experimenting with the
code, I get the sense that the job of split() is to determine how many of
each category of characters (lower, upper, digits, punctation) we will select
to build a password, but nothing in the code aids me in reaching that
determination. I had to figure that out via experimentation, printing, and
close reading. (3) What is choose_charset()? Are we really choosing a
character set, meaning selecting among the CHARSETS data? It doesn't look
like that. Is number in this function the same as number in split()? And
how do those generic concepts compare to password length? The naming scheme is
both generic and seemingly inconsistent. (4) The algorithm in | {
"domain": "codereview.stackexchange",
"id": 44735,
"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, random, console",
"url": null
} |
python, python-3.x, random, console
both generic and seemingly inconsistent. (4) The algorithm in
generate_password() is a head-scratcher. I would confidently wager than less
than 1 in 1000 experienced Python programmers have ever used iconcat -- which
doesn't necessarily make it a bad thing to use, but it does convey the terrain
you're walking on. After a fair bit of study, I managed to figure out what
it's doing, but you are really making your reader work hard! Consider the
following comparison. Even without improving the rest of the code's naming and
readability, we can clarify password generation a lot just by doing the normal
Python thing rather than by doing something super-clever.
# Original code: reduce, iconcat?!?, map, choose_charset -- huh?
password = reduce(
iconcat,
map(
choose_charset, CHARSETS[symbol],
split(length, symbol), [unique]*4
),
[]
) | {
"domain": "codereview.stackexchange",
"id": 44735,
"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, random, console",
"url": null
} |
python, python-3.x, random, console
# Revised code: ok, there is a tuple of "splits" (not sure what that means,
# but it's the same size as CHARSETS, so I sort of see the connection). Oh,
# and then we just build the password from the characters coming out of
# choose_charset(). I sort of get it now.
splits = tuple(split(length, symbol))
password = [
char
for charset, s in zip(CHARSETS[symbol], splits)
for char in choose_charset(charset, s, unique)
]
Does the code work correctly? When I see this kind of complexity, my
suspicions are raised. How do I know the code is doing the right thing? I
decided to do some quick analysis. Thanks to your good decision to use a
command-line argument parser, I quickly added a new behavior to be triggered by
--analysis. It takes a bunch of passwords and counts up how often each
category of characters is observed. Here's the new function, and a sketch of
how I wove it into the existing code.
import sys
from collections import Counter
def main(args):
parser = argparse.ArgumentParser(...)
...
opts = parser.parse_args(args)
...
if opts.analysis:
passwords = [
generate_password(opts.length, opts.unique, opts.symbol)
for _ in range(count)
]
analyze_passwords(opts, passwords)
else:
...
def analyze_passwords(opts, passwords):
csets = dict(
lower = ascii_lowercase,
upper = ascii_uppercase,
punct = punctuation,
digit = digits,
)
c = Counter(
next(name for name, chars in csets.items() if c in chars)
for p in passwords
for c in p
)
for k in csets:
print(k, round(c[k] / opts.count, 3))
if __name__ == '__main__':
main(sys.argv[1:]) | {
"domain": "codereview.stackexchange",
"id": 44735,
"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, random, console",
"url": null
} |
python, python-3.x, random, console
if __name__ == '__main__':
main(sys.argv[1:])
I ran the analysis across various password lengths (8, 16, 35, 70), with and
without --unique. The results suggest that you might want to reconsider your
approach. As password length increases, digits and especially punctuation
become over-represented, while lowercase letters are
under-represented. Also, it seems that digits are always being
selected in unique mode (or otherwise somehow capped at 10
appearances), even when the user did not specify that option on the
command line.
Category | 8 | 16 | 35 | 70 # Non-unique.
----------------------------------------
lower | 2.0 | 3.0 | 5.006 | 9.548
upper | 2.0 | 2.983 | 5.869 | 18.794
punct | 2.0 | 3.386 | 14.127 | 31.658
digit | 2.0 | 6.632 | 9.998 | 10.0
Category | 8 | 16 | 35 | 70 # Unique.
-----------------------------------------
lower | 2.0 | 2.997 | 5.007 | 9.559
upper | 2.0 | 3.0 | 5.857 | 18.77
punct | 2.0 | 3.398 | 14.138 | 31.672
digit | 2.0 | 6.606 | 9.998 | 10.0
A key in the fight against complexity: well-focused data objects. After
thinking about your program a while I decided to abandon any effort at
line-by-line or even function-by-function advice. I would suggest a complete
rethink. Rather than improving the split() function, for example, I would
suggest that you figure out a way not to need it at all. One way to start is by
creating a data object to represent a CharacterSet and the behaviors that
could be tied to it when generating passwords. Such an object should know its
universe of characters (lower, upper, digits, punctuation). It should know how
to randomly emit another character, subject to any unique constraint. And it
should know whether the next request to get another character will fail due to
that constraint.
class CharacterSet: | {
"domain": "codereview.stackexchange",
"id": 44735,
"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, random, console",
"url": null
} |
python, python-3.x, random, console
def __init__(self, chars, unique = False):
self.chars = chars
self.unique = bool(unique)
self.remaining = list(chars)
random.shuffle(self.remaining)
def next_char(self):
if self.unique:
# Because we shuffled, we can just pop from the end.
return self.remaining.pop()
else:
return secrets.choice(self.chars)
@property
def is_empty(self):
return self.unique and not self.remaining
With that very simple data-object in place, the code to generate a single
password in a way that respects the unique constraint and (as much as possible)
selects evenly from the different character categories might look like
the following:
from itertools import cycle
def create_password(length, unique = False, include_punct = False):
# Create the CharacterSet instances.
categories = (ascii_lowercase, ascii_uppercase, digits, punctuation)
csets = [
CharacterSet(chars, unique)
for chars in categories
]
if not include_punct:
csets.pop()
random.shuffle(csets)
# Build a password by just cycling though the shuffled
# CharacterSet instances, getting their next character.
password = []
csets = cycle(csets)
for _ in range(length):
while True:
cset = next(csets)
if not cset.is_empty:
break
password.append(cset.next_char())
random.shuffle(password)
return ''.join(password) | {
"domain": "codereview.stackexchange",
"id": 44735,
"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, random, console",
"url": null
} |
python, python-3.x, random, console
Next steps: reconsider even distributions. When passwords generated by the
code above are run through the analyze_passwords() function, the passwords
end up having a very even distribution across the character categories (again,
subject to unique constraint). But you might want to reconsider having such an
even distribution. My advice would be to start with the minimum counts desired for
each category (eg, 2 characters from each category). You can build that
password in the manner shown above. Then, to get the remaining characters
needed to achieve full password length, draw from a universal CharacterSet
that is created using all of the remaining characters from the
category-specific CharacterSet instances. | {
"domain": "codereview.stackexchange",
"id": 44735,
"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, random, console",
"url": null
} |
beginner, asynchronous, http, concurrency, go
Title: Golang Tour Web Crawler Exercise
Question: In the last few days I've played around with Go a little and took the language tour. The last exercise (text here) requires you to crawl a graph that simulates a set of Web pages with links, using goroutines, channels and locking primitives to do it in a concurrent fashion without ever going to the same page twice. I added a random latency to the fetch procedure to simulate the time to actually fetch a page.
My solution involves a timeout, which I'm not very fond of. In a real Web crawler I could expect some action to be taken when a timeout is hit, but in this very limited case perhaps I can use some more robust solution. Any idea? I tried using a counter to keep track of enqueued items and then closing the results channel when there were no more items to explore but the goroutine fetching the page which feeds the results channel has no awareness of other page fetching going on, so I ended up closing the channel to early (now that I'm writing this down I realize perhaps I can use some sort of "control" channel to sync the goroutines in some way).
This is my solution (available in the Go Playground here — I've written code from the Fetch struct to the Crawl function, the rest was already provided by the exercise):
package main
import (
"fmt"
"sync"
"time"
"math/rand"
)
type Fetcher interface {
Fetch(url string) (body string, urls []string, err error)
}
type Links struct {
urls []string
depth int
}
type ConcurrentStringSet struct {
set map[string]bool
mux sync.Mutex
}
func (cache *ConcurrentStringSet) onMissDoAsync(s string, f func()) {
cache.mux.Lock()
defer cache.mux.Unlock()
if !cache.set[s] {
cache.set[s] = true
go f()
}
} | {
"domain": "codereview.stackexchange",
"id": 44736,
"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": "beginner, asynchronous, http, concurrency, go",
"url": null
} |
beginner, asynchronous, http, concurrency, go
func NewAsyncCrawler(fetcher Fetcher, timeout time.Duration) (crawl func(string, int)) {
links := make(chan Links)
cache := ConcurrentStringSet{set:make(map[string]bool)}
crawl = func(url string, depth int) {
cache.onMissDoAsync(url, func() {
body, urls, err := fetcher.Fetch(url)
if err != nil {
fmt.Println(err)
} else {
fmt.Printf("found: %s %q\n", url, body)
if depth > 1 {
links <- Links{urls, depth - 1}
}
}
})
for {
select {
case link := <-links:
for _, url := range link.urls {
go crawl(url, link.depth)
}
case <-time.After(timeout):
return
}
}
}
return
}
func Crawl(url string, depth int, fetcher Fetcher) {
if (depth > 0) {
crawl := NewAsyncCrawler(fetcher, 500 * time.Millisecond)
crawl(url, depth)
}
}
func main() {
Crawl("http://golang.org/", 4, fetcher)
}
type fakeFetcher map[string]*fakeResult
type fakeResult struct {
body string
urls []string
}
func (f fakeFetcher) Fetch(url string) (string, []string, error) {
rand.Seed(time.Now().UnixNano())
time.Sleep(time.Duration(rand.Intn(500)) * time.Millisecond)
if res, ok := f[url]; ok {
return res.body, res.urls, nil
}
return "", nil, fmt.Errorf("not found: %s", url)
} | {
"domain": "codereview.stackexchange",
"id": 44736,
"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": "beginner, asynchronous, http, concurrency, go",
"url": null
} |
beginner, asynchronous, http, concurrency, go
var fetcher = fakeFetcher{
"http://golang.org/": &fakeResult{
"The Go Programming Language",
[]string{
"http://golang.org/pkg/",
"http://golang.org/cmd/",
},
},
"http://golang.org/pkg/": &fakeResult{
"Packages",
[]string{
"http://golang.org/",
"http://golang.org/cmd/",
"http://golang.org/pkg/fmt/",
"http://golang.org/pkg/os/",
},
},
"http://golang.org/pkg/fmt/": &fakeResult{
"Package fmt",
[]string{
"http://golang.org/",
"http://golang.org/pkg/",
},
},
"http://golang.org/pkg/os/": &fakeResult{
"Package os",
[]string{
"http://golang.org/",
"http://golang.org/pkg/",
},
},
}
Answer: Hello there again my dear myself from 7 years ago. Your solution was nice, but probably a bit overcomplicated. You will probably be happy to know you have been able to come back to it a few years later in the process of re-learning Go and came up with something simpler. It keeps track of outstanding goroutines using sync.WaitGroup. I know in a sense it feels a bit like cheating, since sync.WaitGroup is not covered by the tour, but it looks like a simple, clean and idiomatic solution, so why not?
package main
import (
"fmt"
"sync"
)
type Visited struct {
m sync.Mutex
s map[string]bool
}
func New() Visited {
return Visited{s:make(map[string]bool)}
}
func (v *Visited) Add(key string) {
v.m.Lock()
v.s[key] = true
v.m.Unlock()
}
func (v *Visited) Has(key string) bool {
v.m.Lock()
defer v.m.Unlock()
return v.s[key]
}
type Fetcher interface {
// Fetch returns the body of URL and
// a slice of URLs found on that page.
Fetch(url string) (body string, urls []string, err error)
} | {
"domain": "codereview.stackexchange",
"id": 44736,
"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": "beginner, asynchronous, http, concurrency, go",
"url": null
} |
beginner, asynchronous, http, concurrency, go
// Crawl uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.
func Crawl(url string, depth int, fetcher Fetcher, visited *Visited, wg *sync.WaitGroup) {
defer wg.Done()
if visited.Has(url) || depth <= 0 {
return
}
visited.Add(url)
body, urls, err := fetcher.Fetch(url)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("found: %s %q\n", url, body)
for _, u := range urls {
wg.Add(1)
go Crawl(u, depth-1, fetcher, visited, wg)
}
return
}
func main() {
var wg sync.WaitGroup
visited := New()
wg.Add(1)
go Crawl("https://golang.org/", 4, fetcher, &visited, &wg)
wg.Wait()
}
// fakeFetcher is Fetcher that returns canned results.
type fakeFetcher map[string]*fakeResult
type fakeResult struct {
body string
urls []string
}
func (f fakeFetcher) Fetch(url string) (string, []string, error) {
if res, ok := f[url]; ok {
return res.body, res.urls, nil
}
return "", nil, fmt.Errorf("not found: %s", url)
}
// fetcher is a populated fakeFetcher.
var fetcher = fakeFetcher{
"https://golang.org/": &fakeResult{
"The Go Programming Language",
[]string{
"https://golang.org/pkg/",
"https://golang.org/cmd/",
},
},
"https://golang.org/pkg/": &fakeResult{
"Packages",
[]string{
"https://golang.org/",
"https://golang.org/cmd/",
"https://golang.org/pkg/fmt/",
"https://golang.org/pkg/os/",
},
},
"https://golang.org/pkg/fmt/": &fakeResult{
"Package fmt",
[]string{
"https://golang.org/",
"https://golang.org/pkg/",
},
},
"https://golang.org/pkg/os/": &fakeResult{
"Package os",
[]string{
"https://golang.org/",
"https://golang.org/pkg/",
},
},
}
Now onto more interesting stuff! | {
"domain": "codereview.stackexchange",
"id": 44736,
"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": "beginner, asynchronous, http, concurrency, go",
"url": null
} |
c++20, data-mining
Title: FPGrowth Algorithm Implementation
Question: This is my implementation of the FPGrowth algorithm where, as an optimisation, I avoid re-creating the tree at each extension of the prefix, while I use a view representation that I think would be more memory efficient. Please let me know if there are any other ways to improve the current code. Any feedback is appreciated.
#include <iostream>
#include <map>
#include <unordered_set>
#include <vector>
#include <unordered_map>
#include <deque>
#include <queue>
#import <cassert>
#include <stack>
/**
* Trie node required by the fpgrowth algorithm
* @tparam T
*/
template <typename T> struct fpgrowth_node {
size_t count, // Number of instances being observed
tmp_count, // Temporary count while pruning the graph: instead of creating another fpgrowth tree, I'll use views to accelerate the task
height; // height inducing the visiting order from the leaves
const T* value; // Pointer to the actual value: this is done so to alleviate the memory from having multiple copies of the object. (the actual singleton will reside in the main fpgrowth table)
struct fpgrowth_node* parent; // Root for the current node (if any)
std::unordered_map<const T*, struct fpgrowth_node*> children; // Children mapped by key value
struct fpgrowth_node* list; // single linked list connecting all the nodes associated to the same object
// bool current_leaf; // whether this element is currently a leaf
fpgrowth_node(const T* k = nullptr) : value{k}, count{1}, tmp_count{0}, height{0}, parent{nullptr}, children{}, list{nullptr} {} | {
"domain": "codereview.stackexchange",
"id": 44737,
"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++20, data-mining",
"url": null
} |
c++20, data-mining
/**
* Adding a child to the curent node or, if it already exists, incrementing the counter for the existing one
* @param value Value associated to the child
* @return Either the already-existing child or the newly allocated one
*/
struct fpgrowth_node* add_child(const T* value) {
auto it = children.emplace(value, nullptr);
if (it.second) { // If I am adding a new child
it.first->second = new fpgrowth_node(value); // Allocating the new child
it.first->second->parent = this; // Setting the parent to the current node
it.first->second->height = height+1; // Increasing the height, so to exploit topological sort for efficiently scanning the tree from the leaves
} else {
it.first->second->height = std::max(height+1,it.first->second->height); // Otherwise, update the nodes' depth depending on my current one
it.first->second->count++; // If the child was already there, increment its count
}
return it.first->second; // returning the child already being created in the trie
}
~fpgrowth_node() {
for (const auto& [k,v] : children) delete v; // deleting all of the allocated children so to save memory and avoid memory leaks
}
};
template <typename T>
static inline void fpgrowth_expand(struct fpgrowth_node<T>* tree,
const T* current,
size_t curr_support,
std::unordered_set<const T*> prefix,
const std::unordered_set<struct fpgrowth_node<T>*>& view,
std::unordered_map<const T*, struct fpgrowth_node<T>*>& traverse,
std::vector<std::pair<size_t, std::unordered_set<const T*>>>& results,
size_t minsupport = 1) { | {
"domain": "codereview.stackexchange",
"id": 44737,
"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++20, data-mining",
"url": null
} |
c++20, data-mining
// std::cout << "Step: ";
// for (const auto& ptr :prefix)
// std::cout << *ptr << " ";
// std::cout << *current << std::endl;
std::unordered_set<struct fpgrowth_node<T>*> visitable, // Whether the element was already visited in a previous iteration
in_tree // Whether the node, for its good support, might be part of the next pruning and therefore part of the view
;
auto comp = []( struct fpgrowth_node<T>* a, struct fpgrowth_node<T>* b ) { return a->height < b->height; }; // As a tree is a DAG, I can exploit the topological order to know in which order extract the nodes from the queue
std::priority_queue<struct fpgrowth_node<T>*, std::vector<struct fpgrowth_node<T>*>, decltype(comp)> dq; // Priority queue for storing all the nodes, being sorted by order of visit
auto it = traverse.find(current); // Checking whether we are allowed to traverse from this node
std::unordered_map<const T*, struct fpgrowth_node<T>*> new_firsttraverse; // Updating the first_to_traverse table depending on the nodes being available
std::unordered_map<const T*, size_t> toTraverseNext; // Updating the support table while keeping the support of the previous nodes
std::vector<struct fpgrowth_node<T>*> visitedChild; // For each non-leaf node, keeping all the childs that were visited within the view
if (it != traverse.end()) {
{
struct fpgrowth_node<T>* ptr = it->second;
while (ptr) {
if (view.contains(ptr)) { // If the current element in the linked list is actually part of the view
dq.emplace(ptr);
}
ptr = ptr->list; // Scanning all the elements in the list
}
} | {
"domain": "codereview.stackexchange",
"id": 44737,
"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++20, data-mining",
"url": null
} |
c++20, data-mining
while (!dq.empty()) {
struct fpgrowth_node<T>* dq_ptr = dq.top(); // Next element to be visited
dq.pop();
if (!visitable.emplace(dq_ptr).second) continue; // Discarding visiting the node if visited already
{
dq_ptr->tmp_count = 0; // Re-setting the counter to zero
// dq_ptr->current_leaf = true;
bool isLeaf = (dq_ptr->value == current);
bool goodToTest = false;
if (isLeaf) {
dq_ptr->tmp_count = dq_ptr->count;// As this is the leaf, it needs to hold the tmp_count for the visit its own support count.
// dq_ptr->current_leaf = true;// Setting the current node as leaf, from which start the visit (from the bottom!)
goodToTest = true; // Yes, I can proceed with the visit
} else {
size_t totalChild = 0; // Counting the number of allowed children to be visited within the view as in (A)
visitedChild.clear(); // Clearing the set of the previous children
for (const auto& [k,v] : dq_ptr->children) {
if (view.contains(v)) {
totalChild++; // (A)
if (visitable.contains(v)) {
visitedChild.emplace_back(v); // Yes, this child has been visited in a previous iteration
}
}
}
if (totalChild == visitedChild.size()) { // I can do the counting only if I have already visited all of the childs that are there in the
for (const auto& v : visitedChild) { // After visiting all the childs that I could, *then*, I set my tmp_count to the sum of my child's tmp_count
goodToTest = true; | {
"domain": "codereview.stackexchange",
"id": 44737,
"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++20, data-mining",
"url": null
} |
c++20, data-mining
goodToTest = true;
dq_ptr->tmp_count += v->tmp_count; // Then, setting up the count to the sum of the supports from my fully visited children
// dq_ptr->current_leaf = dq_ptr->current_leaf && ((v->current_leaf) && (v->tmp_count < minsupport)); // Setting myself as a leaf
}
} else
visitable.erase(dq_ptr); // B: If I am not allowed to visit all the children, as they have not fully visited yet, re-set myself in the visiting queue
// the queue guarantees that, if I have not visited another child, then, I will eventually put back in the queue by it in (C), so this does not misses a node
}
if (visitable.contains(dq_ptr)) { // If the visit was successful and (B) did not happen
if (goodToTest && (dq_ptr->tmp_count >= minsupport)) { // testing the support only if I am either a leaf or whether I have already visited all my childs, so to not
auto it4 = toTraverseNext.emplace(dq_ptr->value, dq_ptr->tmp_count); // Setting the current support in the table for the current item
if (!it4.second)
it4.first->second += dq_ptr->tmp_count; // If a previous value was already there, then just update it!
if (current != dq_ptr->value) new_firsttraverse.emplace(dq_ptr->value, dq_ptr); // If this was not met before, then setting the current node as first step in the list to be visited
in_tree.insert(dq_ptr); // Definitively, if the support is good, this should be part of the next iteration
}
if (view.contains(dq_ptr->parent)) // If the parent is an allowed node (still, it should be)
dq.push(dq_ptr->parent); // C: putting the parent as the next step to visit
} | {
"domain": "codereview.stackexchange",
"id": 44737,
"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++20, data-mining",
"url": null
} |
c++20, data-mining
}
}
}
prefix.insert(current); // Adding the current node as part of the prefix
results.emplace_back(curr_support, prefix); // setting this as another result
for (const auto& [next,with_supp] : toTraverseNext) { // Using the updated support table to traverse the remaining nodes
if ((next != current) && ( !prefix.contains(next))) // Visiting next only other strings that were not part of the prefix
fpgrowth_expand(tree, next, with_supp, prefix, in_tree, new_firsttraverse, results, minsupport);
}
} | {
"domain": "codereview.stackexchange",
"id": 44737,
"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++20, data-mining",
"url": null
} |
c++20, data-mining
template <typename T>
static inline std::vector<std::pair<size_t, std::unordered_set<const T*>>> fpgrowth(const std::vector<std::unordered_set<T>>& obj,
std::vector<std::pair<T, size_t>>& final_element_for_scan,
size_t minsupport = 1) {
struct fpgrowth_node<T> tree{nullptr};
final_element_for_scan.clear();
std::unordered_set<struct fpgrowth_node<T>*> in_tree;
std::unordered_map<const T*, struct fpgrowth_node<T>*> last_pointer, firstpointer;
std::unordered_map<const T*, std::unordered_set<struct fpgrowth_node<T>*>> createdElements;
{
std::map<T, size_t> element; // Fast representation for the support table, for efficiently associating the item to the support value
for (auto it = obj.begin(); it != obj.end(); it++) {
for (const T& x : *it) {
auto it2 = element.emplace(x, 1);
if (!it2.second) it2.first->second++;
}
}
// moving this to a vector, while keeping the items with adequate support
for (auto it = element.begin(), en = element.end(); it != en; it++) {
if (it->second >= minsupport)
final_element_for_scan.emplace_back(*it);
}
}
// Sorting the elements in the table by decreasing support
std::sort(final_element_for_scan.begin(), final_element_for_scan.end(), [](const std::pair<T, size_t>& l, const std::pair<T, size_t>& r) {
return l.second>r.second;
});
struct fpgrowth_node<T>* ptr ;
for (auto itx = obj.begin(); itx != obj.end(); itx++) { // For each transaction
auto e = itx->end();
ptr = &tree;
auto it_left = final_element_for_scan.begin();
auto e_left = final_element_for_scan.end();
while ((it_left != e_left)) {
auto f = itx->find(it_left->first);
if (f == e) {it_left++; continue;}
else { | {
"domain": "codereview.stackexchange",
"id": 44737,
"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++20, data-mining",
"url": null
} |
c++20, data-mining
if (f == e) {it_left++; continue;}
else {
// For each element in the transaction which is also in the support table
auto it3 = last_pointer.emplace(&it_left->first, nullptr);
// Expanding the trie with a new child
ptr = ptr->add_child(&it_left->first);
// Using a set of visited nodes to avoid loops in the list
bool newInsertion = createdElements[&it_left->first].emplace(ptr).second;
in_tree.insert(ptr); // This node shoudl be part of the view
if (it3.second) {
// First pointer of the list for traversing the newly established leaves at each novel iteration efficiently
firstpointer.emplace(&it_left->first, ptr);
it3.first->second = ptr;
} else {
if (!it3.first->second) {
// First pointer of the list for traversing the newly established leaves at each novel iteration efficiently
it3.first->second = ptr;
} else if (newInsertion) {
// Avoiding loops: adding an element in the list only if required
it3.first->second->list = ptr;
it3.first->second = ptr;
}
}
it_left++;
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44737,
"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++20, data-mining",
"url": null
} |
c++20, data-mining
createdElements.clear();
// results of the itemsets with their support to be returned
std::vector<std::pair<size_t, std::unordered_set<const T*>>> results;
// Setting up the new projection of the tree, so to avoid the re-creation of the trees multiple times:
// setting up a view with the allowed nodes will be more efficient (as it will save the extra allocation cost for
// the nodes, and the only memory overhead is just the pointer to the nodes in the FPGrowth tree)
for (auto rit = final_element_for_scan.rbegin(), ren = final_element_for_scan.rend(); rit != ren; rit++) {
fpgrowth_expand(ptr, (const T *) &rit->first, rit->second, std::unordered_set<const T *>{}, in_tree, firstpointer, results,
minsupport);
}
return results;
}
int main() {
std::vector<std::unordered_set<std::string>> S;
S.emplace_back(std::unordered_set<std::string>{"m","o","n","k","e","y"});
S.emplace_back(std::unordered_set<std::string>{"d","o","n","k","e","y"});
S.emplace_back(std::unordered_set<std::string>{"m","a","k","e"});
S.emplace_back(std::unordered_set<std::string>{"m","u","c","k","y"});
S.emplace_back(std::unordered_set<std::string>{"c","o","c","k","i","e"});
std::vector<std::pair<std::string, size_t>> single_support;
for (const auto& ref : fpgrowth(S, single_support, 3)) {
std::cout << "Item: ";
for (const auto& ptr : ref.second)
std::cout << *ptr << " ";
std::cout << " with support " << ref.first << std::endl;
}
return 0;
}
``` | {
"domain": "codereview.stackexchange",
"id": 44737,
"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++20, data-mining",
"url": null
} |
c++20, data-mining
Answer: Enable warnings and fix them
Enable compiler and Doxygen warnings, and fix all of them. Doyxgen is complaining about several undocumented class members, and the compiler is complaining about #import (this should be #include), missing #include <algorithm>, and incorrect order of the initializer list in the constructor of fpgrowth_node. I recommend you fix the latter by using default member intializers instead.
Unused parameter tree in fpgrowth_expand()
What the compiler didn't catch, because it looks used, is the parameter tree in fpgrowth_expand(). You pass that on to recursive calls, but you don't do anything else with this parameter. It's there for useless and should be removed.
No need to repeat struct and class after declaration
Unlike in C, after you have declared a struct or a class, you can refer to them just by their name, without having to prefix that with struct or class again.
Avoid manual memory management
Avoid calling new and delete where possible, and instead use containers or smart pointers to manage memory for you. They will ensure you don't forget to delete things, and they also do the right thing in case exceptions are thrown. In your code, it's easy: instead of storing pointers to fpgrowth_node in children, just store fpgrowth_nodes directly:
template <typename T>
struct fpgrowth_node {
…
std::unordered_map<const T*, fpgrowth_node> children;
…
public:
…
fpgrowth_node* add_child(const T* value) {
auto [it, is_new] = children.try_emplace(value, value);
auto& child = it->second;
if (is_new) {
child.parent = this;
child.height = height + 1;
} else {
child.height = std::max(height + 1, child.height);
child.count++;
}
return &child;
}
…
}; | {
"domain": "codereview.stackexchange",
"id": 44737,
"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++20, data-mining",
"url": null
} |
c++20, data-mining
return &child;
}
…
};
Note that you no longer need a destructor this way either.
Make it work for any type of container
You already thought of making the algorithm more generic by templating it on the item type. However, you still require the input to be in the form of std::vectors of std::unordered_sets of those items. But what if you have a std::deque of std::sets instead? You could make your classes and functions even more generic. Consider:
template <typename Dataset>
auto fpgrowth(const Dataset& dataset, …) {
// Derive the types of transactions and items
using Itemset = Dataset::value_type;
using T = Itemset::value_type;
…
}
Most of the code will be unchanged. Of course, the second parameter of fpgrowth() is an issue, because it depended on T. However, this is actually an out parameter, and instead you can just make it part of the return value, or alternatively make the whole type of final_element_for_scan a template type as well.
Make better use of range-for loops
You use range-for loops in a few places, but often you will use old-style for loops. Prefer to use range-for where possible. For example, near the start of fpgrowth():
{
std::unordered_map<T, size_t> elements;
for (auto& transaction: dataset) {
for (auto& item: transaction) {
elements.emplace(item, 0).first->second++;
}
}
for (auto& [item, count]: elements) {
if (count >= minsupport)
final_element_for_scan.emplace_back(item, count);
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44737,
"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++20, data-mining",
"url": null
} |
c++20, data-mining
Since you are using C++20, I also used structured bindings to avoid having to write .first and .second in the second for-loop. This brings me to:
Naming things
Whenever you use std::pair, you are stuck with naming the two members .first and .second. These names carry little meaning When you have pairs of pairs, you get to write things like foo.first->second->bar, and it's really hard to understand the code at that point.
There are various ways to avoid this. First, you can use references and structured bindings to temporarily give better names to members of a pair, like I did above in add_child(). However, even better is to not use std::pair if possible, and just create a struct with two better named members. Consider:
struct element_count {
T item;
std::size_t count;
};
std::vector<element_count> final_elements_for_scan;
And:
struct itemset_support {
Itemset items;
std::size_t support;
};
std::vector<itemset_support> result;
Related to this, if you frequently use a nested type like std::unordered_set<fpgrowth_node<T>*>, create a type alias for it with a clear name, like:
using Nodeset = std::unordered_set<fpgrowth_node<T>*>;
…
Nodeset in_tree;
std::unordered_map<const T*, Nodeset> createdElements; | {
"domain": "codereview.stackexchange",
"id": 44737,
"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++20, data-mining",
"url": null
} |
c++20, data-mining
Also try to avoid abbreviating names too much, and avoid using too generic names. It's not great to see it, it2, itx, e, it_left, e_left and it3 all in one function. As mentioned above, prefer range-for, so instead of iterators you only have to deal with values. If you do abbreviate, at least be consistent; don't write element in one place and e in another.
Also be consistent in the way you format names. I see snake_case in some places, camelCase in others. It does not matter that much which way you choose, as long as you use the same style everywhere.
Consider using C++20's ranges
If possible, consider using C++20's range-based algorithms. These avoid you having to specify the begin and end iterators, and instead just take a reference to the whole container, so there is less to type and less chance of making mistakes.
Reconsider your datatypes
I see both std::map and std::unordered_map. I see the member variable tmp_count in fpgrowth_node, but local function variables visitable and in_tree. All these things have a certain cost, and the performance of your algorithm can be greatly affected by this. For example, lookups and insertions in std::map are \$O(\log N)\$, whereas lookups and insertions in std::unordered_map are \$O(1)\$.
Also consider memory usage of these datastructures. Both std::map and std::unordered_map can make a separate heap memory allocation for each item you insert. So if you can make in_tree a bool member variable of fpgrowth_node, that would save a lot of memory.
Also consider merging maps if possible. Why have separate last_pointer, firstpointer and createdElements maps when they are all indexed by the same key? These maps could be merged by creating a struct that holds the value parts of each of the three original maps. | {
"domain": "codereview.stackexchange",
"id": 44737,
"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++20, data-mining",
"url": null
} |
strings, swift, palindrome
Title: Is Palindrom-function in Swift
Question: Task is simply to write the classic isPalindrom-function.
Here's my implementation:
func isStringPalindrom(str: String) -> Bool {
let lcStr = str.lowercased()
var i = 0
let aChars = Array(lcStr)
while i < (lcStr.count / 2) {
if aChars[i] != aChars[aChars.count - (i + 1)] {
return false
}
i += 1
}
return true
}
// Samples (provided with the exercise)
print(isStringPalindrom(str: "rotator")) // Should return true
print(isStringPalindrom(str: "Rats live on no evil star")) // Should return true
print(isStringPalindrom(str: "Never odd or even")) // Should return false
print(isStringPalindrom(str: "Hello, world")) // Should return false
// Own ideas
print(isStringPalindrom(str: "Anna"))
print(isStringPalindrom(str: "Otto"))
print("Otxto: \(isStringPalindrom(str: "Otxto"))")
print(isStringPalindrom(str: "Tacocat"))
print(isStringPalindrom(str: "Tacoxcat"))
All tests work as expected. Therefore I think it's formally correct.
But could it become improved concerning algorithm and naming?
Answer: Nitpicking: In English it is “palindrome” and not “palindrom”, so the function name should be isStringPalindrome.
The parameter name str does not convey any information to the caller, I would use an empty argument label instead
func isStringPalindrome(_ str: String) -> Bool
or simply
func isPalindrome(_ str: String) -> Bool
Another option is to make it an extension method of the String type
extension String {
func isPalindrome() -> Bool {
// ...
}
}
which is then called as
"someString".isPalindrome() | {
"domain": "codereview.stackexchange",
"id": 44738,
"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": "strings, swift, palindrome",
"url": null
} |
strings, swift, palindrome
which is then called as
"someString".isPalindrome()
As said in the comments, you might want to leave it to the caller whether all characters should be converted to lower case before the comparison.
You convert the string to an array first. That allows efficient (\$ O(1) \$) random access to all characters. But then you should use aChars.count in the while-condition and not lcStr.count. The latter is \$ O(N) \$ where \$ N \$ is the number of characters in the string, whereas the former is \$ O(1) \$.
Instead of creating an array with all characters you can use two indices into the string, one traversing from the start of the string forward, and the other traversing from the end of the string backwards:
func isPalindrome(_ str: String) -> Bool {
if str.isEmpty {
return true
}
var front = str.startIndex
var back = str.endIndex
str.formIndex(before: &back)
while front < back {
if str[front] != str[back] {
return false
}
str.formIndex(after: &front)
str.formIndex(before: &back)
}
return true
}
But actually this can be shortened and simplified to
func isPalindrome(_ str: String) -> Bool {
str.elementsEqual(str.reversed())
}
reversed() creates a view presenting the elements of the string in reverse order, so no additional string or array is allocated, and elementsEqual compares the two strings (or in general, sequences) one by one until a difference is found. | {
"domain": "codereview.stackexchange",
"id": 44738,
"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": "strings, swift, palindrome",
"url": null
} |
strings, regex, kotlin
Title: Swift-function which counts the letters, numbers, spaces, special chars in a given string
Question: Task description: Write a function, which counts the letters, spaces, number and special characters in string.
My implementation:
fun getPartsCount(str: String): Array<Int> {
val nums = "[0-9]".toRegex().findAll(str)
val letters = "[a-zA-Z]".toRegex().findAll(str)
val spaces = " ".toRegex().findAll(str)
var others = str.count() - nums.count() - letters.count() - spaces.count()
return arrayOf(nums.count(), letters.count(), spaces.count(), others)
}
fun main() {
print("Please enter a string > ")
val userInput = readLine()
if (!userInput.isNullOrEmpty()) {
val results = getPartsCount(userInput)
println("Numbers: ${results[0]}, Letters: ${results[1]}, " +
"Spaces: ${results[2]}, Others: ${results[3]}")
} else {
println("No input provided.")
}
}
I solved the task using Regular Expressions, but is there a better way in Kotlin for accomplishing the task?
What's your opinion about returning the results in an array?
What would you do different and why?
Answer: Returning an array
What's your opinion about returning the results in an array?
Why would you do that? Because it's an easy way to return the result? Because you don't know how else to do it?
How are users expected to know which index is 0, 1, 2, and 3 respectively?
It would be much better to return a class.
data class PartsCountResult(
val numbers: Int,
val letters: Int,
val spaces: Int,
val others: Int,
)
Creating a class in Kotlin is really easy. Do it when you need it. You don't even have to put it in a separate file!
Using Regex
I solved the task using Regular Expressions, but is there a better way in Kotlin for accomplishing the task? | {
"domain": "codereview.stackexchange",
"id": 44739,
"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": "strings, regex, kotlin",
"url": null
} |
strings, regex, kotlin
As each character is only in one group and are easily distinguishable, you can loop over the string once and count each char.
var letters = 0
var numbers = 0
var spaces = 0
var others = 0
for (c in str) {
when (c) {
in 'a'..'z', in 'A'..'Z' -> letters++
in '0'..'9' -> numbers++
' ' -> spaces++
else -> others++
}
}
Alternative solution
val letters = str.count { it in 'A'..'Z' || it in 'a'..'z' }
val digits = str.count { it in '0'..'9' }
val spaces = str.count { it == ' ' }
val others = str.length - letters - digits - spaces | {
"domain": "codereview.stackexchange",
"id": 44739,
"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": "strings, regex, kotlin",
"url": null
} |
java, comparative-review, rest, spring
Title: Spring REST Endpoint for Saving a User Inquiry
Question: Here's a piece of code from codebase I maintain/contribute to.
It is a Spring REST controller, which exposes an endpoint to create user question. The question consists of title, description and reference to the user who asked it.
It feels it's a bit of problematic from the design standpoint. That said, the person who originally wrote this controller is more experienced than I am so I want to make sure. To me, the method below seems bloated and violating the Single Responsibility Principle (SRP)
@RequiredArgsConstructor
@Validated
@RestController
@RequestMapping("/api/v1/user/questions")
public class UserQuestionRestController {
private final QuestionService questionService;
private final TagService tagService;
private final QuestionResponseDtoService questionResponseDtoService;
@PostMapping
public ResponseEntity<Void> create(@RequestBody @Valid QuestionRequestDto dto,
@NotNull Authentication authentication) {
Question question = QuestionMapper.toEntity(dto);
Account currentUser = (Account) authentication.getPrincipal();
question.setOwner(currentUser);
List<Tag> tags = new ArrayList<>();
if (dto.tagIds() != null) {
tags = tagService.getByIds(dto.tagIds());
}
question.setTags(new HashSet<>(tags));
questionService.create(question);
return ResponseEntity.status(HttpStatus.CREATED).build();
}
public final class QuestionMapper {
private QuestionMapper() {
}
public static Question toEntity(QuestionRequestDto dto) {
Question question = new Question();
question.setTitle(dto.title());
question.setDescription(dto.description());
return question;
}
} | {
"domain": "codereview.stackexchange",
"id": 44740,
"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, comparative-review, rest, spring",
"url": null
} |
java, comparative-review, rest, spring
First, the controller does so much more that simply receiving a request and sending a response. Second, there's an attempt to separate concerns with the QuestionMapper static method toEntity() which doesn't do the "DTO → entity" mapping in its entirety anyway. The owner and tags fields are set in the controller itself. That is, it's what seems to me a SRP violation happening twice
If I am right, and there's a need to move all that logic from the controller somewhere else, what that "somewhere else" should be? I could make QuestionMapper a @Component, add and @Autowire a service field, and then set all the fields in the toEntity() method (I also doubt it should be static in this case). Eventually, I ditched the QuestionMapper altogether and do the conversion with the help of a service instance.
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/v1/user/questions")
public class UserQuestionRestController {
private final QuestionService service;
@PostMapping
public ResponseEntity<Void> create(@RequestBody @Valid QuestionRequestDto dto,
@NotNull Authentication authentication) {
Question question = service.mapFromDto(dto, authentication);
service.create(question);
return ResponseEntity.created(/* URL */).build();
}
}
Would you agree that this is the better way to do it?
Here is the Question entity for completeness.
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@Entity
@EntityListeners(AuditingEntityListener.class)
@Table(name = "questions")
public class Question {
@Setter(AccessLevel.NONE)
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true, nullable = false, updatable = false)
private Long id;
@Setter(AccessLevel.NONE)
@NotNull
@CreatedDate
@Column(name = "created_date", nullable = false)
private LocalDateTime createdDate; | {
"domain": "codereview.stackexchange",
"id": 44740,
"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, comparative-review, rest, spring",
"url": null
} |
java, comparative-review, rest, spring
@Setter(AccessLevel.NONE)
@NotNull
@LastModifiedDate
@Column(name = "modified_date", nullable = false)
private LocalDateTime modifiedDate;
@NotBlank
@Column(name = "title", nullable = false)
private String title;
@NotBlank
@Column(name = "description", nullable = false, columnDefinition = "text")
private String description;
@NotNull
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "account_id", nullable = false, updatable = false)
private Account owner;
@NotNull
@ManyToMany
@JoinTable(name = "questions_tags",
joinColumns = @JoinColumn(name = "question_id", nullable = false),
inverseJoinColumns = @JoinColumn(name = "tag_id", nullable = false),
uniqueConstraints = @UniqueConstraint(columnNames = {"question_id", "tag_id"}))
private Set<Tag> tags = new HashSet<>();
Answer: Regarding the mapper
public final class QuestionMapper {
public static Question toEntity(QuestionRequestDto dto) {
...
}
} | {
"domain": "codereview.stackexchange",
"id": 44740,
"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, comparative-review, rest, spring",
"url": null
} |
java, comparative-review, rest, spring
The way the mapper is implemented is an invitation to SRP violations. You have a mapper for a type, and the mapper is responsible for converting that type to whatever other object type there is a need for. What happens if you need to create a QuestionSummary object? By the way the mapper is named, the toQuestionSummary() method would go to QuestionMapper. With your design, the possible set of responsibilities for a given mapper are not restricted. I have seen the worst possible results for this approach and they were not pretty.
My preferred choice is to "reverse" the mapper. A QuestionMapper would be responsible for creating Question objects from whatever type there is. While this doesn't guarantee 1-to-1 mapping, it has worked really well for me and the mappers that have multiple mapping methods are a rarity.
My chosen name for all mapping methods is from. This ensures that the naming is always consistent between mappers and that naming conflicts are a sign of a SRP violation or other code smell. And there is no need to spend time figuring out the correct name for a mapping method (e.g. should your method be toDto, toEntity or toQuestionRequest?) The name of the input parameter for the from-method is always source. The name for the target object is always... target. These last two are a matter of taste, you could use "input" and "output" or whatever, as long as the choice is consistent throughout the codebase.
The mappers are components that get injected. A mapper may depend on another mapper, in case the mapped type is a complex object or contains common mappings. The dependencies are again injected. This allows efficient unit testing as the mappers can be easily mocked.
Your mapper would thus become:
@Component
public class QuestionMapper {
public Question from(final QuestionRequestDto source) {
final Question target = new Question();
...
return target;
}
} | {
"domain": "codereview.stackexchange",
"id": 44740,
"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, comparative-review, rest, spring",
"url": null
} |
python, multithreading, rust, numpy, game-of-life
Title: Parallelization of the tick function in a Game of Life simulation using Rust and Python (+ NumPy)
Question: I've been writing a small Rust module recently with the sole purpose of speeding up my Python program, which is a Conway's Game of Life simulation. The function written in Rust is called from Python using the maturin package and PyO3 crate (on Rust's side).
I've come up with a working prototype, but there are still a few things I'd like to polish out before I'm happy with the project:
the function, albeit working, looks a little verbose and not how Rust ought to be written - I am new to the language, so clunky code is to be expected; a complete rewrite of the function might be beneficial in achieving the desired effect,
the function uses a PyArray2 object to represent the Game of Life Universe (due to the fact that on Python's side this is stored as a NumPy's ndarray) and stores individual cells as u8 type, which I think is an overkill - we don't need 8 bits per cell when one bit is plenty enough, but I haven't got a clue how to properly store them in such a manner,
most importantly: parallelization - I'd like my function to fully utilize the CPU cores by running multiple threads in the update function (for example, by splitting the updated universe in half and dispatching work to two threads). I have attempted to achieve this in a few different ways but haven't come up with anything of value, hence why I'm asking for help).
Attached below is the source code of both my Rust and Python files (I only care about improving the update_cells() function on Rust's side, but I thought showing the entirety of the project's code might ease the work required to test the function):
lib.rs:
use numpy::PyArray2;
use pyo3::prelude::*;
#[pyfunction]
fn update_cells<'a>(py: Python<'a>, cur: &'a PyArray2<u8>) -> PyResult<&'a PyArray2<u8>> {
let width = cur.shape()[0];
let height = cur.shape()[1];
let nxt = PyArray2::<u8>::zeros(py, [width, height], false); | {
"domain": "codereview.stackexchange",
"id": 44741,
"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, multithreading, rust, numpy, game-of-life",
"url": null
} |
python, multithreading, rust, numpy, game-of-life
for r in 0..width {
for c in 0..height {
let mut num_alive: u8 = 0;
for i in -1..2 {
for j in -1..2 {
if i == 0 && j == 0 {
continue;
}
let row = (r as i32 + i) as usize;
let col = (c as i32 + j) as usize;
if row < width && col < height {
num_alive += cur.get_owned([row, col]).unwrap();
}
}
}
if (cur.get_owned([r, c]).unwrap() == 1 && 2 <= num_alive && num_alive <= 3)
|| (cur.get_owned([r, c]).unwrap() == 0 && num_alive == 3)
{
unsafe {
*nxt.get_mut([r, c]).unwrap() = 1;
}
}
}
}
Ok(nxt)
}
#[pymodule]
fn interop_module_rs(_py: Python, m: &PyModule) -> PyResult<()> {
m.add_function(wrap_pyfunction!(update_cells, m)?)?;
Ok(())
}
main.py:
import os
from interop_module_rs import update_cells
os.environ["PYGAME_HIDE_SUPPORT_PROMPT"] = '1'
import numpy as np # noqa: E402
import pygame as pg # noqa: E402
from numpy.typing import ArrayLike # noqa: E402
PATH = os.path.dirname(os.path.abspath(__file__))
MAX_FPS = 60 # set to 0 to disable
def draw(surface: pg.Surface,
cur: ArrayLike,
sz: int,
grid: pg.Surface) -> None:
cur = np.flip(np.rot90(cur*255), 0)
cur = np.repeat(np.repeat(cur, sz, axis=0), sz, axis=1)
surf = pg.surfarray.make_surface(cur)
surface.blit(surf, (0, 0))
surface.blit(grid, (0, 0))
def init_gun(dimx: int,
dimy: int) -> ArrayLike:
cells = np.zeros((dimy, dimx)).astype(np.uint8)
pattern = np.loadtxt(
os.path.join(PATH, "init_gun.csv"),
dtype=np.uint8,
delimiter=",")
pos = (3, 3)
cells[pos[0]:pos[0]+pattern.shape[0],
pos[1]:pos[1]+pattern.shape[1]] = pattern
return cells | {
"domain": "codereview.stackexchange",
"id": 44741,
"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, multithreading, rust, numpy, game-of-life",
"url": null
} |
python, multithreading, rust, numpy, game-of-life
def random_init(dimx: int,
dimy: int) -> ArrayLike:
return np.random.randint(0, 2, (dimy, dimx)).astype(np.uint8)
def create_grid(surface: pg.Surface,
cellsize: int) -> pg.Surface:
grid = pg.Surface(surface.get_size())
for x in range(0, grid.get_width(), cellsize):
pg.draw.line(grid, (32, 32, 32), (x, 0), (x, grid.get_height()))
for y in range(0, grid.get_height(), cellsize):
pg.draw.line(grid, (32, 32, 32), (0, y), (grid.get_width(), y))
grid.set_colorkey((0, 0, 0))
return grid
def main(dimx: int,
dimy: int,
cellsize: int) -> None:
pg.init()
surface = pg.display.set_mode((dimx*cellsize, dimy*cellsize))
pg.display.set_caption("Game of Life")
# cells = init_gun(dimx, dimy)
cells = random_init(dimx, dimy)
grid = create_grid(surface, cellsize)
clock = pg.time.Clock()
while True:
clock.tick(MAX_FPS)
pg.display.set_caption(f"Game of Life - {int(clock.get_fps())} FPS")
for event in pg.event.get():
# quit game
if (event.type == pg.QUIT or
(event.type == pg.KEYDOWN and
event.key in (pg.K_ESCAPE, pg.K_q))):
pg.quit()
return
# pause game
if (event.type == pg.KEYDOWN and
event.key in (pg.K_SPACE, pg.K_p)):
while True:
pg.display.set_caption("Game of Life - PAUSED")
event = pg.event.wait()
if (event.type == pg.KEYDOWN and
event.key in (pg.K_SPACE, pg.K_p)):
break
# check if user wants to quit during pause
if (event.type == pg.QUIT or
(event.type == pg.KEYDOWN and
event.key in (pg.K_ESCAPE, pg.K_q))):
pg.quit()
return | {
"domain": "codereview.stackexchange",
"id": 44741,
"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, multithreading, rust, numpy, game-of-life",
"url": null
} |
python, multithreading, rust, numpy, game-of-life
cells = update_cells(cells)
draw(surface, cells, cellsize, grid)
pg.display.update()
if __name__ == "__main__":
main(64, 64, 9)
Screenshot of the simulation running:
Any help will be highly appreciated.
Answer: The numpy PyArray types are somewhat limited. Fortunately, they have an as_array method that will give you an Array from the ndarray crate which is must more powerful. It is unsafe for PyArray but you can use .readonly().as_array() safely.
Once you've got an array you can used numpy::ndarray::Zip, something like this:
Zip::indexed(cur.readonly().as_array()).map_collect(|(r, c), _| {
// calculate the correct value for row r and column c and return it
})
This will create a new array of the same shape as cur but with values computed by calling the closure.
You can also call par_map_collect instead of map_collect and it will do it using parallelism.
Then you can convert that array into a numpy array using numpy::PyArray2::from_owned_array.
let row = (r as i32 + i) as usize;
let col = (c as i32 + j) as usize;
What happens if r = 0 and i = -1 or c = 0 and j = 1? In dev mode this should panic. If you really want to use usizes that wrap around you should use std::num::Wrapping or the wrapping_add function. | {
"domain": "codereview.stackexchange",
"id": 44741,
"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, multithreading, rust, numpy, game-of-life",
"url": null
} |
c++, windows, assembly
Title: part of a c++ program which mods a game using code injection
Question: https://github.com/speedrun-program/amnesia_load_screen_tool/blob/main/code_injection.cpp
https://github.com/speedrun-program/amnesia_load_screen_tool/blob/main/file_helper.h
#include <cstdio>
#include <windows.h>
#include <tlhelp32.h>
#include <psapi.h>
#include <cstdint>
#include <string>
#include <memory>
#include <stdexcept>
#include "file_helper.h"
typedef LONG(__stdcall* NTFUNCTION)(HANDLE);
const wchar_t steamName[] = L"Amnesia.exe";
const wchar_t nosteamName[] = L"Amnesia_NoSteam.exe";
const char flashbackNameFile[] = "flashback_names.txt";
const uint32_t flashbackSkipInstructionsSize = 128;
const uint32_t flashbackWaitInstructionsSize = 128;
class ProcessHelper
{
public:
std::unique_ptr<unsigned char[]> buffer;
uint32_t memoryOffset = 0;
uint32_t bytesLeft = 0;
HANDLE amnesiaHandle = nullptr;
uint32_t amnesiaMemoryLocation = (uint32_t)-1;
DWORD pageSize = 0;
int bufferPosition = 0;
ProcessHelper(const ProcessHelper& fhelper) = delete;
ProcessHelper& operator=(ProcessHelper other) = delete;
ProcessHelper(ProcessHelper&&) = delete;
ProcessHelper& operator=(ProcessHelper&&) = delete;
ProcessHelper(DWORD pid)
{
amnesiaHandle = OpenProcess(
PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_SUSPEND_RESUME,
false,
pid
);
SYSTEM_INFO sysInfo;
GetSystemInfo(&sysInfo);
pageSize = sysInfo.dwPageSize;
buffer = std::make_unique<unsigned char[]>(pageSize);
bufferPosition = pageSize; // this initial value lets the first read happen on the first call to getByte
}
~ProcessHelper()
{
if (amnesiaHandle != nullptr)
{
CloseHandle(amnesiaHandle);
}
} | {
"domain": "codereview.stackexchange",
"id": 44742,
"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++, windows, assembly",
"url": null
} |
c++, windows, assembly
bool checkIfPathIsToAmnesia(const std::wstring& filepathBuffer)
{
// if L'\\' isn't found, filenamePosition will increase from npos to 0
size_t filenamePosition = filepathBuffer.find_last_of(L'\\') + 1;
int filenameSize = wcslen(&filepathBuffer[filenamePosition]);
if ((filenameSize != (sizeof(steamName) / sizeof(wchar_t)) - 1 && filenameSize != (sizeof(nosteamName) / sizeof(wchar_t)) - 1)
|| (wcscmp(&filepathBuffer[filenamePosition], steamName) != 0 && wcscmp(&filepathBuffer[filenamePosition], nosteamName) != 0))
{
return false;
}
return true;
}
bool checkIfProcessIsAmnesia()
{
std::wstring filepathBuffer(512 - 1, L'\0'); // - 1 because a character is used for a null terminator on modern implementations
DWORD queryFullProcessImageNameResult = 0;
if (amnesiaHandle != nullptr) // this check gets rid of warning C6387
{
while (queryFullProcessImageNameResult == 0)
{
DWORD filepathBufferSize = filepathBuffer.size() - 1; // - 1 because writing to filepathBuffer.size() position is undefined
queryFullProcessImageNameResult = QueryFullProcessImageName(amnesiaHandle, 0, &filepathBuffer[0], &filepathBufferSize);
if (queryFullProcessImageNameResult == 0)
{
DWORD errorNumber = GetLastError();
if (errorNumber == 122) // buffer too small error
{
filepathBuffer.clear();
filepathBuffer.resize(((filepathBufferSize + 2) * 2) - 1, L'\0'); // resizing to the next power of 2
}
else
{
printf("error when using GetModuleBaseName: %d\n", GetLastError());
return false;
}
} | {
"domain": "codereview.stackexchange",
"id": 44742,
"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++, windows, assembly",
"url": null
} |
c++, windows, assembly
if (filepathBufferSize >= 32767) // this should never happen
{
printf("ERROR: file path size from QueryFullProcessImageName somehow exceeded 32767 characters\n");
return false;
}
}
}
// if L'\\' isn't found, filenamePosition will increase from npos to 0
if (!checkIfPathIsToAmnesia(filepathBuffer))
{
printf("process name wasn't Amnesia.exe or Amnesia_NoSteam.exe when checking it using GetModuleBaseName: %ls\n", &filepathBuffer[0]);
return false;
}
return true;
}
bool findExecutableMemoryLocation()
{
std::wstring filepathBuffer(512 - 1, L'\0'); // - 1 because a character is used for a null terminator on modern implementations
uint32_t queryAddress = 0;
MEMORY_BASIC_INFORMATION mbi = {};
if (VirtualQueryEx(amnesiaHandle, (LPCVOID)queryAddress, &mbi, sizeof(mbi)) == 0) // checking if VirtualQueryEx works
{
printf("error when using VirtualQueryEx: %d\n", GetLastError());
return false;
}
// finding start of Amnesia.exe or Amnesia_NoSteam.exe memory
DWORD filepathBufferSize = 0;
DWORD charactersWritten = 0;
size_t filepathLength = (size_t)-1;
do
{
if (queryAddress != 0) // this check gets rid of warning C6387
{
do
{
filepathBufferSize = filepathBuffer.size() - 1; // - 1 because writing to filepathBuffer.size() position is undefined
charactersWritten = GetMappedFileName(
amnesiaHandle,
(LPVOID)queryAddress,
&filepathBuffer[0],
filepathBufferSize
); | {
"domain": "codereview.stackexchange",
"id": 44742,
"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++, windows, assembly",
"url": null
} |
c++, windows, assembly
if (filepathBufferSize == charactersWritten)
{
if (filepathBufferSize >= 32767) // this should never happen
{
continue;
}
filepathBuffer.clear();
filepathBuffer.resize(((filepathBufferSize + 2) * 2) - 1, L'\0'); // resizing to the next power of 2
}
}
while (filepathBufferSize == charactersWritten); // if this is true then filepathBuffer wasn't big enough
}
if (checkIfPathIsToAmnesia(filepathBuffer))
{
filepathLength = charactersWritten;
break;
}
queryAddress += mbi.RegionSize;
}
while (VirtualQueryEx(amnesiaHandle, (LPCVOID)queryAddress, &mbi, sizeof(mbi)) != 0);
if (filepathLength == (size_t)-1)
{
printf("couldn't find Amnesia.exe or Amnesia_NoSteam.exe memory location\n");
return false;
}
// finding the .text area
std::wstring filepathBufferCopy = filepathBuffer;
do
{
if (mbi.Protect == PAGE_EXECUTE_READ)
{
amnesiaMemoryLocation = queryAddress;
bytesLeft = mbi.RegionSize;
memoryOffset = queryAddress - pageSize; // this will overflow to 0 on the first call to getByte
return true;
}
if (queryAddress != 0) // this check gets rid of warning C6387
{
charactersWritten = GetMappedFileName(
amnesiaHandle,
(LPVOID)queryAddress,
&filepathBuffer[0],
filepathBufferSize
);
} | {
"domain": "codereview.stackexchange",
"id": 44742,
"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++, windows, assembly",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.