text stringlengths 1 2.12k | source dict |
|---|---|
c++, strings, immutability
//! Comparison operators (between basic_cstring and Char*)
template<typename Char, typename Traits, typename Allocator>
inline bool operator==(const basic_cstring<Char,Traits,Allocator> &lhs, const Char *rhs) noexcept {
return (lhs.compare(rhs) == 0);
}
template<typename Char, typename Traits, typename Allocator>
inline bool operator!=(const basic_cstring<Char,Traits,Allocator> &lhs, const Char *rhs) noexcept {
return (lhs.compare(rhs) != 0);
}
template<typename Char, typename Traits, typename Allocator>
inline bool operator<(const basic_cstring<Char,Traits,Allocator> &lhs, const Char *rhs) noexcept {
return (lhs.compare(rhs) < 0);
}
template<typename Char, typename Traits, typename Allocator>
inline bool operator<=(const basic_cstring<Char,Traits,Allocator> &lhs, const Char *rhs) noexcept {
return (lhs.compare(rhs) <= 0);
}
template<typename Char, typename Traits, typename Allocator>
inline bool operator>(const basic_cstring<Char,Traits,Allocator> &lhs, const Char *rhs) noexcept {
return (lhs.compare(rhs) > 0);
}
template<typename Char, typename Traits, typename Allocator>
inline bool operator>=(const basic_cstring<Char,Traits,Allocator> &lhs, const Char *rhs) noexcept {
return (lhs.compare(rhs) >= 0);
} | {
"domain": "codereview.stackexchange",
"id": 45135,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, strings, immutability",
"url": null
} |
c++, strings, immutability
//! Comparison operators (between Char * and basic_cstring)
template<typename Char, typename Traits, typename Allocator>
inline bool operator==(const Char *lhs, const basic_cstring<Char,Traits,Allocator> &rhs) noexcept {
return (rhs.compare(lhs) == 0);
}
template<typename Char, typename Traits, typename Allocator>
inline bool operator!=(const Char *lhs, const basic_cstring<Char,Traits,Allocator> &rhs) noexcept {
return (rhs.compare(lhs) != 0);
}
template<typename Char, typename Traits, typename Allocator>
inline bool operator<(const Char *lhs, const basic_cstring<Char,Traits,Allocator> &rhs) noexcept {
return (rhs.compare(lhs) > 0);
}
template<typename Char, typename Traits, typename Allocator>
inline bool operator<=(const Char *lhs, const basic_cstring<Char,Traits,Allocator> &rhs) noexcept {
return (rhs.compare(lhs) >= 0);
}
template<typename Char, typename Traits, typename Allocator>
inline bool operator>(const Char *lhs, const basic_cstring<Char,Traits,Allocator> &rhs) noexcept {
return (rhs.compare(lhs) < 0);
}
template<typename Char, typename Traits, typename Allocator>
inline bool operator>=(const Char *lhs, const basic_cstring<Char,Traits,Allocator> &rhs) noexcept {
return (rhs.compare(lhs) <= 0);
}
// template incarnations
typedef basic_cstring<char> cstring;
typedef basic_cstring<wchar_t> wcstring;
typedef basic_cstring<char>::basic_cstring_view cstring_view;
typedef basic_cstring<wchar_t>::basic_cstring_view wcstring_view;
} // namespace gto
namespace std {
//! Specializes the std::swap algorithm for std::basic_cstring.
template<typename Char, typename Traits, typename Allocator>
inline void swap(gto::basic_cstring<Char,Traits,Allocator> &lhs, gto::basic_cstring<Char,Traits,Allocator> &rhs) noexcept {
lhs.swap(rhs);
} | {
"domain": "codereview.stackexchange",
"id": 45135,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, strings, immutability",
"url": null
} |
c++, strings, immutability
//! Performs stream output on basic_cstring.
template<typename Char, typename Traits, typename Allocator>
inline basic_ostream<Char,Traits> & operator<<(std::basic_ostream<Char,Traits> &os, const gto::basic_cstring<Char,Traits,Allocator> &str) {
return operator<<(os, str.view());
}
//! The template specializations of std::hash for gto::cstring.
template<>
struct hash<gto::cstring> {
std::size_t operator()(const gto::cstring &str) const {
return hash<std::string_view>()(str.view());
}
};
//! The template specializations of std::hash for gto::wcstring.
template<>
struct hash<gto::wcstring> {
std::size_t operator()(const gto::wcstring &str) const {
return hash<std::wstring_view>()(str.view());
}
};
} // namespace std
``` | {
"domain": "codereview.stackexchange",
"id": 45135,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, strings, immutability",
"url": null
} |
c++, strings, immutability
Answer: In no particular order.
NUL-termination
The ASCII character with a value of 0 is the NUL character. C Strings are thus NUL-terminated strings. I would advise changing the comment 0-ended to NUL-terminated.
Public and Private API
The repeated switch between public and private declarations at the top of the class is fairly annoying. If possible, try to put first all public declarations (user API) and then all private ones. Worst comes to worst, an initial private section can be used.
The prefix_type and atomic_prefix_type have no reason to be public.
Size and Alignment assumptions
The memory layout you use makes a number of assumptions, for example that the alignment of Char is less than or equal to that of prefix_type, and that the size of prefix_type is equal to that of atomic_prefix_type.
Those are reasonable assumptions, but they ought to be checked.
You can add static_assert(alignof(Char) <= alignof(prefix_type)), etc... to validate (and document) each assumption that is made.
I recommend putting those static_assert where the assumptions are used, such as in the getPtrToCounter and getPtrToLength.
Do not worry about duplicated them. Any time an assumption is used, check the assumption. This allows locally reasoning that all assumptions are checked when reading the code.
Thread safety
Your use of atomics is correct, in fact it's even over the top.
By directly using = and ++/-- you are using the Sequentially Consistent memory ordering -- the strongest of all -- which is overkill here.
Since you have no synchronization with another piece of memory, you can instead use the Relaxed memory ordering.
Strict-aliasing woes.
Your definition of mEmpty violates strict-aliasing.
In general, you cannot store a value as type A, then read it as type B. An exception is made for char, signed char, unsigned char, and std::byte, but as your class is templated on Char you cannot rely on this -- and indeed it fails when used with wchar_t. | {
"domain": "codereview.stackexchange",
"id": 45135,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, strings, immutability",
"url": null
} |
c++, strings, immutability
Instead, you should be defining a struct with the exact layout that you want:
struct EmptyString { atomic_prefix_type r; prefix_type s; value_type z; }; | {
"domain": "codereview.stackexchange",
"id": 45135,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, strings, immutability",
"url": null
} |
c++, strings, immutability
static constexpr EmptyString mEmpty = {};
Weird mix of case style
In order to present a STL-like interface, your public interface uses snake_case.
Yet, your private interface uses camelCase.
The dissonance is annoying for the reader. Pick one, stick to it.
Allocation and deallocation
The getAllocatedLength function could benefit from a comment explaining what is going on, because that's quite unclear. It may be clever maths, if so I'm missing it. The obvious formula would be: 2 * sizeof(prefix_type) / sizeof(value_type) + sizeof(value_type) * (len + 1).
In allocate, you never check that n > len. On 32-bits platforms, with len close to the maximum, the computation in getAllocatedLength will overflow. You should at least assert against that.
allocate and deallocate are asymmetric: allocate just allocates, whereas deallocate both decrements the counter and deallocates. It would be better for deallocate just to deallocate, and to have a decrementRefCounter function instead.
Documentation
Your documentation comments are mostly pointless, either get rid of them, or make them useful.
For example, //! Default constructor. is useless. I can see perfectly in the signature that this is the default constructor, thank you very much. At the same time, there's important information that's not conveyed: that the default-constructed string is empty.
The same holds true for //! Constructor (and co), they're just paraphrasing the signature without providing any useful information.
Good documentation comments should: | {
"domain": "codereview.stackexchange",
"id": 45135,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, strings, immutability",
"url": null
} |
c++, strings, immutability
Clearly indicate the functionality, even if obvious. operator[](size_type pos) returns a reference to the character at index pos, not just any character. empty returns whether the string is empty (not just "test" it...).
Clearly indicate any pre-condition. The first //! Constructor requires that the string be NUL-terminated. operator[] requires that pos be within [0, length()] (and not [0, length())).
Clearly indicate any post-condition. The //! Default Constructor returns an empty string.
Clearly indicate what happens when a pre-condition is violated: is it undefined behavior? Is an exception thrown?
Examples:
//! Constructs an empty string.
basic_cstring() : basic_cstring(nullptr) {}
//! Returns a reference to the character at index `pos`.
//!
//! # Pre-conditions
//!
//! - `pos` must be in the `[0, length()]` range.
//!
//! # Undefined Behavior
//!
//! If `pos` is outside `length()`, Undefined Behavior occurs.
const_reference operator[](size_type pos) const { return mStr[pos]; } | {
"domain": "codereview.stackexchange",
"id": 45135,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, strings, immutability",
"url": null
} |
c++, strings, immutability
Noexcept
Mark noexcept functions that cannot throw an exception, such as your default constructor, operator[], etc... Some of your functions are marked, but not all that could be.
If and else.
If an if block ends with return, there is no need for an else. This will save you one degree of indentation, and make it clearer to the reader.
Also, even when an if has a single statement in its block, do use {} around it.
Front and back.
Your front and back functions throw an out_of_range exception, which is not the case of std::basic_string. I do prefer throwing, although it may affect performance.
Performance hint: even though it's getting better, inline throw statements tend to bloat the code of the functions they appear in. It is better to manually outline them behind functions that are marked as no-inline, cold, and no-return.
Prefer non-member non-friend functions
I advise you to read Monolith Unstrung, though at the same time I do understand wanting to provide as close to std::string as possible an interface.
I do note, however, that in such cases you may want to delegate to std::string-view more often, rather than re-implement the functionality yourself.
Free-functions and ADL
Your operator== and friends are declared in the global namespace, instead of being declared in the gto namespace. For ADL to find them, they need to be in the namespace of one of their arguments.
(Might be a copy/paste mistake? As I see the namespace being closed a second time afterwards)
Specialization
It is better to specialize std algorithms in the global namespace, rather than open the std namespace. The namespace you are in affects name-lookup, and you may accidentally refer to a std entity.
Specialization IS NOT Overloading
The definitions of swap and operator<< are NOT specializations, they're overloading.
They should be in the gto namespace, instead.
TODO
With regard to your todo list: | {
"domain": "codereview.stackexchange",
"id": 45135,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, strings, immutability",
"url": null
} |
c++, strings, immutability
The assumption should be encoded as static_assert, then you can be sure it either holds, or that the user will get a compile-time error on their weird platform.
__builtin_assume_aligned(...) may help indeed.
std::atomic is enough, your use of it is even overkill.
Atomic operations have two impacts on code:
They are slower than non-atomic operations in general, with a slight exception for pure reads/writes in non SeqCst mode on x86.
Writes imply cache invalidation on other cores.
Beware that benchmarks lie ;)
Conclusion
A fairly nice read, you did a good job overall! | {
"domain": "codereview.stackexchange",
"id": 45135,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, strings, immutability",
"url": null
} |
linux, shell, sh, docker
Title: Debian and Docker compose upgrade script, 2nd version
Question: As a continuation of this question, I would like a second review from you.
Here is the updated sh script:
#!/bin/sh
set -e
spath="/home/<user>/<dir>/"
sname="<scriptname>.sh"
if [ $# -eq 0 ]
then
sh "${spath}${sname}" "logging" 2>&1 | tee -a "${spath}log_$(date +%F_%T_%N).txt"
exit
fi
cd $spath
# This three commands for logging...
pwd
date
whoami
docker compose down
# To go sure, docker is down and file operations are complete
sleep 5
sudo sh -c "apt update && DEBIAN_FRONTEND=noninteractive apt upgrade -y && apt autoremove -y && apt autoclean"
# To go sure, upgrades are done
sleep 5
if [ -f /var/run/reboot-required ]
then
# To go sure, system is up again after reboot
at now + 2 minute -f "${spath}${sname}"
sudo reboot
else
docker compose pull
docker compose build --pull
docker compose up -d
# To go sure, docker is running again
sleep 5
docker system prune -a -f
# Just for information/debug logging purposes, everything is up
sleep 5
docker system df
docker stats --no-stream | sort -k 2
fi
The requirements are almost the same. I think it's safer to user sh instead of bash because I use the at command.
Answer: The base path and the name of the current script
I don't understand the purpose of these lines:
spath="/home/<user>/<dir>/"
sname="<scriptname>.sh"
From the rest of the script I'd guess it's the base path and name of the script. Instead of hardcoding, you could write like this:
spath=$(cd "$(dirname "$0")"; pwd)
sname=$(basename "$0") | {
"domain": "codereview.stackexchange",
"id": 45136,
"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": "linux, shell, sh, docker",
"url": null
} |
linux, shell, sh, docker
Double-quote variables on the command line
Unquoted variables on the command line are subject to word splitting and globbing by the shell. Most of the time it's not intended, therefore it's better to write cd "$spath" instead of cd $spath.
Even if you know for sure that in this use case $spath will not contain any characters that may lead to word splitting or globbing, it's a good habit to build.
More blank lines please
The script is a "wall of text".
Adding blank lines in between sections with tightly related commands would make it easier to read.
Avoid arbitrary sleep
Sleeping for some arbitrary amount of time and hoping that something is ready by the time the sleep ends is error prone.
It's better to think of some observable event to wait for.
For example, this code hopes that the container will be down after 5 minutes:
docker compose down
# To go sure, docker is down and file operations are complete
sleep 5
This will fail if sometimes it takes a bit longer, or if you increase the sleep, then sometimes it will be unnecessarily slow.
It would be better to sleep 1 in a loop until the container is actually down, and up to some maximum number of iterations.
Hint: use docker-compose ps -q <service_name> to check if the container is down.
Avoid sudo in scripts
After starting a script, I like to assume that I can step away for a coffee and it will be done by the time I'm back.
If the script has sudo in the middle, then I might not be there to enter a password.
I recommend to make it mandatory to run the script as root user.
That is, when $(id -u) is not 0, print a helpful message and exit 1.
You could add this check after the top part, right before the cd "$spath". | {
"domain": "codereview.stackexchange",
"id": 45136,
"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": "linux, shell, sh, docker",
"url": null
} |
python-3.x, algorithm, reinventing-the-wheel, graph, pathfinding
Title: The shortest path between airports
Question: Airlines need to provide their customers with flights to every corner, so they need an app that allows them to do so. The customer must be able to transfer when there is no direct connection.
The developer's task is to prepare the following functionalities:
selection of airport A and airport B
showing the shortest possible connection to a list of all airports
Note!
In the list of available connections, flights are performed in both directions, i.e. from ATH you can get to EDI and from EDI you can get to ATH
Here is my solution, I'm looking forward for some feedback, and obviously, better solutions!
data_set = (
['ATH','EDI'], ['ATH','GLA'], ['ATH','CTA'],
['BFS','CGN'], ['BFS','LTN'], ['BFS','CTA'],
['BTS','STN'], ['BTS','BLQ'],
['CRL','BLQ'], ['CRL','BSL'], ['CRL','LTN'],
['DUB','LCA'],
['LTN','DUB'], ['LTN','MAD'],
['LCA','HAM'],
['EIN','BUD'], ['EIN','MAD'],
['HAM','BRS'],
['KEF','LPL'], ['KEF','CGN'],
['SUF','LIS'], ['SUF','BUD'], ['SUF','STN'],
['STN','EIN'],['STN','HAM'], ['STN','DUB'], ['STN','KEF'])
airports = {}
class Airport:
def __init__(self, name):
self.name = name
self.con = []
def add_con(self, con):
if con not in self.con:
self.con.append(con)
else:
"already there"
def __str__(self):
con = [x.name for x in self.con]
return self.name + "\t" + " ".join(con)
def already_exist(name):
if name in airports.keys():
return True
return False
for x in data_set:
if not already_exist(x[0]):
airports[x[0]] = Airport(x[0])
if not already_exist(x[1]):
airports[x[1]] = Airport(x[1])
airports[x[0]].add_con(airports[x[1]])
airports[x[1]].add_con(airports[x[0]])
for key in airports.keys():
print(airports[key])
def get_shortest_path(A, B):
A,B = B, A
checked = []
path = [B]
lvl = 7
def find(A, B, lvl):
checked.append(A) | {
"domain": "codereview.stackexchange",
"id": 45137,
"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-3.x, algorithm, reinventing-the-wheel, graph, pathfinding",
"url": null
} |
python-3.x, algorithm, reinventing-the-wheel, graph, pathfinding
def find(A, B, lvl):
checked.append(A)
if lvl == 1: return
elif lvl > 1:
to_check = [a for a in A.con if a not in checked]
if to_check:
for x in to_check:
if x not in checked:
if x.name == B.name:
path.append(A)
return True
if find(x, B, lvl - 1):
path.append(A)
return True
find(A, B, lvl)
return path
path = get_shortest_path(airports['ATH'], airports['KEF'])
print([airport.name for airport in path])
Answer: data_set (which could get a better name) has inner lists when those should be inner tuples for immutability.
Airport needing to be a class is dubious.
con = [x.name for x in self.con] should have a generator () and not a list comprehension [].
Add PEP484 type hints.
This:
for key in airports.keys():
print(airports[key]) | {
"domain": "codereview.stackexchange",
"id": 45137,
"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-3.x, algorithm, reinventing-the-wheel, graph, pathfinding",
"url": null
} |
python-3.x, algorithm, reinventing-the-wheel, graph, pathfinding
seems like debug output and should be deleted.
lvl = 7 is concerning. Will your program still work for paths above seven edges? It seems not: try for example ATH -> BRS, which for your implementation outputs only ['ATH'].
You recurse on find(). For several reasons, Python is not good at recursion: it's slow since there is no tail optimisation, and the Python default stack is very shallow so it's easy for a recursive algorithm to overflow it.
There are stock algorithms in standard (albeit not built-in) libraries that offer various levels of increased efficiency and convenience. scipy.sparse has a good one. It is able to pre-calculate a predecession matrix that can then be used to find any shortest path in linear time, paying for the more difficult calculation up front. This would be appropriate for (say) a web server where the airport connections do not change often, but there are hundreds of requests a second for shortest flight path. If your use case is expected to remain as-is with a single path request, you can modify the call to shortest_path only supplying the endpoints of interest. If you ever have uni-directional flight paths or want to optimise for shortest land distance covered, scipy will make it easy.
Suggested
from itertools import chain
from typing import Iterator
import numpy as np
import scipy.sparse | {
"domain": "codereview.stackexchange",
"id": 45137,
"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-3.x, algorithm, reinventing-the-wheel, graph, pathfinding",
"url": null
} |
python-3.x, algorithm, reinventing-the-wheel, graph, pathfinding
import numpy as np
import scipy.sparse
def load_connections() -> tuple[
tuple[str, ...], # airport names, sorted alphabetically
dict[str, int], # airport index by name
scipy.sparse.csr_matrix, # connection adjacencies, symmetric
]:
connection_names = (
('ATH', 'EDI'), ('ATH', 'GLA'), ('ATH', 'CTA'),
('BFS', 'CGN'), ('BFS', 'LTN'), ('BFS', 'CTA'),
('BTS', 'STN'), ('BTS', 'BLQ'),
('CRL', 'BLQ'), ('CRL', 'BSL'), ('CRL', 'LTN'),
('DUB', 'LCA'),
('EIN', 'BUD'), ('EIN', 'MAD'),
('HAM', 'BRS'),
('KEF', 'LPL'), ('KEF', 'CGN'),
('LTN', 'DUB'), ('LTN', 'MAD'),
('LCA', 'HAM'),
('STN', 'EIN'), ('STN', 'HAM'), ('STN', 'DUB'), ('STN', 'KEF'),
('SUF', 'LIS'), ('SUF', 'BUD'), ('SUF', 'STN'),
)
airport_names = tuple(sorted(set(chain.from_iterable(connection_names))))
airport_indices = {
name: i for i, name in enumerate(airport_names)
}
N = len(airport_names)
sources, dests = [], []
for source, dest in connection_names:
sources.append(airport_indices[source])
dests.append(airport_indices[dest])
connections = scipy.sparse.csr_matrix(
(
np.ones(len(sources), dtype=np.int32), # All connections have equal weight
(sources, dests),
),
shape=(N, N),
)
# All connections have the same weight in the other direction
connections += connections.T
return airport_names, airport_indices, connections
airport_names, airport_indices, connections = load_connections()
def load_predecessors() -> np.ndarray:
distances, predecessors = scipy.sparse.csgraph.shortest_path(
csgraph=connections, directed=False, unweighted=True, return_predecessors=True,
)
return predecessors
predecessors = load_predecessors() | {
"domain": "codereview.stackexchange",
"id": 45137,
"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-3.x, algorithm, reinventing-the-wheel, graph, pathfinding",
"url": null
} |
python-3.x, algorithm, reinventing-the-wheel, graph, pathfinding
predecessors = load_predecessors()
def get_path_by_index(source: int, dest: int) -> Iterator[int]:
while source != dest:
yield dest
dest = predecessors[source, dest]
yield source
def get_path(source: str, dest: str) -> Iterator[str]:
for index in get_path_by_index(
airport_indices[source],
airport_indices[dest],
):
yield airport_names[index]
if __name__ == '__main__':
for source in airport_names:
print(' <- '.join(get_path(source, dest='ATH')))
Output
ATH
ATH <- CTA <- BFS
ATH <- CTA <- BFS <- LTN <- CRL <- BLQ
ATH <- CTA <- BFS <- CGN <- KEF <- STN <- HAM <- BRS
ATH <- CTA <- BFS <- LTN <- CRL <- BSL
ATH <- CTA <- BFS <- LTN <- CRL <- BLQ <- BTS
ATH <- CTA <- BFS <- LTN <- MAD <- EIN <- BUD
ATH <- CTA <- BFS <- CGN
ATH <- CTA <- BFS <- LTN <- CRL
ATH <- CTA
ATH <- CTA <- BFS <- LTN <- DUB
ATH <- EDI
ATH <- CTA <- BFS <- LTN <- MAD <- EIN
ATH <- GLA
ATH <- CTA <- BFS <- CGN <- KEF <- STN <- HAM
ATH <- CTA <- BFS <- CGN <- KEF
ATH <- CTA <- BFS <- LTN <- DUB <- LCA
ATH <- CTA <- BFS <- CGN <- KEF <- STN <- SUF <- LIS
ATH <- CTA <- BFS <- CGN <- KEF <- LPL
ATH <- CTA <- BFS <- LTN
ATH <- CTA <- BFS <- LTN <- MAD
ATH <- CTA <- BFS <- CGN <- KEF <- STN
ATH <- CTA <- BFS <- CGN <- KEF <- STN <- SUF | {
"domain": "codereview.stackexchange",
"id": 45137,
"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-3.x, algorithm, reinventing-the-wheel, graph, pathfinding",
"url": null
} |
python-3.x, algorithm, reinventing-the-wheel, graph, pathfinding
Note that this "tells the truth" because the predecession matrix defines paths in reverse order. However, since your adjacency is symmetric you could just lie and supply the source for the destination and the destination for the source when iterating the path, and you'll get a forward path at no extra cost.
Alternate adjacency literals
An alternate and more condensed way of expressing your adjacency literals is to use a dictionary of tuples:
def load_connections() -> tuple[
tuple[str, ...], # airport names, sorted alphabetically
dict[str, int], # airport index by name
scipy.sparse.csr_matrix, # connection adjacencies, symmetric
]:
connection_names = {
'ATH': ('EDI', 'GLA', 'CTA'),
'BFS': ('CGN', 'LTN', 'CTA'),
'BTS': ('STN', 'BLQ'),
'CRL': ('BLQ', 'BSL', 'LTN'),
'DUB': ('LCA',),
'EIN': ('BUD', 'MAD'),
'HAM': ('BRS',),
'KEF': ('LPL', 'CGN'),
'LTN': ('DUB', 'MAD'),
'LCA': ('HAM',),
'STN': ('EIN', 'HAM', 'DUB', 'KEF'),
'SUF': ('LIS', 'BUD', 'STN'),
}
airport_names = tuple(sorted({
*connection_names.keys(),
*chain.from_iterable(connection_names.values()),
}))
airport_indices = {
name: i for i, name in enumerate(airport_names)
}
N = len(airport_names)
sources, dests = [], []
for source, destinations in connection_names.items():
for dest in destinations:
sources.append(airport_indices[source])
dests.append(airport_indices[dest])
connections = scipy.sparse.csr_matrix(
(
np.ones(len(sources), dtype=np.int32), # All connections have equal weight
(sources, dests),
),
shape=(N, N),
)
# All connections have the same weight in the other direction
connections += connections.T
return airport_names, airport_indices, connections | {
"domain": "codereview.stackexchange",
"id": 45137,
"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-3.x, algorithm, reinventing-the-wheel, graph, pathfinding",
"url": null
} |
c++, c++11, multithreading
Title: Multithreaded disk scan
Question: I'm writing an application to compare and sync folders on a disks. Scanning the contents of folders is performed in separate threads. I wrote a class to manage scan threads.
The main application class inherits from this class.
The application is built and at first glance works without errors.
But I'm new to writing multithreaded code and I'm not sure I did everything right. Please look at my thread manager class. Is everything right there? Are there any problems? If so, how can they be corrected? Can it be made better?
Added on October 12th: I forgot to mention that my application is based on event loop. The main thread cannot wait the worker threads until they finish. Instead I use the callback function which puts a message to the event queue.
Header file:
#pragma once
#include <atomic>
#include <thread>
#include <mutex>
// This class runs two time-consuming file scanning jobs in separate threads.
// To implement specific scanning jobs tasks, inherit from this class.
class ThreadManager {
public:
ThreadManager() = default;
ThreadManager(const ThreadManager&) = delete;
ThreadManager& operator=(const ThreadManager&) = delete;
~ThreadManager();
// Start scan jobs.
void startScan(const std::wstring& localDir, const std::wstring& sharedDir);
// Stop scan jobs while they are running without waiting for results.
void stopScan();
// Scan worker functions.Implement them in the descendant class.
virtual bool scanLocal(const std::wstring& localDir, const std::atomic<bool>& stopScan, std::string& errorMessage) = 0;
virtual bool scanShared(const std::wstring& sharedDir, const std::atomic<bool>& stopScan, std::string& errorMessage) = 0;
// A callback function that is called when both scanning tasks are completed or stopped.
virtual void scanFinished(bool success, const std::string& errorMessage) = 0; | {
"domain": "codereview.stackexchange",
"id": 45138,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++11, multithreading",
"url": null
} |
c++, c++11, multithreading
private:
void freeThreadsResources();
void scanLocalWrapper(const std::wstring& localDir);
void scanSharedWrapper(const std::wstring& sharedDir);
private:
std::atomic<bool> m_stopScan;
std::mutex m_scanStateMutex;
std::thread m_localScanThread;
std::thread m_sharedScanThread;
bool m_localRunning = false;
bool m_sharedRunning = false;
std::mutex m_localResultMutex;
bool m_localSuccess = false;
std::string m_localErrorMessage;
std::mutex m_sharedResultMutex;
bool m_sharedSuccess = false;
std::string m_sharedErrorMessage;
};
CPP file:
#include "ThreadManager.h"
#include <sstream>
ThreadManager::~ThreadManager()
{
freeThreadsResources();
}
void ThreadManager::startScan(const std::wstring& localDir, const std::wstring& sharedDir)
{
freeThreadsResources();
std::lock_guard lock(m_scanStateMutex);
m_stopScan.store(false, std::memory_order_seq_cst);
m_localRunning = true;
m_sharedRunning = true;
m_localScanThread = std::thread(&ThreadManager::scanLocalWrapper, this, localDir);
m_sharedScanThread = std::thread(&ThreadManager::scanSharedWrapper, this, sharedDir);
}
void ThreadManager::stopScan()
{
m_stopScan.store(true, std::memory_order_seq_cst);
}
void ThreadManager::freeThreadsResources()
{
if (m_localScanThread.joinable())
m_localScanThread.join();
if (m_sharedScanThread.joinable())
m_sharedScanThread.join();
}
static std::string composeErrorMessage(const std::string& localErrorMessage, const std::string& sharedErrorMessage)
{
std::ostringstream result;
result << localErrorMessage;
if (!sharedErrorMessage.empty())
{
if (!localErrorMessage.empty())
result << std::endl;
result << sharedErrorMessage;
}
return result.str();
} | {
"domain": "codereview.stackexchange",
"id": 45138,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++11, multithreading",
"url": null
} |
c++, c++11, multithreading
void ThreadManager::scanLocalWrapper(const std::wstring& localDir)
{
std::lock_guard localResultLock(m_localResultMutex);
m_localSuccess = scanLocal(localDir, m_stopScan, m_localErrorMessage);
if (!m_localSuccess)
stopScan();
std::lock_guard scanLock(m_scanStateMutex);
m_localRunning = false;
if (!m_sharedRunning)
{
std::lock_guard sharedResultLock(m_sharedResultMutex);
auto errorMessage = composeErrorMessage(m_localErrorMessage, m_sharedErrorMessage);
scanFinished(m_localSuccess && m_sharedSuccess, errorMessage);
}
}
void ThreadManager::scanSharedWrapper(const std::wstring& sharedDir)
{
std::lock_guard sharedResultLock(m_sharedResultMutex);
m_sharedSuccess = scanShared(sharedDir, m_stopScan, m_sharedErrorMessage);
if (!m_sharedSuccess)
stopScan();
std::lock_guard scanLock(m_scanStateMutex);
m_sharedRunning = false;
if (!m_localRunning)
{
std::lock_guard localResultLock(m_localResultMutex);
auto errorMessage = composeErrorMessage(m_localErrorMessage, m_sharedErrorMessage);
scanFinished(m_localSuccess && m_sharedSuccess, errorMessage);
}
}
Answer: I was in the middle of writing a review when one was accepted. I had only finished the design review, and was working on the actual code review. Rather than throw it all away, I’ll post the design review, and a few comments of what would have come up in the code review.
Design review
As I understand the design, the intention is for a user to derive this class, supply their own scanLocal(), scanShared(), and scanFinished() functions, and then use it like:
auto scanner = type_derived_from_thread_manager{};
scanner.startScan(); | {
"domain": "codereview.stackexchange",
"id": 45138,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++11, multithreading",
"url": null
} |
c++, c++11, multithreading
… correct?
Okay, before I start the review, I have to ask… C++11? Really? This is 2023! I would expect, at least, a bare minimum of C++17. That’s the version all major compilers default to. Concurrency support is barely functional in C++11. (It’s still not perfect as of C++20—executors is really holding everything up—but it’s much better than it was in C++11.)
Alright, so, I am not a fan of this interface. It’s extremely convoluted, and very hard to use… and very easy to misuse. Suppose I just want to do a scan and literally nothing else. Could I do this?
auto main() -> int
{
auto scanner = type_derived_from_thread_manager{};
scanner.startScan();
std::cout << "scan done (successfully?)";
}
That’s already two lines for one operation, but more importantly… that won’t work. Because startScan() does indeed start the scan… but the interface provides no way to know when the scan finishes, except that the destructor completes. So if I wanted to print a completion message, I’d have to do:
auto main() -> int
{
{
auto scanner = type_derived_from_thread_manager{};
scanner.startScan();
}
std::cout << "scan done (successfully?)";
}
Except what if I want to know whether the scan succeeded or not? There’s just no way to find out. Presumably that would have to be dealt with in the scanFinished() callback… but that is not where one would logically want to deal with success or failure; you deal with the success/failure of an operation in the code that called the operation… that’s why operations return error status to the caller, or unwind the stack with an exception, rather than everything returning void or being noexcept and handling errors internally.
At best you would have to do something like:
auto main() -> int
{
auto result = bool{};
{
auto scanner = type_derived_from_thread_manager{&result};
scanner.startScan();
} | {
"domain": "codereview.stackexchange",
"id": 45138,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++11, multithreading",
"url": null
} |
c++, c++11, multithreading
if (result)
std::cout << "scan succeeded";
else
std::cout << "scan failed";
}
… with the derived type properly setting that flag in scanFinished(). It’s a spaghetti mess of responsibilities.
Also, it’s wildly over-complicated, with no fewer than three mutexes, locks-within-locks, and, most dangerously, callbacks into unknown code while holding locks… which you should never, ever do. To put it bluntly, if it appears to be deadlock-free, that’s only because the most important parts of the code are missing. When those abstract member functions are defined, it’s quite likely there will be data race problems, and maybe even deadlocks.
I would suggest that the problems here stem from the mistake of thinking of this problem in terms of threads. It is better to think in terms of tasks.
What you have here are two tasks—the “scan local” and “scan shared” tasks—that are presumably independent, and that you would like to run concurrently, and wait for both to finish.
In other words, something more like:
// If you want to return actual result data, then replace void in the
// promise with the result data type.
auto do_scan(std::wstring dir, std::promise<void> promise)
{
try
{
// do whatever you need to do here for the scan
//
// throw any exception on error
promise.set_value_at_thread_exit();
}
catch (...)
{
promise.set_exception_at_thread_exit(std::current_exception());
}
}
auto scan(std::wstring dir) -> std::future<void>
{
auto promise = std::promise<void>{};
auto future = promise.get_future();
auto thread = std::thread{do_scan, std::move(dir), std::move(promise)};
thread.detach(); // this is fine, because we are using promise with
// set_value_at_thread_exit()
return future;
}
auto main() -> int
{
using namespace std::literals;
auto const local_dir = L"local"s
auto const shared_dir = L"shared"s | {
"domain": "codereview.stackexchange",
"id": 45138,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++11, multithreading",
"url": null
} |
c++, c++11, multithreading
auto const local_dir = L"local"s
auto const shared_dir = L"shared"s
// Start all the scans, and collect the result futures.
auto results = std::array<std::future<void>, 2>{
scan(local_dir),
scan(shared_dir)
};
// ... do any other work you want here...
// Wait for all the results.
std::for_each(results.begin(), results.end(),
[](std::future<void>& result) { result.wait(); }
);
// Report results.
std::cout << "all scans finished:\n";
auto report = [](char const* which, std::future<void>& result)
{
try
{
result.get();
std::cout << " " << which << " scan succeeded\n";
}
catch (...)
{
std::cout << " " << which << " scan failed\n";
}
};
report("local", result[0]);
report("shared", result[1]);
}
The above assumes the local and shared scanning algorithms are identical… only the directory is different… but if they are not, it’s a small change. If you want to add cancellation, that’s also not hard.
Unless you are doing a large amount of scans, this should suffice. If you are doing a large amount of scans, then you will need a thread pool and a task queue. That’s a bit more complicated, but not by much. The key API functionality would probably look something like:
// This could create a thread pool and task queue, and pop tasks off the
// queue to run in the threads until done.
auto tasks = task_manager{};
// These return futures with the results of the tasks.
auto result_local = tasks.enqueue(scan_local, local_dir);
auto result_shared = tasks.enqueue(scan_shared, shared_dir);
// Now .wait() or .get() those results as you please. | {
"domain": "codereview.stackexchange",
"id": 45138,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++11, multithreading",
"url": null
} |
c++, c++11, multithreading
// Now .wait() or .get() those results as you please.
And the point remains: you should think in terms of tasks… not threads. You’ll notice in the code above that there is not a single mutex or lock in sight, and zero chance of deadlock (unless the scan functions are not actually independent). The interface is almost impossible to misuse.
The standard library futures are still very simplistic—we are waiting on executors before improving them—but there are other libraries out there with better futures. Still, even the standard futures, limited as they are, are far easier to compose than threads.
Even if you want to keep your interface, startScan() should return a future so calling code can know when it’s done, and can query whether it succeeds or not:
auto main() -> int
{
auto scanner = type_derived_from_thread_manager{};
try
{
auto result = scanner.startScan().get();
std::cout << "scan succeeded";
}
catch (std::exception const& x)
{
std::cout << "scan failed: " << x.what();
}
}
The moral of the story is: don’t think in terms of threads, think in terms of tasks. You get concurrency almost transparently by returning futures from task functions. And even though standard futures are clunky, there are still far more composable than threads.
Code review
The code review wasn’t finished, but here are some things I was going to mention:
There is quite a bit of repetition and manual unrolling of what should probably be loops.
For example, having two separate data members for two threads will make modifying to support a third thread difficult; had you used a container to hold the threads, adding support for a third thread would be trivial.
There are way too many locks, and they are held for way too long, including locks within locks. | {
"domain": "codereview.stackexchange",
"id": 45138,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++11, multithreading",
"url": null
} |
c++, c++11, multithreading
There are way too many locks, and they are held for way too long, including locks within locks.
For example, in startScan(), the m_scanStateMutex should be unlocked as soon as m_localRunning and m_localRunning are set.
In scanLocalWrapper(), you lock m_localResultMutex and hold it for the whole function, including a dive into a user-supplied callback (!!!)… and then you lock m_scanStateMutex and, conditionally, m_sharedResultMutex too!
In scanLocalWrapper(), you lock m_localResultMutex, then m_sharedResultMutex. In scanSharedWrapper(), you lock m_sharedResultMutex, then m_localResultMutex. Normally this would be deadlock 101… but you may be saved by the fact that you lock m_scanStateMutex between, and do the dance with the two “running” flags. Note that I said may; I was in the process of reasoning this out, but never finished.
There is no consideration whatsoever of exceptions, and that creates a number of problems.
For example, what if the second thread construction fails in startScan()?
If any exceptions are thrown anywhere in the “wrapper” functions—including any exceptions that escape from the user-supplied callbacks—you will not only not get any notice of a scan failure (because scanFinished() probably won’t get called), you’ll probably get a straight-up crash (via terminate()). | {
"domain": "codereview.stackexchange",
"id": 45138,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++11, multithreading",
"url": null
} |
powershell
Title: Powershell Export function to create environment variables with bash syntax
Question: A lot of the time when working in DevOps, documentation and code snippets from colleagues will be based on bash. Most of those same commands work seamlessly in PowerShell; but setting environment variables doesn't; e.g. export DEMO_CLIENT_ID="ff3b7b84-e041-4e76-993e-239930808aa7".
I've written the below function so I can more easily just copy-paste these snippets and have them work without needing a rewrite:
Function Export {
$regex = [System.Text.RegularExpressions.Regex]::new('^\s*([^=]+?)\s*=(.*)$')
$result = $regex.Match(($args -join ' '))
if (!$result.Success) {
throw "Could not set an environment variable based on [$($args -join ' ')]"
}
[Environment]::SetEnvironmentVariable($result.Groups[1].Value, $result.Groups[2].Value)
}
This works well for most real world examples I've hit so far... but I'm sure there are gotchas lurking (e.g. I know that multiple spaces will be squashed to a single space when the split arguments are re-joined... which may be an issue in some scenarios).
Is there a better approach to this, or are there improvements I can make to avoid this and similar/unforeseen pitfalls?
Note: I know the function name doesn't meet best practices (i.e. verb-noun naming)... My only use case for this function is to simulate the export command; so I figured giving it a verb noun name and then aliasing that was just adding complexity with no benefit.
Answer:
The PowerShell-idiomatic approach is to:
Define a command (function) that adheres to PowerShell's <verb>-<noun> naming convention, using one of the approved verbs.
Use an alias to provide another, typically shorter, name for the command, that isn't bound by this convention. | {
"domain": "codereview.stackexchange",
"id": 45139,
"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": "powershell",
"url": null
} |
powershell
Using -split, the string splitting operator, limiting the number of resulting tokens to 2, allows you to split each name-value pair into its constituent parts, and the Env: drive can be used to define a process-scoped environment variable for each pair.
Given that the export builtin in POSIX-compatible shells such as Bash accepts multiple <name>=<value> pairs (e.g. export FOO='bar none' BAZ=2), so does the function below.
Caveat: POSIX-compatible shells allow defining environment variables without a value (e.g. export FOO), which PowerShell and .NET do not support: assigning $null or '' invariably undefines (removes) an environment variable there.
Therefore, the function below only accepts <name>=<value> pairs, and reports a non-terminating error if a given argument lacks an = or a value thereafter.
Set-Alias export Set-EnvironmentVariableByNameValuePair
function Set-EnvironmentVariableByNameValuePair {
param(
[Parameter(Mandatory, ValueFromPipeline, ValueFromRemainingArguments)]
[string[]] $NameValuePair
)
process {
foreach ($pair in $NameValuePair) {
$name, $value = $pair -split '=', 2
if (-not $name -or -not $value) { Write-Error "Not in <name>=<value> format: `"$pair`". For technical reasons, you must supply a value."; continue }
Set-Content Env:$name $value
}
}
}
Note:
The above is more permissive than POSIX-compatible shells with respect to the names of environment variables - even though names that do not adhere to the constraints spelled out below are supported by the underlying platforms themselves.
If you want to enforce the same name constraints that Bash does, insert the following before the Set-Content call:
if ($name -notmatch '^[a-z_]\w*$') { Write-Error "Invalid name: $name"; continue }
See also: | {
"domain": "codereview.stackexchange",
"id": 45139,
"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": "powershell",
"url": null
} |
powershell
See also:
GitHub issue #3316, which asks for PowerShell to support the / something like the concise syntax that POSIX-compatible shells offer for defining child-process-scoped environment variables (e.g. FOO='bar none' BAZ=2 some_utility ...) | {
"domain": "codereview.stackexchange",
"id": 45139,
"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": "powershell",
"url": null
} |
zsh
Title: My ~/.zprofile (paths, configuration and env variables)
Question: This is my .zprofile, it recently got nuked so I remade it. I made it clearer and better then my previous .zprofile and then I heard about this site so I want to know how can I improve this code.
# Setting PATH for Python 3.11
export PATH="/Library/Frameworks/Python.framework/Versions/3.11/bin:$PATH"
alias python=python3
export PYTHONPATH="/Users/jfami/Desktop:/Users/jfami/Desktop.noml:$PYTHONPATH"
# Setting PATH for Demonal
export PATH="/Users/jfami/Library/Demonal/bin:$PATH"
# Setting PATH for Sublime Text
export PATH="/Applications/Sublime Text.app/Contents/SharedSupport/bin:$PATH"
# Moving to a better directory
cd Desktop
# Aliases!
alias noml="python ~/Desktop/noml/app.py"
alias deppy="python ~/Desktop/deppy.py"
alias pylect="python ~/pylect/pylect-env/.pylect.py"
# ENV variables
export MYSQL_PASSWORD=$(cat MYSQL_PASSWORD)
# Configuration
termdx tebwhite > /dev/null 2>&1
termdx tefblack > /dev/null 2>&1
deppy cache-clear
demonal project select playground
# Print the art
echo -e "\e[0;35m<------------------------------------> \e[0m"
echo -e "\e[0;35mThe Terminal \e[0m"
echo -e "\e[0;35m<------------------------------------> \e[0m"
echo -e "\e[0;33mOS: $(uname)\e[0m"
echo -e "\e[0;36mUsername: $(whoami)\e[0m"
echo -e "\e[0;32mBrowser: $('/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' --version)\e[0m"
Answer: Do you really want all Python programs to look first in these directories?
export PYTHONPATH="/Users/jfami/Desktop:/Users/jfami/Desktop.noml:$PYTHONPATH"
It might be appropriate to create very small shell scripts (which set the environment and exec the Python interpreter) for the few Python programs that actually use that path, and put them in $HOME/bin (or some other suitable place on your $PATH).
Don't do this:
export MYSQL_PASSWORD=$(cat MYSQL_PASSWORD) | {
"domain": "codereview.stackexchange",
"id": 45140,
"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": "zsh",
"url": null
} |
zsh
Don't do this:
export MYSQL_PASSWORD=$(cat MYSQL_PASSWORD)
That's exposing your password in the environment variables of every process you run from this shell. It's all too easy to leak that information to untrusted programs or other users.
You might think you only ever log in from one kind of terminal, but one day you'll find these hard-coded escape sequences a nuisance:
echo -e "\e[0;35m<------------------------------------> \e[0m"
Instead, use tput to generate the correct codes for your actual $TERM if they exist. | {
"domain": "codereview.stackexchange",
"id": 45140,
"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": "zsh",
"url": null
} |
linux, shell, sh, jq
Title: The Blacklist -- Follow-Up 2: Electric Boogaloo
Question: One of my main goals regarding this script has been to figure out a way to use the "adblock.sources" file available on its main repository and not my fork. That version has some syntax issues with its JSON, preventing it from being directly piped into jq.
After some research, I came across the jq -n -f {file} command that successfully read in the ill-formatted JSON! I have a couple questions on this feature and one on the sed command.
Is jq -n -f {file} being used properly?
Can the two jq commands be blended into one command?
Can the two sed parameters be blended into one parameter?
#!/bin/sh
set -eu
sources=$(mktemp)
trap 'rm "$sources"' EXIT
curl -s -o "$sources" https://raw.githubusercontent.com/openwrt/packages/master/net/adblock/files/adblock.sources
jq -n -f "$sources" | jq -r 'keys[] as $k | [$k, .[$k].url, .[$k].rule] | @tsv' |
while IFS=$'\t' read key url rule; do
case $key in
gaming | oisd_basic | yoyo )
# Ignore these sources:
# "gaming" blocks virtually all gaming servers
# "oisd_basic" is included in "oisd_full"
# "yoyo" is included in "stevenblack"
;;
* )
curl -s "$url" |
case $url in
*.tar.gz) tar -xOzf - ;;
*) cat ;;
esac | gawk --sandbox -- "$rule"
;;
esac
done | sed -e 's/\r//g' -e 's/^/0.0.0.0 /' | sort -u >| the_blacklist.txt
# use sort over gawk to merge sort multiple temp files instead of using up limited memory
Answer: You might want to check again the link you've provided: on 2023-10-12, it is strictly valid JSON and as such you can remove the jq -n -f part completely. | {
"domain": "codereview.stackexchange",
"id": 45141,
"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": "linux, shell, sh, jq",
"url": null
} |
linux, shell, sh, jq
That being said, yes, if it worked for you, you were probably using jq -n -f correctly. The idea behind this workaround is the following: you are telling jq to ignore its input (-n), thereby not using its parser for data, and to read the filter to apply from your file (-f). Since jq's parser for filters is much more permissive than the one for data (e.g. since the filter language accepts #-style comments, you could use this to parse json data with #-style comments, or with unquoted identifiers -- see here), you can use this to obtain correct input from nearly-correct input. Note that this will not always work though, as "nearly correct" is defined as what the filter parser accepts.
Yes, with some modification of the input file of the first command. Because in the jq -n -f command the filter is read from a file, and you use the filter to define the data, you can simply append the actual filter you're using at the end of the json data and use that for a single pass, with jq -n -r -f:
In your "$sources" file:
{ nearly-json data ...} | keys[] as $k | [$k, .[$k].url, .[$k].rule] | @tsv
You can either modify the "$sources" file after curl-ing, or use the fact that jq -f allows - as a filename to point to standard input, and construct the desired string beforehand in a pipe.
Yes as well. Sed allows usage of ; to separate commands in scripts, so your above command can be written sed -e 's/\r//g; s/^/0.0.0.0 /'.
One final comment: when writing shell scripts, especially involved ones, it is useful to have shellcheck running in your editor. In your case, it gives the following two (useful) warnings:
shellcheck blacklist.sh
In foo.sh line 11:
while IFS=$'\t' read key url rule; do
^---^ SC3003 (warning): In POSIX sh, $'..' is undefined.
^--^ SC2162 (info): read without -r will mangle backslashes. | {
"domain": "codereview.stackexchange",
"id": 45141,
"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": "linux, shell, sh, jq",
"url": null
} |
linux, shell, sh, jq
For more information:
https://www.shellcheck.net/wiki/SC3003 -- In POSIX sh, $'..' is undefined.
https://www.shellcheck.net/wiki/SC2162 -- read without -r will mangle backslashes. | {
"domain": "codereview.stackexchange",
"id": 45141,
"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": "linux, shell, sh, jq",
"url": null
} |
javascript, datetime
Title: Convert durations to a single unit
Question: In the codebase I inherited, I have this function which converts a number and unit into milliseconds:
function convertToMs(duration){
const matcher = new RegExp(/-?(\d+)(ms|[smhd])/);
const matches = matcher.exec(duration);
const digit = Number(matches[1]);
const suffix = matches[2];
let milliSeconds = digit;
switch(suffix) {
case 'd': milliSeconds *= 24;
case 'h': milliSeconds *= 60;
case 'm': milliSeconds *= 60;
case 's': milliSeconds *= 1000;
}
return milliSeconds;
}
console.log(`1s: ${convertToMs('1s')}`);
console.log(`3s: ${convertToMs('3s')}`);
console.log(`5m: ${convertToMs('5m')}`);
console.log(`1h: ${convertToMs('1h')}`);
console.log(`2d: ${convertToMs('2d')}`);
I'm especially concerned about the part that I thought was cool, but at the same time feels like it's using a side effect to achieve something; I am not sure if that's a good practice:
switch(suffix) {
case 'd': milliSeconds *= 24;
case 'h': milliSeconds *= 60;
case 'm': milliSeconds *= 60;
case 's': milliSeconds *= 1000;
}
Here, a number is being converted to milliseconds based on the suffix. The case rolls over into (all) the next case(s) to convert into milliseconds. Do you think that's okay?
Answer: To address your specific concern, it's normal to highlight that fall-through to the next case is intentional, e.g. with a comment:
case 'd': milliSeconds *= 24; /* FALLTHROUGH */
case 'h': milliSeconds *= 60; /* FALLTHROUGH */
case 'm': milliSeconds *= 60; /* FALLTHROUGH */
case 's': milliSeconds *= 1000; | {
"domain": "codereview.stackexchange",
"id": 45142,
"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, datetime",
"url": null
} |
javascript, datetime
The specific comment I've used is recognised by some compilers of related languages to silence a warning about unintended fall-through.
I'd consider adding case 'ms': /* no action needed */' to show explicitly that every match is handled. And perhaps even a default so that if the regex is extended to support, say, "weeks", we're forced to handle that change rather than silently treating it the same as milliseconds.
Other problems in this function:
digit is poorly named, since several digits may be matched.
If the regular expression doesn't match, then matches won't have the values we're looking for - we need a reasonable error action here.
Negative durations lose their - sign, becoming positive ones. None of the test cases are negative, so this isn't caught. | {
"domain": "codereview.stackexchange",
"id": 45142,
"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, datetime",
"url": null
} |
python, python-3.x, console, authentication
Title: A Python terminal
Question: This is the code for Pylect, a Python terminal I worked on a while ago which also caused my Desktop to get destroyed because of bad code. I use it infrequently but I would like a review for the code since this is a bit larger project that has span multiple months so there is some unclear bad code hidden in there likely.
Pylect is a REPL in which you provide Python code and Pylect executes the code and so on.
You can pass flags which are:
--name | Changes the name of the terminal.
--modules | Imports the comma-separated list of modules.
--dev | Shows debugging messages.
There are custom commands that Pylect has beginning with .:
.imports | Shows the imported modules.
.history | Shows the history so far.
.history prev | Shows the last item in the history.
.exit-env | Exits Pylect.
.clear-env | Clears all files in the Pylect folder except the Python files needed for Pylect.
There are also other things for fun (import ., import cake, import thanks, raise PylectError). 0.1+0.2 prints 0.3 is there because Python itself does the calculation wrong and there's also a reminder when I forgot the . before exit-env.
There is also a security feature where it has you type a password to access Pylect if there is a password. You can create a password, edit the password, and even remove the password through another program.
There is a configuration program for switching Pylect versions easily.
All text files involved:
.pylect.password.txt - Has the password.
.pylect.aliasversion.txt - Has the version which will be aliased to assuming that the .zprofile actually uses it for aliasing of course.
~/pylect/pylect1.1/.pylect.py
try:
import getpass
pw = open("/Users/jfami/pylect/.pylect.password.txt", "r").read()
gpw = getpass.getpass(prompt="Password: ")
if str(gpw) == str(pw):
invalid = False
pass
else:
print("Invalid password")
invalid = True
except:
invalid = False
pass | {
"domain": "codereview.stackexchange",
"id": 45143,
"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, console, authentication",
"url": null
} |
python, python-3.x, console, authentication
if invalid == True:
quit()
import sys, os, platform
from os import system as shell
modulenames = set(sys.modules) & set(globals())
allmodules = [sys.modules[name] for name in modulenames]
if "--dev" in sys.argv:
dev = True
else:
dev = False
if "--name" in sys.argv:
try:
if dev: print(f"[Pylect] name = {sys.argv[sys.argv.index('--name')+1]}")
name = sys.argv[sys.argv.index("--name")+1]
except:
if dev:
print("[Pylect] name could not be initalized, choosing default name")
print('[Pylect] name = "Pylect"')
name = "Pylect"
else:
if dev: print(f'[Pylect] name = "Pylect"')
name = "Pylect"
if "--modules" in sys.argv:
try:
modules = sys.argv[sys.argv.index("--modules")+1]
modules = modules.split(",")
except:
if dev:
print("[Pylect] modules could not be initalized, ignoring option")
modules = []
else:
modules = []
class Pylect():
def __init__(self):
self.name = "Pylect"
self.env_folder = "pylect1.1"
self.version_tuple = (1, 1, 6)
self.version_status = "release"
self.version = "1.1.6"
self.build = 49
self.src = "python"
self.src_path = "/Users/jfami/pylect/pylect1.1"
self.modules = allmodules
self.__pylect__ = self | {
"domain": "codereview.stackexchange",
"id": 45143,
"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, console, authentication",
"url": null
} |
python, python-3.x, console, authentication
del __file__
sys.pylect = Pylect()
sys.exec_context = (os.getcwd(), (platform.system(), platform.release()), (platform.uname().machine, platform.uname().node), (platform.python_implementation(), platform.python_compiler(), platform.python_build()), (sys.pylect.name, sys.pylect.env, sys.pylect.version))
sys.env = ("3.11", "pylect1.1")
sys.filename = ""
sys.validargs = ["--dev", "--name", "--modules"]
sys.pylectargs = []
sys.invalidargs = False
sys.ispylect = True
sys.argv.remove(sys.argv[0])
for arg in sys.argv:
if arg.startswith("--"):
sys.pylectargs.append(arg)
if not arg == "--dev":
try:
if sys.argv[sys.argv.index(arg)+1].startswith("--"): raise Exception
sys.pylectargs.append(sys.argv[sys.argv.index(arg)+1])
sys.argv.remove(sys.argv[sys.argv.index(arg)+1])
except:
sys.invalidargs = True
sys.argv.remove(arg)
if dev and sys.invalidargs: print("Some args could not be initalized")
print(f"{name} Terminal!")
def exit_env():
from os import walk, remove
from os.path import join
path = '/Users/jfami/pylect/pylect1.1'
items = [join(root, file) for root, subdirs, files in walk(path) for file in files]
if len(items) == 1: return
for item in items:
if "pylect.py" in item:
pass
else:
remove(item)
cmds = [] | {
"domain": "codereview.stackexchange",
"id": 45143,
"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, console, authentication",
"url": null
} |
python, python-3.x, console, authentication
cmds = []
while True:
if modules != []:
for module in modules:
if dev: print(f"[Pylect] import {module}")
try:
exec(f"import {module}", globals(), locals())
except:
print(f"No module named '{module}'")
inp = input("> ")
if dev and not inp[0] == ".": print(f"[Pylect] {inp}")
cmds.append(inp)
if inp == ".imports":
modulenames = set(sys.modules) & set(globals())
allmodules = [sys.modules[name] for name in modulenames]
print(allmodules)
continue
elif inp == ".env":
import sys
print(f"Python {sys.version.split(' ')[0]} (pylect1.1)")
continue
elif inp == ".exit-env":
if dev: print("[Pylect] exit_env()")
if dev: print("[Pylect] exit()")
exit_env()
exit()
elif inp == ".clear-env":
if dev: print("[Pylect] exit_env()")
exit_env()
continue
elif inp == ".history":
if dev: print("[Pylect] cmds")
print(cmds)
continue
elif inp == ".history prev":
if dev: print("[Pylect] cmds[-2]")
print(cmds[-2])
continue
elif inp == "import .":
print("This is not a module :)")
continue
elif inp == "import cake":
print("THE CAKE IS A LIE!")
continue
elif inp == "import thanks":
print("Thank you")
continue
elif inp == "0.1+0.2":
print(0.3)
continue
elif inp == "raise PylectError":
print("PylectError: Could not find `PylectError`")
continue
elif inp == "exit-env":
print("You forgot a dot.")
continue
try:
res = eval(inp, globals(), locals())
print(res)
except KeyboardInterrupt:
exit_env()
exit()
except:
try:
exec(inp, globals(), locals())
except Exception as e:
print(str(e))
~/pylect/pylect1.1/.pylect.password.py
import os | {
"domain": "codereview.stackexchange",
"id": 45143,
"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, console, authentication",
"url": null
} |
python, python-3.x, console, authentication
~/pylect/pylect1.1/.pylect.password.py
import os
if os.path.exists("/Users/jfami/pylect/.pylect.password.txt"):
change = input("Do you want to change your password? (y/n) ")
if change == "y":
with open("/Users/jfami/pylect/.pylect.password.txt", "w") as pw:
password = input("Input your new password: ")
pw.write(password)
else:
remove = input("Do you want to remove your password? (NOT RECOMMENDED) (y/n) ")
if remove == "y":
os.remove("/Users/jfami/pylect/.pylect.password.txt")
else:
setup = input("Setup a Pylect password? (y/n) ")
if setup == "y":
with open("/Users/jfami/pylect/.pylect.password.txt", "w") as pw:
password = input("Input your password: ")
pw.write(password)
~/pylect/pylect1.1/.pylect.config.py
import os
import subprocess
import sys
if sys.argv[1] == "list" or sys.argv[1] == "-l":
print("Pylect: Finding avaliable versions...")
versions = [x.split("pylect")[1] for x in subprocess.check_output("ls ~/pylect", shell=True).decode().strip().split("\n")]
for version in versions:
if open("~/pylect/.pylect.aliasversion.txt", "r").read().strip() == version:
print(version, "(current)")
else:
print(version)
elif sys.argv[1] == "version" or sys.argv[1] == "-v":
print(f"Pylect {open("~/pylect/.pylect.aliasversion.txt", "r").read().strip()} (pylect{open("~/pylect/.pylect.aliasversion.txt", "r").read().strip()})")
elif sys.argv[1] == "run" or sys.argv[1] == "-r":
args = ""
for arg in sys.argv[1:]:
args += f" {arg}"
os.system(f"pylect {args}")
Answer: .pylect.password.py
Your file naming is non-standard. I have some concerns with prefixing python files with ., and using . rather than _ to delimit names.
Make pylect1.1 hidden instead (.pylect1.1).
You should use globals to DRY hard coded values like /Users/jfami/pylect.
You can use pathlib to have a modern path interface. | {
"domain": "codereview.stackexchange",
"id": 45143,
"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, console, authentication",
"url": null
} |
python, python-3.x, console, authentication
You can use pathlib to have a modern path interface.
You should use functions. You have two places which write to a password file. You can make a function to reduce the amount of repeated code (DRY).
You can DRY your code by adding a SET_TEXT constant with both versions of the set text.
import pathlib
ROOT = pathlib.Path("/Users/jfami/pylect")
PASSWORD = ROOT / ".pylect.password.txt"
SET_TEXT = (
(
"Setup a Pylect password? (y/n) ",
"Input your password: ",
),
(
"Do you want to change your password? (y/n) ",
"Input your new password: ",
),
)
def set_password(
password: str,
location: str | pathlib.Path = PASSWORD,
) -> None:
with open(location, "w") as f:
f.write(password)
def main() -> None:
exits = PASSWORD.exists()
SET, PASSWORD = SET_TEXT[exists]
if "y" == input(SET):
set_password(input(PASSWORD))
elif exists:
remove = input("Do you want to remove your password? (NOT RECOMMENDED) (y/n) ")
if remove == "y":
os.remove(PASSWORD)
.pylect.config.py
We can take a lot of the learning points from .pylect.password.py
You can use a in {"1", "2"} rather than a == "1" or a == "2".
Your list comprehension is too long and so is hard to read.
You can remove the comprehension entirely.
We can use " ".join(sys.argv[1:]) rather than a for loop to in run.
import os
import pathlib
import subprocess
import sys
ROOT = pathlib.Path("~/pylect")
ALIAS_VERSION = ROOT / ".pylect.aliasversion.txt"
def read_version(path: str | pathlib.Path = ALIAS_VERSION):
with open(ALIAS_VERSION, "r") as f:
return f.read().strip() | {
"domain": "codereview.stackexchange",
"id": 45143,
"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, console, authentication",
"url": null
} |
python, python-3.x, console, authentication
class Main:
@staticmethod
def list() -> None:
print("Pylect: Finding avaliable versions...")
for line in subprocess.check_output("ls ~/pylect", shell=True).decode().strip().split("\n"):
version = line.split("pylect")[1]
if version == read_version():
print(version, "(current)")
else:
print(version)
@staticmethod
def version() -> None:
version = read_version()
print(f"Pylect {version} (pylect{version})")
@staticmethod
def run() -> None:
os.system(f"pylect {' '.join(sys.argv[1:])}")
if sys.argv[1] in {"list", "-l"}:
Main.list()
elif sys.argv[1] in {"version", "-v"}:
Main.version()
elif sys.argv[1] in {"run", "-r"}:
Main.run()
I think you could possibly benefit from argparse to make more complicated CLI interfaces easier.
We can add a flag to allow using -v and --version as to get the version information:
parser = argparse.ArgumentParser()
parser.add_argument("-v", "--version", action="store_true")
print(parser.parse_args(["-v"]))
Namespace(version=True)
Rather than using "store_true" and having to build the if elif else we can use "store_const" to store Main.version.
parser = argparse.ArgumentParser()
parser.add_argument("-v", "--version", action="store_const", const=Main.version)
print(parser.parse_args(["-v"]))
Namespace(version=<function Main.version at 0x7f0c36e99440>)
We can have a default main function by using parser.set_defaults(main=no_entry).
We can then change -v to store to main, rather than version, to overwrite the function we run.
parser = argparse.ArgumentParser()
parser.set_defaults(main=Main.no_entry)
parser.add_argument("-v", "--version", action="store_const", dest="main", const=Main.version)
print(parser.parse_args([]))
print(parser.parse_args(["-v"]))
Namespace(main=<function Main.no_entry at 0x7f7bfde10f40>)
Namespace(main=<function Main.version at 0x7f7bfdf9d440>) | {
"domain": "codereview.stackexchange",
"id": 45143,
"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, console, authentication",
"url": null
} |
python, python-3.x, console, authentication
To add list we have two options:
As a mutually exclusive option with --version.
Add a subparser.
Since run will be a subparser I'll make --list mutually exclusive with --version as a means of demonstration.
parser = argparse.ArgumentParser()
parser.set_defaults(main=Main.no_entry)
options = parser.add_mutually_exclusive_group()
options.add_argument("-v", "--version", action="store_const", dest="main", const=Main.version)
options.add_argument("-l", "--list", action="store_const", dest="main", const=Main.list)
print(parser.parse_args(["-v"]))
print(parser.parse_args(["-l"]))
print(parser.parse_args(["-l", "-v"]))
Namespace(main=<function Main.version at 0x7f4690c99440>)
Namespace(main=<function Main.list at 0x7f4690c98f40>)
usage: .pylect.py [-h] [-v | -l]
.pylect.py: error: argument -v/--version: not allowed with argument -l/--list
We can add run as a subparser.
Subparsers are very similar to the root parser so the code should be fairly easy to understand.
parser = argparse.ArgumentParser()
parser.set_defaults(main=Main.no_entry)
# ...
subparsers = parser.add_subparsers()
run = subparsers.add_parser("run")
run.set_defaults(main=Main.run)
run.add_argument("values", nargs="*")
print(parser.parse_args(["run", "1", "2", "3"]))
Namespace(main=<function Main.run at 0x7f26d91d1f80>, values=['1', '2', '3'])
We need to pass the Namespace to run (and all other functions) to be able to get the same functionality.
@staticmethod
def run(args: argparse.Namespace) -> None:
print(f"pylect {' '.join(args.values)}")
args = parser.parse_args()
args.main(args)
Note: functions have been changed for easier testing of argparse.
import argparse
class Main:
@staticmethod
def list(args: argparse.Namespace) -> None:
print("Pylect: list")
@staticmethod
def version(args: argparse.Namespace) -> None:
print(f"Pylect: version") | {
"domain": "codereview.stackexchange",
"id": 45143,
"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, console, authentication",
"url": null
} |
python, python-3.x, console, authentication
@staticmethod
def run(args: argparse.Namespace) -> None:
print(f"pylect {' '.join(args.values)}")
@staticmethod
def no_entry(args: argparse.Namespace) -> None:
print(f"pylect: no command specified")
raise SystemExit(1)
@classmethod
def build_parser(cls) -> argparse.ArgumentParser:
parser = argparse.ArgumentParser()
parser.set_defaults(main=cls.no_entry)
parser.add_argument(
"-v",
"--version",
action="store_const",
dest="main",
const=cls.version,
)
subparsers = parser.add_subparsers()
list = subparsers.add_parser("list")
list.set_defaults(main=cls.list)
run = subparsers.add_parser("run")
run.set_defaults(main=cls.run)
run.add_argument("values", nargs="*")
return parser
args = Main.build_parser().parse_args()
args.main(args)
Some more can be said of .pylect.py. However I think you should expand on my advice and update the file for a 2nd review. | {
"domain": "codereview.stackexchange",
"id": 45143,
"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, console, authentication",
"url": null
} |
javascript, functional-programming
Title: Partial Function Application in JavaScript
Question: I'm trying to make a partial function from any function.
Here is a working example:
function partial(fn) {
const argc = fn.length;
const argv = [];
return function part(...args) {
argv.push(...args);
return argv.length >= argc ? fn(...argv) : part;
}
}
Usage:
function foo(a, b, c, d) {
return `foo: ${a}, ${b}, ${c}, ${d}`;
}
console.log( partial(foo)(1, 2, 3, 4) ); // => foo: 1, 2, 3, 4
console.log( partial(foo)(1, 2)(3, 4) ); // => foo: 1, 2, 3, 4
console.log( partial(foo)(1, 2)(3)(4) ); // => foo: 1, 2, 3, 4
console.log( partial(foo)(1)(2)(3)(4) ); // => foo: 1, 2, 3, 4
console.log( partial(foo)()(1, 2)()(3)()(4) ); // => foo: 1, 2, 3, 4
However, I'm not completely happy with it because of argv.push(...args);.
Is there a better, shorter, or more canonical way to make a partial function application in JavaScript?
Edit:
Replaced deprecated arguments with rest parameters ...args.
Answer: An interesting question,
I have never seen a partial functional application like that, I am used to see something more like
function partial2(f, ...args) {
return function() {
return f.apply(this, args.concat(...arguments));
};
}
console.log(partial2(foo, 1, 2)(3,4)); // => foo: 1, 2, 3, 4
Where you create once the partial application, and that's it.
To me, that is the more canonical way.
Your code is in a way more flexible and fun. The only thing I can provide is to note that Array.push returns the new count elements, and Array.length provides the current count of elements. This means you could just skip the request of argv.length and directly work with the return value of argv.push(...args)
function partial3(f) {
const argc = f.length, argv = [];
return function partialFunction(...args) {
return argv.push(...args) >= argc ? f(...argv) : partialFunction;
};
} | {
"domain": "codereview.stackexchange",
"id": 45144,
"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, functional-programming",
"url": null
} |
javascript, functional-programming
And actually, the caching of argc seems a bit overkill, you only use f.length once.
function partial3(f) {
const argv = [];
return function partialFunction(...args) {
return argv.push(...args) >= f.length ? f(...argv) : partialFunction;
};
}
Final thought, this might need some more fiddling.
const myPartial = partial3(foo)(1, 2, 3);
console.log( myPartial('a') );
console.log( myPartial('b') );
console.log( myPartial('c') );
The expectation of a partial is that this should return
foo: 1, 2, 3, a
foo: 1, 2, 3, b
foo: 1, 2, 3, c
but it returns
foo: 1, 2, 3, a
foo: 1, 2, 3, a
foo: 1, 2, 3, a
because the partial function keeps too much state...
Belows is a snippet with the different functions and some tests;
function partial(fn) {
const argc = fn.length;
const argv = []
return function part(...args) {
argv.push(...args);
return argv.length >= argc ? fn(...argv) : part;
}
}
function partial2(f, ...args) {
return function() {
return f.apply(this, args.concat(...arguments));
};
}
function partial3(f) {
const argc = f.length, argv = [];
return function partialFunction(...args) {
return argv.push(...args) >= argc ? f(...argv) : partialFunction;
};
}
function foo(a, b, c, d) {
return `foo: ${a}, ${b}, ${c}, ${d}`;
}
console.log( partial(foo)(1, 2, 3, 4) ); // => foo: 1, 2, 3, 4
console.log( partial(foo)(1, 2)(3, 4) ); // => foo: 1, 2, 3, 4
console.log( partial(foo)(1, 2)(3)(4) ); // => foo: 1, 2, 3, 4
console.log( partial(foo)(1)(2)(3)(4) ); // => foo: 1, 2, 3, 4
console.log( partial(foo)()(1, 2)()(3)()(4) ); // => foo: 1, 2, 3, 4
console.log( partial2(foo, 1, 2)(3,4) ); // => foo: 1, 2, 3, 4 | {
"domain": "codereview.stackexchange",
"id": 45144,
"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, functional-programming",
"url": null
} |
javascript, functional-programming
console.log( partial2(foo, 1, 2)(3,4) ); // => foo: 1, 2, 3, 4
console.log( partial3(foo)(1, 2, 3, 4) ); // => foo: 1, 2, 3, 4
console.log( partial3(foo)(1, 2)(3, 4) ); // => foo: 1, 2, 3, 4
console.log( partial3(foo)(1, 2)(3)(4) ); // => foo: 1, 2, 3, 4
console.log( partial3(foo)(1)(2)(3)(4) ); // => foo: 1, 2, 3, 4
console.log( partial3(foo)()(1, 2)()(3)()(4) ); // => foo: 1, 2, 3, 4
const myPartial = partial3(foo)(1, 2, 3);
console.log( myPartial('a') );
console.log( myPartial('b') );
console.log( myPartial('c') ); | {
"domain": "codereview.stackexchange",
"id": 45144,
"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, functional-programming",
"url": null
} |
python, cs50
Title: C$50 Finance - A Web App for Stock Portfolio Management
Question: C$50 Finance is a web application built with Flask that allows users to manage their stock portfolios. It enables users to check real-time stock prices, view their portfolio values, and buy/sell stocks.
The full specification of the problem set can be found here:
C$50 Finance.
The code passes all the green checks on check50.
Review Goal:
General coding comments, style, etc.
Code:
app.py:
import datetime
from cs50 import SQL
from flask import Flask, flash, redirect, render_template, request, session
from werkzeug.security import check_password_hash, generate_password_hash
from flask_session import Session
from helpers import apology, is_strong_password, login_required, lookup, usd
# Configure application
app = Flask(__name__)
# Custom filter
app.jinja_env.filters["usd"] = usd
# Configure session to use filesystem (instead of signed cookies)
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
# Configure CS50 Library to use SQLite database
db = SQL("sqlite:///finance.db")
@app.after_request
def after_request(response):
"""Ensure responses aren't cached"""
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
response.headers["Expires"] = 0
response.headers["Pragma"] = "no-cache"
return response
@app.route("/")
@login_required
def index():
"""Show portfolio of stocks"""
# Query to retrieve distinct stock symbols and the sum of shares owned
# for each stock
stocks = db.execute(
"""
SELECT DISTINCT(symbol) AS symbol, SUM(shares_amount) AS shares
FROM transactions
WHERE user_id = ?
GROUP BY symbol
""",
session["user_id"],
)
total_shares_worth = 0
# Calculate total shares' worth and collect stock prices
for stock in stocks:
symbol = stock["symbol"]
shares = stock["shares"] | {
"domain": "codereview.stackexchange",
"id": 45145,
"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, cs50",
"url": null
} |
python, cs50
# Lookup stock price
if symbol:
stock_info = lookup(stock["symbol"])
if stock_info:
stock_price = stock_info["price"]
total_shares_worth += stock_price * shares
stock.update({"price": stock_price,
"total": stock_price * shares})
return render_template(
"index.html",
stocks=stocks,
cash=retrieve_cash(),
grand_total=retrieve_cash() + total_shares_worth,
)
@app.route("/buy", methods=["GET", "POST"])
@login_required
def buy():
"""Buy shares of stock"""
if request.method == "POST":
symbol = request.form.get("symbol")
shares = request.form.get("shares")
if not symbol or not shares:
return apology("Please fill in all the fields.")
# Check if the symbol exists
stock_info = lookup(symbol)
if not stock_info:
return apology("The symbol does not exist.")
try:
shares = int(shares)
except ValueError:
return apology("Shares must be a whole number.")
if shares < 1:
return apology("The number of shares can not be less than 1.")
# Calculate the total cost of the shares
cost = shares * stock_info["price"]
# Check if the user can afford the shares
cash = retrieve_cash()
if cash < cost:
return apology("Insufficient balance.", 403)
update_cash(cash - cost)
record_transaction(stock_info, shares, "buy")
flash("Bought!")
return redirect("/")
# User reached route via GET (as by clicking a link or via redirect)
return render_template("buy.html") | {
"domain": "codereview.stackexchange",
"id": 45145,
"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, cs50",
"url": null
} |
python, cs50
@app.route("/history")
@login_required
def history():
"""Show history of transactions"""
transactions = db.execute(
"""
SELECT symbol, shares_amount AS shares, price, date
FROM transactions
WHERE user_id = ?
""",
session["user_id"],
)
return render_template("history.html", transactions=transactions)
@app.route("/login", methods=["GET", "POST"])
def login():
"""Log user in"""
# Forget any user_id
session.clear()
# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":
username = request.form.get("username")
password = request.form.get("password")
# Ensure username and password were submitted
if not password:
return apology("Please fill all the fields.", 403)
# Query database for username
rows = db.execute(
"""
SELECT *
FROM users
WHERE username = ?
""",
username,
)
# Ensure username exists and password is correct
if len(rows) != 1 or not check_password_hash(rows[0]["hash"], password):
return apology("Invalid username and/or password", 403)
# Remember which user has logged in
session["user_id"] = rows[0]["id"]
# Redirect user to home page
return redirect("/")
# User reached route via GET (as by clicking a link or via redirect)
return render_template("login.html")
@app.route("/logout")
def logout():
"""Log user out"""
# Forget any user_id
session.clear()
# Redirect user to login form
return redirect("/")
@app.route("/quote", methods=["GET", "POST"])
@login_required
def quote():
"""Get stock quote."""
if request.method == "POST":
symbol = request.form.get("symbol")
if not symbol:
return apology("Please fill all the fields.")
stock_info = lookup(symbol) | {
"domain": "codereview.stackexchange",
"id": 45145,
"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, cs50",
"url": null
} |
python, cs50
stock_info = lookup(symbol)
if stock_info:
return render_template(
"quoted.html",
price=stock_info["price"],
name=stock_info["name"],
symbol=stock_info["symbol"],
)
return apology("Symbol does not exist.")
# User reached route via GET (as by clicking a link or via redirect)
return render_template("quote.html")
@app.route("/register", methods=["GET", "POST"])
def register():
"""Register user"""
if request.method == "POST":
username = request.form.get("username")
password = request.form.get("password")
confirmation = request.form.get("confirmation")
users = db.execute(
"""
SELECT *
FROM users
WHERE username = ?
""",
username,
)
if not username or not password or not confirmation:
return apology("Please fill in all fields.")
if users:
return apology("Username already exists.")
res = is_strong_password(password)
if res != "Success.":
return apology(res)
if password != confirmation:
return apology("Passwords do not match.", 403)
db.execute(
"""
INSERT INTO users (username, hash)
VALUES(?, ?)
""",
username,
generate_password_hash(password),
)
return redirect("/login")
# User reached route via GET (as by clicking a link or via redirect)
return render_template("register.html")
@app.route("/sell", methods=["GET", "POST"])
@login_required
def sell():
"""Sell shares of stock"""
if request.method == "POST":
symbol = request.form.get("symbol")
shares = request.form.get("shares")
if not symbol or not shares:
return apology("Please input all the fields.") | {
"domain": "codereview.stackexchange",
"id": 45145,
"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, cs50",
"url": null
} |
python, cs50
if not symbol or not shares:
return apology("Please input all the fields.")
try:
shares = int(shares)
except ValueError:
return apology("Shares must be a whole number.")
# Check if the user owns the stock
cur_shares = db.execute(
"""
SELECT SUM(shares_amount) AS total
FROM transactions
WHERE user_id = ? AND symbol = ?
""",
session["user_id"],
symbol,
)
if not cur_shares[0]["total"] or cur_shares[0]["total"] < shares:
return apology("You don't own enough shares of this stock.")
if shares < 0:
return apology("You can't sell negative shares.")
# Update user's cash balance
stock_info = lookup(symbol)
profit = shares * stock_info["price"]
update_cash(retrieve_cash() + profit)
record_transaction(stock_info, -shares, "sold")
flash("Sold!")
return redirect("/")
stocks = db.execute(
"""
SELECT DISTINCT(symbol) AS symbol
FROM transactions
WHERE user_id = ?
GROUP BY symbol
HAVING SUM(shares_amount) > 0
""",
session["user_id"],
)
# User reached route via GET (as by clicking a link or via redirect)
return render_template("sell.html", stocks=stocks)
def retrieve_cash() -> None:
return db.execute(
"""
SELECT cash
FROM users
WHERE id = ?
""",
session["user_id"],
)[0]["cash"]
def update_cash(amount: int) -> None:
return db.execute(
"""
UPDATE users
SET cash = ?
WHERE id = ?
""",
amount,
session["user_id"],
) | {
"domain": "codereview.stackexchange",
"id": 45145,
"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, cs50",
"url": null
} |
python, cs50
def record_transaction(stock_info: dict, shares: int, trans_type: str) -> None:
db.execute(
"""
INSERT INTO transactions(user_id, symbol, shares_amount, price, date, type)
VALUES(?, ?, ?, ?, ?, ?)
""",
session["user_id"],
stock_info["name"],
shares,
stock_info["price"],
datetime.datetime.now(),
trans_type,
)
helpers.py:
import datetime
import re
import urllib
import uuid
from functools import wraps
import pytz
import requests
from flask import redirect, render_template, session
def apology(msg: str, code: int = 400):
"""Render message as an apology to user."""
def escape(s):
"""
Escape special characters.
https://github.com/jacebrowning/memegen#special-characters
"""
for old, new in [
("-", "--"),
(" ", "-"),
("_", "__"),
("?", "~q"),
("%", "~p"),
("#", "~h"),
("/", "~s"),
('"', "''"),
]:
s = s.replace(old, new)
return s
return (
render_template("apology.html", top=code, bottom=escape(msg)),
code,
)
def login_required(f):
"""
Decorate routes to require login.
http://flask.pocoo.org/docs/0.12/patterns/viewdecorators/
"""
@wraps(f)
def decorated_function(*args, **kwargs):
if session.get("user_id") is None:
return redirect("/login")
return f(*args, **kwargs)
return decorated_function
def lookup(symbol: str) -> dict:
"""Look up quote for symbol."""
# Prepare API request
symbol = symbol.upper()
end = datetime.datetime.now(pytz.timezone("US/Eastern"))
start = end - datetime.timedelta(days=7) | {
"domain": "codereview.stackexchange",
"id": 45145,
"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, cs50",
"url": null
} |
python, cs50
# Yahoo Finance API
url = (
f"https://query1.finance.yahoo.com/v7/finance/download/{urllib.parse.quote_plus(symbol)}"
f"?period1={int(start.timestamp())}"
f"&period2={int(end.timestamp())}"
f"&interval=1d&events=history&includeAdjustedClose=true"
)
# Query API
try:
response = requests.get(
url,
cookies={"session": str(uuid.uuid4())},
headers={"User-Agent": "python-requests", "Accept": "*/*"},
)
response.raise_for_status()
# CSV header: Date,Open,High,Low,Close,Adj Close,Volume
quotes = list(
csv.DictReader(response.content.decode("utf-8").splitlines())
)
quotes.reverse()
price = round(float(quotes[0]["Adj Close"]), 2)
return {"name": symbol, "price": price, "symbol": symbol}
except (requests.RequestException, ValueError, KeyError, IndexError):
return {}
def usd(value: float) -> str:
"""Format value as USD."""
return f"${value:,.2f}"
def is_strong_password(password: str) -> str:
"""Verify the strength of 'password'.
Returns a string indicating the wrong criteria.
A password is considered strong if:
8 characters length or more
1 digit or more
1 symbol or more
1 uppercase letter or more
1 lowercase letter or more
"""
criteria = [
(len(password) >= 8, "Password must be at least 8 characters long."),
(re.search(r"\d", password), "Password must contain at least one digit."),
(re.search(r"[A-Z]", password), "Password must contain at least one uppercase letter."),
(re.search(r"[a-z]", password), "Password must contain at least one lowercase letter."),
(re.search(r"\W", password), "Password must contain at least one special character"),
]
for cond, msg in criteria:
if not cond:
return msg
return "Success." | {
"domain": "codereview.stackexchange",
"id": 45145,
"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, cs50",
"url": null
} |
python, cs50
for cond, msg in criteria:
if not cond:
return msg
return "Success."
The code was formatted with black and isort.
Answer:
The code was formatted with black and isort.
Yes, thank you, I noticed that at once upon reading these imports:
# [2nd group]
from flask import Flask, flash, redirect, render_template, request, session
...
# [3rd group]
from flask_session import Session
from helpers import ...
I was about to consult pypi for "flask_session" which I'm not familiar with,
and then I noticed that the posted "helpers" and the not-posted "flask_session"
are definitely part of your project rather than a published pypi project.
Kudos for clear communication.
safely importable
app = Flask(__name__)
# ...
app.jinja_env.filters["usd"] = usd
# ...
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
# Configure CS50 Library to use SQLite database
db = SQL("sqlite:///finance.db")
That first line is bog standard and should remain as-is.
The filter, I imagine, is pretty safe, as are the .config assignments.
I'm not familiar with Session(), but I worry about its FS read/write needs.
And the SQL() call will definitely write to
CWD
and perhaps require finding a readable .db file there.
In other words this code will produce CWD side effects, and may
have "bailing due to fatal error" side effects if it can't read its favorite file.
Avoid side effecting code at top level of a module.
Bury such code in a helper function.
Use an if __name__ ... guard to run it conditionally.
We want it to be safe for other modules to import this module,
without side effects. For example, a
test suite
may want to test some helper within this module.
BTW, a nit on docstrings: You begin them with an English sentence, and that's great.
Each sentence should end with a . period. Whatever. | {
"domain": "codereview.stackexchange",
"id": 45145,
"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, cs50",
"url": null
} |
python, cs50
cite your reference
The after_request function is, on the whole, terrific.
Single responsibility, short, sweet, pretty clear.
There has been a fair amount of drift over the years
in what origin servers, proxies, and clients support.
Caching is a regrettably complex topic.
Maintenance engineers commonly have to investigate cache-related problem reports.
The doctest / comments would benefit from any descriptions you'd care to add,
describing research you've already done while authoring this code:
IETF spec(s) you adhere to
URL of someone's blog on the topic that you relied on
list of server versions and proxy versions you've validated against
pointer to integration tests within this repo that verify correct behavior
sql details
SELECT DISTINCT(symbol) ...
FROM ...
GROUP BY symbol
Sorry, I'm not getting the DISTINCT here.
We're GROUPing by symbol, right?
So the backend is guaranteeing we will only get unique symbols in the result.
Maybe this is leftover from early exploratory debugging queries.
Anyway, recommend you elide "DISTINCT".
Similarly down in sell().
Also, kudos on properly using bind vars, and thereby dodging
the spectre of Little Bobby Tables.
null guard
if symbol:
Consider tacking on a WHERE ... AND conjunct,
to guarantee that only "good" symbols are returned by the backend.
hoist common subexpression
return render_template(
... ,
cash=retrieve_cash(),
grand_total=retrieve_cash() + ... ,
)
There's an opportunity to assign a temp var,
so you make a single backend call instead of two.
Alternatively, possibly a
@lru_cache
decorator on that retrieve_cash helper would be attractive.
minimize indent
@app.route("/buy", methods=["GET", "POST"])
...
if request.method == "POST":
Consider conditionally dealing with GET first and returning a result.
Then by the time you get to the bulk of the code,
you can unconditionally deal with POST,
saving four spaces of indent. | {
"domain": "codereview.stackexchange",
"id": 45145,
"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, cs50",
"url": null
} |
python, cs50
extract validation helper
shares = int(shares)
In a few places you check for fractional shares.
Consider creating a helper that would let you write
shares = need_whole_number(shares)
and in the error case it would raise a FractionalSharesError
to let a top-level try report the appropriate apology().
selling stock you don't own
I don't understand the [0] dereference:
cur_shares = db.execute(
"""
SELECT SUM(shares_amount) AS total
FROM transactions
WHERE user_id = ? AND symbol = ?
""",
session["user_id"],
symbol,
)
if not cur_shares[0]["total"]
If symbol is some non-existant XYZZY,
then we get zero result rows and the [0]
leads to IndexError.
standard time zone
In record_transaction we record now() in the transactions table.
It's not obvious to me that we're recording UTC seconds since 1970.
Maybe we are?
There's no comments or unit tests to help me understand
whether running the webserver in EDT or PDT time zone
would affect what's stored in the database.
It's common to develop against sqlite and then later deploy
in production against e.g. postgres, where different clients
may be in diverse geographic locations / timezones, hence the concern.
This codebase appears to achieve its design goals.
I would be willing to delegate or accept maintenance tasks on it. | {
"domain": "codereview.stackexchange",
"id": 45145,
"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, cs50",
"url": null
} |
c, http, curl
Title: Small HTTP client/SDK created using libcurl in C language
Question: I created a SDK in C for my Rust project (a key value store in Rust). It should give access to the HTTP routes in a simple manner. (I never worked with C outside of university.)
I used:
libcurl to call the HTTP endpoints from C, because it is a well known library and works on almost any system.
CMake to make it easier to build and link the library and the example.
clang-tidy for static analysis/linting and clang-format for formatting
for the result struct, I wanted a Rust Result feeling, and took inspiration from this gist: https://gist.github.com/f0rki/9b2c2b73d46ccdad2b39ab79b3a5517f
The lib code is pasted here, but I have a PR open on GitHub, with CMake, header files and a example executable. I accept reviews there as well. Thanks!
https://github.com/auyer/MemoryKV/pull/2
#include <curl/curl.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
// string_carrier struct to store the body results from curl with easy reallocation
struct string_carrier {
char *ptr;
size_t len;
bool error_flag;
};
// init_string_carrier initializes the string_carrier struct to store the body results from curl
void init_string_carrier(struct string_carrier *s) {
s->len = 0;
s->ptr = malloc(s->len + 1);
s->error_flag = false;
if (s->ptr == NULL) {
// TODO: figure out a better way to handle errors in C
fprintf(stderr, "memkv client: Error in Callback, malloc() failed\n");
// skip exit and return error instead
// exit(EXIT_FAILURE);
s->error_flag = true;
} else {
s->ptr[0] = '\0';
}
} | {
"domain": "codereview.stackexchange",
"id": 45146,
"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, http, curl",
"url": null
} |
c, http, curl
// string_carrier_writefunc is the callback function to read the body from libcurl into a string_carrier
size_t string_carrier_writefunc(void *ptr, size_t size, size_t nmemb, struct string_carrier *s) {
// new length to realocate response chunks from libcurl
size_t new_len = s->len + size * nmemb;
s->ptr = realloc(s->ptr, new_len + 1);
if (s->ptr == NULL) {
// TODO: figure out a better way to handle errors in C
fprintf(stderr, "memkv client: Error in string_carrier_writefunc Callback, realloc() failed\n");
// skip exit and return error instead
// exit(EXIT_FAILURE);
s->error_flag = true;
} else {
memcpy(s->ptr + s->len, ptr, size * nmemb);
s->ptr[new_len] = '\0';
s->len = new_len;
}
return size * nmemb;
}
// memkv_client
typedef struct memkv_client {
char *host;
} memkv_client;
void memkv_init_client(struct memkv_client *client, char *host) {
curl_global_init(CURL_GLOBAL_ALL);
client->host = host;
}
memkv_client *memkv_client_new(char *host) {
memkv_client *client = malloc(sizeof(memkv_client));
memkv_init_client(client, host);
return client;
}
char *build_url(const char *host, const char *params) {
// snprintf returns the number of characters that would have been written if called with NULL
unsigned long sizeneeded = snprintf(NULL, 0, "%s/%s", host, params);
// use that number to allocate a buffer of the right size
char *url = malloc(sizeneeded + 1);
// write the string_carrier to the buffer
sprintf(url, "%s/%s", host, params);
return url;
}
typedef struct {
bool success;
union {
char *result;
char *error;
};
} memkv_result;
static const char base_curl_error[] = "Error from curl";
static const char unknown_error_msg[] = "unknown error";
void make_curl_error(memkv_result *r, const char *err) {
r->success = false; | {
"domain": "codereview.stackexchange",
"id": 45146,
"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, http, curl",
"url": null
} |
c, http, curl
void make_curl_error(memkv_result *r, const char *err) {
r->success = false;
if (strlen(err) == 0) {
r->error = malloc(sizeof(unknown_error_msg));
strcpy(r->error, unknown_error_msg);
return;
}
unsigned long sizeneeded = snprintf(NULL, 0, "%s : %s", base_curl_error, err);
r->error = malloc(sizeneeded + 1);
snprintf(r->error, sizeneeded + 1, "%s : %s", base_curl_error, err);
}
// init_memkv_result initializes the memkv_result struct with success as false
memkv_result *init_memkv_result() {
memkv_result *r = malloc(sizeof(memkv_result));
r->result = malloc(sizeof(char));
if (r->result == NULL) {
free(r);
printf("Error in init_memkv_result");
return NULL;
}
r->success = false;
return r;
}
// the functions that make the HTTP calls start here
// they are very similar, and have some code repetition that maybe can be put in a function.
memkv_result *memkv_get_key(struct memkv_client *client, const char *key) {
memkv_result *r = init_memkv_result();
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if (!curl) {
make_curl_error(r, "Failed startig curl");
return r;
}
struct string_carrier s;
init_string_carrier(&s);
if (s.error_flag) {
make_curl_error(r, "Failed to initialize string_carrier");
return r;
}
char *url = build_url(client->host, key);
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, string_carrier_writefunc);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &s);
res = curl_easy_perform(curl);
/* always cleanup */
curl_easy_cleanup(curl);
free(url); | {
"domain": "codereview.stackexchange",
"id": 45146,
"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, http, curl",
"url": null
} |
c, http, curl
/* always cleanup */
curl_easy_cleanup(curl);
free(url);
if (res != CURLE_OK) {
const char *err = curl_easy_strerror(res);
make_curl_error(r, err);
return r;
}
if (s.error_flag) {
make_curl_error(r, "Failed to get results from server");
return r;
}
r->success = true;
r->result = malloc(strlen(s.ptr) + 1);
strcpy(r->result, s.ptr);
return r;
}
memkv_result *memkv_delete_key(struct memkv_client *client, const char *key) {
memkv_result *r = init_memkv_result();
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if (!curl) {
make_curl_error(r, "Failed startig curl");
return r;
}
struct string_carrier s;
init_string_carrier(&s);
if (s.error_flag) {
make_curl_error(r, "Failed to initialize string_carrier");
return r;
}
char *url = build_url(client->host, key);
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
// set custom request to delete
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, string_carrier_writefunc);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &s);
/* Perform the request, res will get the return code */
res = curl_easy_perform(curl);
/* always cleanup */
curl_easy_cleanup(curl);
free(url);
/* Check for errors */
if (res != CURLE_OK) {
const char *err = curl_easy_strerror(res);
make_curl_error(r, err);
return r;
}
if (s.error_flag) {
make_curl_error(r, "Failed to get results from server");
return r;
}
r->success = true;
r->result = malloc(strlen(s.ptr) + 1);
strcpy(r->result, s.ptr);
return r;
} | {
"domain": "codereview.stackexchange",
"id": 45146,
"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, http, curl",
"url": null
} |
c, http, curl
strcpy(r->result, s.ptr);
return r;
}
memkv_result *memkv_put_key(struct memkv_client *client, const char *key, const char *put_body) {
memkv_result *r = init_memkv_result();
CURL *curl;
CURLcode res;
// start the easy interface in curl
curl = curl_easy_init();
if (!curl) {
make_curl_error(r, "Failed startig curl");
return r;
}
struct string_carrier s;
init_string_carrier(&s);
if (s.error_flag) {
make_curl_error(r, "Failed to initialize string_carrier");
return r;
}
char *url = build_url(client->host, key);
curl_easy_setopt(curl, CURLOPT_URL, url);
struct curl_slist *headers = NULL;
/* default type with postfields is application/x-www-form-urlencoded,
change it if you want */
headers = curl_slist_append(headers, "Content-Type: application/octet-stream");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
/* pass on content in request body. When CURLOPT_POSTFIELDSIZE is not used,
curl does strlen to get the size. */
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, put_body);
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT");
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, string_carrier_writefunc);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &s);
/* Perform the request, res will get the return code */
res = curl_easy_perform(curl);
/* always cleanup */
curl_easy_cleanup(curl);
free(url);
/* free headers */
curl_slist_free_all(headers);
/* Check for errors */
if (res != CURLE_OK) {
const char *err = curl_easy_strerror(res);
make_curl_error(r, err);
return r;
}
if (s.error_flag) {
make_curl_error(r, "Failed to get results from server");
return r;
}
r->success = true;
r->result = malloc(strlen(s.ptr) + 1);
strcpy(r->result, s.ptr);
return r;
} | {
"domain": "codereview.stackexchange",
"id": 45146,
"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, http, curl",
"url": null
} |
c, http, curl
strcpy(r->result, s.ptr);
return r;
}
memkv_result *memkv_list_keys(struct memkv_client *client) {
memkv_result *r = init_memkv_result();
CURL *curl;
CURLcode res;
// start the easy interface in curl
curl = curl_easy_init();
if (!curl) {
make_curl_error(r, "Failed startig curl");
return r;
}
struct string_carrier s;
init_string_carrier(&s);
if (s.error_flag) {
make_curl_error(r, "Failed to initialize string_carrier");
return r;
}
const char *key = "keys";
char *url = build_url(client->host, key);
// set custom request to delete
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, string_carrier_writefunc);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &s);
/* Perform the request, res will get the return code */
res = curl_easy_perform(curl);
/* always cleanup */
curl_easy_cleanup(curl);
free(url);
/* Check for errors */
if (res != CURLE_OK) {
r->success = false;
const char *err = curl_easy_strerror(res);
make_curl_error(r, err);
return r;
}
if (s.error_flag) {
make_curl_error(r, "Failed to get results from server");
return r;
}
r->success = true;
r->result = malloc(strlen(s.ptr) + 1);
strcpy(r->result, s.ptr);
return r;
}
memkv_result *memkv_list_keys_with_prefix(struct memkv_client *client, const char *key_prefix) {
memkv_result *r = init_memkv_result();
CURL *curl;
CURLcode res;
// start the easy interface in curl
curl = curl_easy_init();
if (!curl) {
make_curl_error(r, "Failed startig curl");
return r;
}
struct string_carrier s;
init_string_carrier(&s);
if (s.error_flag) {
make_curl_error(r, "Failed to initialize string_carrier");
return r;
} | {
"domain": "codereview.stackexchange",
"id": 45146,
"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, http, curl",
"url": null
} |
c, http, curl
const char *key = "keys";
char *url_part1 = build_url(client->host, key);
// TODO: build URL in one call
char *url = build_url(url_part1, key_prefix);
free(url_part1);
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, string_carrier_writefunc);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &s);
/* Perform the request, res will get the return code */
res = curl_easy_perform(curl);
/* always cleanup */
curl_easy_cleanup(curl);
free(url);
/* Check for errors */
if (res != CURLE_OK) {
r->success = false;
const char *err = curl_easy_strerror(res);
make_curl_error(r, err);
return r;
}
if (s.error_flag) {
make_curl_error(r, "Failed to get results from server");
return r;
}
r->success = true;
r->result = malloc(strlen(s.ptr) + 1);
strcpy(r->result, s.ptr);
return r;
}
memkv_result *memkv_delete_keys_with_prefix(struct memkv_client *client, const char *key_prefix) {
memkv_result *r = init_memkv_result();
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if (!curl) {
make_curl_error(r, "Failed startig curl");
return r;
}
struct string_carrier s;
init_string_carrier(&s);
if (s.error_flag) {
make_curl_error(r, "Failed to initialize string_carrier");
return r;
}
const char *key = "keys";
char *url_part1 = build_url(client->host, key);
// TODO: build URL in one call
char *url = build_url(url_part1, key_prefix);
free(url_part1);
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); | {
"domain": "codereview.stackexchange",
"id": 45146,
"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, http, curl",
"url": null
} |
c, http, curl
// set custom request to delete
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, string_carrier_writefunc);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &s);
/* Perform the request, res will get the return code */
res = curl_easy_perform(curl);
/* always cleanup */
curl_easy_cleanup(curl);
free(url);
/* Check for errors */
if (res != CURLE_OK) {
const char *err = curl_easy_strerror(res);
make_curl_error(r, err);
return r;
}
if (s.error_flag) {
make_curl_error(r, "Failed to get results from server");
return r;
}
r->success = true;
r->result = malloc(strlen(s.ptr) + 1);
strcpy(r->result, s.ptr);
return r;
}
memkv_result *memkv_delete_all_keys(struct memkv_client *client) {
memkv_result *r = init_memkv_result();
CURL *curl;
CURLcode res;
// start the easy interface in curl
curl = curl_easy_init();
if (!curl) {
make_curl_error(r, "Failed startig curl");
return r;
}
struct string_carrier s;
init_string_carrier(&s);
if (s.error_flag) {
make_curl_error(r, "Failed to initialize string_carrier");
return r;
}
const char *key = "keys";
char *url = build_url(client->host, key);
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, string_carrier_writefunc);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &s);
/* Perform the request, res will get the return code */
res = curl_easy_perform(curl);
/* always cleanup */
curl_easy_cleanup(curl);
free(url); | {
"domain": "codereview.stackexchange",
"id": 45146,
"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, http, curl",
"url": null
} |
c, http, curl
/* always cleanup */
curl_easy_cleanup(curl);
free(url);
/* Check for errors */
if (res != CURLE_OK) {
r->success = false;
const char *err = curl_easy_strerror(res);
make_curl_error(r, err);
return r;
}
if (s.error_flag) {
make_curl_error(r, "Failed to get results from server");
return r;
}
r->success = true;
r->result = malloc(strlen(s.ptr) + 1);
strcpy(r->result, s.ptr);
return r;
}
```
Answer: Memory Leak:
s->ptr = realloc(s->ptr, new_len + 1);
If realloc() returned NULL, we'd lose access to the original memory and suffer a memory leak. Use a temporary pointer instead:
void *const tmp = realloc(s->ptr, new_len + 1);
if (!tmp) {
/* realloc() failed to reallocate memory. The original memory is still
* there and needs to be freed.
*/
handle_failure();
} else {
/* Now s->ptr points to the new chunk of memory. */
s->ptr = tmp;
...
}
Reduce scope:
Unless I am mistaken, base_curl_error and unknown_error_msg are not used outside of make_url_error(), so there is no point in defining them outside of the function.
Simplify initialization:
In init_string_carrier():
# if 0
s->len = 0;
s->ptr = malloc(s->len + 1);
s->error_flag = false;
#else
memset(s, 0, sizeof *s);
Check the return value of library functions:
We forego checking the result of malloc() in memkv_client_new(), build_url(), make_curl_error(), init_memkv_result(), memkv_get_key(), et cetera.
Good job on not casting the return value albeit.
The return value of curl_global_init() in memkv_init_client() goes unchecked. According to the documentation:
If this function returns non-zero, something went wrong and you cannot
use the other curl functions.
But it may not be necessary to call it at all, since the documentation for curl_easy_init() states:
If you did not already call curl_global_init(3), curl_easy_init(3)
does it automatically. | {
"domain": "codereview.stackexchange",
"id": 45146,
"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, http, curl",
"url": null
} |
c, http, curl
If you did not already call curl_global_init(3), curl_easy_init(3)
does it automatically.
Stylistic choice:
Why has struct memkv been typedefed, but struct string_carrier has not?
Redundant comment:
// memkv_client
typedef struct memkv_client {
..
It should be removed, or replaced with one that describes the struct.
snprintf() returns an int:
// unsigned long sizeneeded = snprintf(NULL, 0, "%s/%s", host, params);
int sizeneeded = snprint(NULL, 0, "%s/%s", host, params);
Is there any specific reason why snake-case has been disregarded whilst naming the above identifier, unlike the rest of the code?
Reduce duplication:
There's a significant amount of code duplication in the functions for making HTTP requests in your code. If we introduce a helper like so:
// NOTE: This is untested code. Change it as you may.
memkv_result *memkv_execute_request(
const char *url,
const char *custom_req,
const char *content_type,
const char *post_data
) {
memkv_result *r = init_memkv_result();
CURL *curl = curl_easy_init();
if (!curl) {
make_curl_error(r, "Failed starting curl.");
return r;
}
CURLCODE res;
struct string_carrier s;
init_string_carrier(&s);
if (s.error_flag) {
make_curl_error(r, "Failed to initialize string_carrier");
return r;
}
curl_easy_setopt(curl, CURLOPT_URL, url);
if (custom_req) {
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, custom_req);
}
struct curl_slist *headers = NULL;
if (content_type) {
/* default type with postfields is application/x-www-form-urlencoded,
change it if you want. */
headers = curl_slist_append(headers, content_type);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
}
if (post_data) {
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post_data);
} | {
"domain": "codereview.stackexchange",
"id": 45146,
"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, http, curl",
"url": null
} |
c, http, curl
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_WRITE_FUNCIION, string_carrier_writefunc);
curl_easy_setopt(curl, CUROPT_WRITEDATA, &s);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
free(url);
if (headers) {
curl_slist_free_all(headers);
}
if (res != CURLE_OK) {
const char *err = curl_easy_strerror(res);
make_curl_error(r, err);
return r;
}
if (s.error_flag) {
make_curl_error(r, "Failed to get results from server.");
return r;
}
r->success = true;
r->result = malloc(strlen(s.ptr) + 1);
strcpy(r->result, s.ptr);
return r;
}
we get left with just:
memkv_result *memkv_get_key(struct memkv_client *client, const char *key) {
char *url = build_url(client->host, key);
return memkv_execute_request(url, NULL, NULL, NULL);
memkv_result *memkv_delete_key(struct memkv_client *client, const char *key) {
char *url = build_url(client->host, key);
return memkv_execute_request(url, "DELETE", NULL, NULL);
memkv_result *memkv_put_key(struct memkv_client *client, const char *key, const char *put_body) {
char *url = build_url(client->host, key);
return memkv_execute_request(url, "PUT", "Content-Type: application/octet-stream", put_body);
}
memkv_result *memkv_list_keys(struct memkv_client *client) {
char *url = build_url(client->host, "keys");
return memkv_execute_request(url, NULL, NULL, NULL);
}
memkv_result *memkv_list_keys_with_prefix(struct memkv_client *client, const char *key_prefix) {
char *url_part1 = build_url(client->host, "keys");
// TODO: build URL in one call
char *url = build_url(url_part1, key_prefix);
free(url_part1);
return memkv_execute_request(url, NULL, NULL, NULL);
} | {
"domain": "codereview.stackexchange",
"id": 45146,
"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, http, curl",
"url": null
} |
c, http, curl
return memkv_execute_request(url, NULL, NULL, NULL);
}
memkv_result *memkv_delete_keys_with_prefix(struct memkv_client *client, const char *key_prefix) {
char *url_part1 = build_url(client->host, "keys");
// TODO: build URL in one call
char *url = build_url(url_part1, key_prefix);
free(url_part1);
return memkv_execute_request(url, "DELETE", NULL, NULL);
}
memkv_result *memkv_delete_all_keys(struct memkv_client *client) {
char *url = build_url(client->host, "keys");
return memkv_execute_request(url, "DELETE", NULL, NULL);
}
Others:
The functions that are not used outside of this translation unit should be marked as having internal linkage. (with the static keyword)
The parameters that are not changed anywhere in the function should be const-qualified.
Don't declare more variables than you need. The key variable in all the HTTP functions is not required.
Consider initializing variables as you declare them.
Use more const.
Fix the spelling mistakes in the error strings.
sizeof(char) is defined by the C standard to be 1.
Allocate to the referenced type:
// memkv_result *r = malloc(sizeof(memkv_result));
memkv_result *r = malloc(sizeof *r);
Consider rewriting the build_url() function to take a pointer to a pointer as the the second parameter, and optionally, a third argument to
specify the number of items like so:
static char *build_url(const char *host, const char **params, size_t num_params) {
...
}
Now we can call it like this:
#if 0
char *url_part1 = build_url(client->host, "keys");
// TODO: build URL in one call
char *url = build_url(url_part1, key_prefix);
#else
const char *const url = build_url(client->host, {"keys", key_prefix}, 2); | {
"domain": "codereview.stackexchange",
"id": 45146,
"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, http, curl",
"url": null
} |
python, simulation, pygame, vectorization
Title: Agent based Dengue transmission simulation
Question: I'm trying to implement the dynamics of Dengue transmission between mosquitoes and humans. I decided create two classes, one for the human population and another for the mosquitoes. Both are based on an abstract class. I tried to optimize the different methods of each class by vectorizing them with numpy matrices. It works okay. I'm want it to be as readable, maintainable and extendable as possible.
"""
File: population.py
Project: dengueSim
File Created: Tuesday, 3rd October 2023 5:43:09 pm
Author: Athansya
-----
License: MIT License
-----
Description: Population abstract class and its subclasses to simulate
human and mosquito populations dynamics during dengue infections.
"""
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from icecream import ic
import numpy as np
import pygame
# TODO Define scene to simulate (e.g. room, street, park)
# TODO Define time scale (e.g. minutes, hours, days, etc)
# TODO Define valid states given previous decisions
# TODO Define movement in scene for each agent (e.g. commuting, walking, flying)
# TODO Save states and counters in a file for plotting
# TODO Change Pygame framework to Manim for better visualization. | {
"domain": "codereview.stackexchange",
"id": 45147,
"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, simulation, pygame, vectorization",
"url": null
} |
python, simulation, pygame, vectorization
@dataclass(slots=True)
class Population(ABC):
"""
Abstract base population class. Handles positions, velocities and states of
the population. Includes abstract methods to be overriden by subclasses.
Attributes
----------
size : int
Population size.
max_position_x : float
Maximum x coordinate.
max_position_y : float
Maximum y coordinate.
max_velocity : float
Maximum velocity.
states : dict[str, int]
Dictionary of states.
states_color_map : dict[int, str]
Dictionary of colors.
_positions_matrix : np.ndarray
Matrix of positions.
_velocities_matrix np.ndarray
Matrix of velocities.
_states_matrix : np.ndarray
Matrix of states.
"""
size: int = 10
max_position_x: float = 500
max_position_y: float = 500
max_velocity: float = 10
states: dict[str, int] = field(
default_factory=lambda: {"susceptible": 0, "infected": 1, "recovered": 2}
)
states_color_map: dict[int, str] = field(
default_factory=lambda: {0: "blue", 1: "red", 2: "green"}
)
_positions_matrix: np.ndarray = field(init=False)
_velocities_matrix: np.ndarray = field(init=False)
_states_matrix: np.ndarray = field(init=False)
def __post_init__(self) -> None:
"""
Initialize positions, velocities and states matrices.
Returns
-------
None
"""
self._init_positions()
self._init_velocities()
self._init_states()
def _init_positions(self) -> None:
"""
PRIVATE METHOD
Initialize a matrix array of size (N, 2) where N is the
population size and 2 the x and y coordinates. Fills it
with random values from a uniform distribution with boundaries
between 0 and max_positions.
Returns
-------
None | {
"domain": "codereview.stackexchange",
"id": 45147,
"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, simulation, pygame, vectorization",
"url": null
} |
python, simulation, pygame, vectorization
Returns
-------
None
"""
self._positions_matrix = np.zeros(shape=(self.size, 2))
self._positions_matrix[:, 0] = np.random.uniform(
0, self.max_position_x, size=self.size
)
self._positions_matrix[:, 1] = np.random.uniform(
0, self.max_position_y, size=self.size
)
def _init_velocities(self) -> None:
"""
PRIVATE METHOD
Initialize a matrix array of size (N, 2) where N is the
population size and 2 the vx and vy velocity components.
Fills it with random values from a uniform distribution
based on the max_velocity.
Returns
-------
None
"""
self._velocities_matrix = np.random.uniform(
-self.max_velocity, self.max_velocity, size=(self.size, 2)
)
def _init_states(self) -> None:
"""
PRIVATE METHOD
Initialize a matrix array of size (N, 1) where N is the
population size and 1 the state. Assigns a random state,
excluding the "recovered" state.
Returns
-------
None
"""
self._states_matrix = np.random.choice(
list(self.states.values())[:-1], size=(self.size, 1)
)
def _handle_borders(self) -> None:
"""
PRIVATE METHOD
Check if positions are out of bounds and replace them.
Returns
-------
None
"""
# X-coordinate
self._positions_matrix[:, 0] = np.where(
self._positions_matrix[:, 0] > self.max_position_x, # Exceeded width
0, # Value to replace it with
self._positions_matrix[:, 0], # else keep the same
) | {
"domain": "codereview.stackexchange",
"id": 45147,
"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, simulation, pygame, vectorization",
"url": null
} |
python, simulation, pygame, vectorization
self._positions_matrix[:, 0] = np.where(
self._positions_matrix[:, 0] < 0, # Less than 0
self.max_position_x, # Value to replace it with
self._positions_matrix[:, 0], # else keep the same
)
# Y-coordinate
self._positions_matrix[:, 1] = np.where(
self._positions_matrix[:, 1] > self.max_position_y, # Exceeded height
0, # Value to replace it with
self._positions_matrix[:, 1], # else keep the same
)
self._positions_matrix[:, 1] = np.where(
self._positions_matrix[:, 1] < 0, # Less than 0
self.max_position_y, # Value to replace it with
self._positions_matrix[:, 1], # else keep the same
)
def draw(self, screen: pygame.Surface, radius: int | float) -> None:
"""
Draws the population as circles on the screen.
Parameters
----------
screen : pygame.Surface
Window to draw on.
radius : int | float
Radius of the circles.
Returns
-------
None
"""
for index, agent_pos in enumerate(self._positions_matrix):
pygame_vector_pos = pygame.Vector2(agent_pos[0], agent_pos[1])
pygame.draw.circle(
screen,
color=self.states_color_map[self._states_matrix[index][0]],
center=pygame_vector_pos,
radius=radius,
)
@abstractmethod
def move(self) -> None:
"""
ABSTRACT METHOD
Move the agents. MUST be overriden by subclasses.
Returns
-------
None
"""
pass
@abstractmethod
def update_velocity(self) -> None:
"""
ABSTRACT METHOD
Update agents velocities. MUST be overriden by subclasses.
Returns
-------
None | {
"domain": "codereview.stackexchange",
"id": 45147,
"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, simulation, pygame, vectorization",
"url": null
} |
python, simulation, pygame, vectorization
Returns
-------
None
"""
# TODO CHECK IF IT IS NECESSARY OR DELETE IT!
pass
@dataclass
class HumanPopulation(Population):
"""
Human agents population class. Inherits from Population class. Adds additional
properties, methods and overrides the move and update_velocity abstract methods.
Attributes
----------
time_to_recover : float = 50
Defines how much time must pass before a human can recover from infection.
time_to_susceptible : float = 50
Defines how much time must pass before a human can become susceptible.
In other words, it how much time a human remains immune to infection.
_infection_timer_matrix : np.ndarray = field(init=False)
Timer that keeps track of how long each human has been infected.
_recover_timer_matrix : np.ndarray = field(init=False)
Timer that keeps track of how long each human has been recovered from infection.
"""
# TODO CHECK IF FOLLOWING ATTRIBUTES ARE NECESSARY OR DELETE THEM
# Infected rate per infected vector
# B_i: float = 0
# Infection rate per infected host
# Beta_i: float = 0
# Susceptible birth rate
# mu: float = 1 / 65
# Recovery rate
# gamma: float = 365 / 7
# Temporary cross-immunity rate
# alpha: float = 2
time_to_recover: float = 50
time_to_susceptible: float = 50
_infection_timer_matrix: np.ndarray = field(init=False)
_recover_timer_matrix: np.ndarray = field(init=False)
def _init_states(self) -> None:
"""
Initializes the states matrix and its related timers.
Returns
-------
None
"""
# Every human is susceptible at the start
self._states_matrix = np.zeros(shape=(self.size, 1))
self._infection_timer_matrix = np.zeros(shape=(self.size, 1))
self._recover_timer_matrix = np.zeros(shape=(self.size, 1)) | {
"domain": "codereview.stackexchange",
"id": 45147,
"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, simulation, pygame, vectorization",
"url": null
} |
python, simulation, pygame, vectorization
def move(self, random: bool = False) -> None:
"""
Moves the humans, updating their positions.
Parameters
----------
random : bool, optional
Whether to move randomly or not, by default False.
Returns
-------
None
"""
if random:
self._init_velocities()
self._positions_matrix += self._velocities_matrix
self._handle_borders()
def update_velocity(self) -> None:
pass
def _time_infected(self) -> None:
"""
PRIVATE METHOD
Updates the timers that keep track of how long each human has been infected.
Returns
-------
None
"""
infected_humans = self._states_matrix == self.states["infected"]
if np.any(infected_humans):
self._infection_timer_matrix[infected_humans] += 1
def recover(self) -> None:
"""
Checks which humans are ready to recover from infection and changes their state.
Returns
-------
None
"""
self._time_infected()
humans_ready_to_recover = self._infection_timer_matrix >= self.time_to_recover
if np.any(humans_ready_to_recover):
self._states_matrix[humans_ready_to_recover] = self.states["recovered"]
self._infection_timer_matrix[humans_ready_to_recover] = 0
def _time_recovered(self) -> None:
"""
PRIVATE METHOD
Updates the timers that keep track of how long each human has been recovered (immune).
Returns
-------
None
"""
infected_humans = self._states_matrix == self.states["recovered"]
if np.any(infected_humans):
self._recover_timer_matrix[infected_humans] += 1
def make_susceptible(self) -> None:
"""
Checks which humans are ready to be suscpetible to infection and changes their state. | {
"domain": "codereview.stackexchange",
"id": 45147,
"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, simulation, pygame, vectorization",
"url": null
} |
python, simulation, pygame, vectorization
Returns
-------
None
"""
self._time_recovered()
humans_ready_to_susceptible = self._recover_timer_matrix >= self.time_to_susceptible
if np.any(humans_ready_to_susceptible):
self._states_matrix[humans_ready_to_susceptible] = self.states["susceptible"]
self._recover_timer_matrix[humans_ready_to_susceptible] = 0
@dataclass
class MosquitoPopulation(Population):
"""
Mosquito agents population class. Inherits from Population class. Adds additional
properties, methods and overrides the move and update_velocity abstract methods.
Attributes
----------
bite_radius : float = 1
Mosquito bite radius area.
bite_probability : float = 0.5
Probability of biting a human.
transmission_probability : float = 0.5
Probability of Dengue transmission from a mosquito to a human
"""
# TODO CHECK IF FOLLOWING ATTRIBUTES ARE NECESSARY OR DELETE THEM
# Susceptible birth rate
# upsilon: float = 36.5
# Infection rate per host
# var_theta: float = 73
# Magnitude of sinusoidal fluctuations
# eta: float = 0 # or 0.35
# Ratio of likelihood of transmission from hosts with
# secondary and hosts primary infection to vectors
# var_phi: float = 0 # or 12
# Phase
# phi: float = 0
bite_radius: float = 1
bite_probability: float = 0.5
transmission_probability: float = 0.5
def move(self, random: bool = False) -> None:
"""
Moves the mosquitos
Parameters
----------
random : bool, optional
_description_, by default False
"""
if random:
self._init_velocities()
self._positions_matrix += self._velocities_matrix
self._handle_borders()
def update_velocity(self) -> None:
pass | {
"domain": "codereview.stackexchange",
"id": 45147,
"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, simulation, pygame, vectorization",
"url": null
} |
python, simulation, pygame, vectorization
def update_velocity(self) -> None:
pass
def bite_humans(self, human_population: HumanPopulation) -> None:
"""
For each mosquito in the population, check if it is close to a human.
If it is, checks the probability of biting and infecting the human.
Parameters
----------
human_population : HumanPopulation
Human agents population.
Returns
-------
None
"""
# For each mosquito check if it is close to a human
for mosquito_pos in self._positions_matrix:
distances = np.linalg.norm(
human_population._positions_matrix - mosquito_pos, axis=1
)
close_to_human = distances < self.bite_radius
susceptible_humans = human_population._states_matrix == self.states["susceptible"]
susceptible_humans = susceptible_humans.reshape(len(susceptible_humans))
# If there are close humans, update their state
if np.any(close_to_human):
# Bite and infect with certain probability. Note that events are dependent and
# the probability of an event A and B happening is the product of the probabilities
probabilities_array = np.random.random(
size=close_to_human.shape[0]
) <= (self.bite_probability * self.transmission_probability)
# Only changes humans state if they are close to the mosquito AND the transmission probability is met
# AND the human is susceptible
human_population._states_matrix[
close_to_human
& probabilities_array
& susceptible_humans
] = self.states["infected"]
If you want to test it here is a simple code to run the simulation:
from population import HumanPopulation, MosquitoPopulation
import pygame
WIDTH = 500
HEIGHT = 500
FPS = 60 | {
"domain": "codereview.stackexchange",
"id": 45147,
"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, simulation, pygame, vectorization",
"url": null
} |
python, simulation, pygame, vectorization
WIDTH = 500
HEIGHT = 500
FPS = 60
MOSQUITO_RADIUS = 1
HUMAN_RADIUS = 5
# Host population
N = 100
# Vector population
M = 1000
def main():
# States dict
states = {"susceptible": 0, "infected": 1, "recovered": 2}
color_map = {
states["susceptible"]: "blue",
states["infected"]: "red",
states["recovered"]: "green",
}
mosquitoes = MosquitoPopulation(
size=M,
max_position_x=WIDTH,
max_position_y=HEIGHT,
max_velocity=50,
states=states,
states_color_map=color_map
)
humans = HumanPopulation(
size=N,
max_position_x=WIDTH,
max_position_y=HEIGHT,
max_velocity=10,
states=states,
states_color_map=color_map
)
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
running = True
# Time to move or not
timer_to_move = 0
while running:
screen.fill((255, 255, 255))
# poll for events
# pygame.QUIT event means the user clicked X to close your window
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Mosquito population
mosquitoes.draw(screen, MOSQUITO_RADIUS)
# Move mosquitos every certain time
if timer_to_move % 10 == 0:
mosquitoes.move(random=True)
mosquitoes.bite_humans(humans)
# Human population
humans.draw(screen, HUMAN_RADIUS)
if timer_to_move % 10 == 0:
humans.move(random=True)
else:
humans.move()
humans.recover()
humans.make_susceptible()
pygame.display.flip()
clock.tick(FPS)
timer_to_move += 1
if __name__ == "__main__":
main()
Answer: use Enum
This is a bit odd:
states = {"susceptible": 0, "infected": 1, "recovered": 2} | {
"domain": "codereview.stackexchange",
"id": 45147,
"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, simulation, pygame, vectorization",
"url": null
} |
python, simulation, pygame, vectorization
Answer: use Enum
This is a bit odd:
states = {"susceptible": 0, "infected": 1, "recovered": 2}
Normally we'd expect to see an
Enum
in that situation.
Having a separate color_map seems tedious,
when color could just be an Enum attribute.
In SIR
modeling you might prefer to substitute "removed" for "recovered".
That clarifies we're describing individuals who are deceased or,
through activity of the immune system, are now removed
from the "susceptible" population.
use type hints
class Population(ABC):
Thank you for the lovely docstring.
The English sentences were helpful.
But then you go into a long "Attributes" section.
It's nice enough.
But I encourage you to delete it.
All the identifiers are wonderful and informative.
The docstring does not further illuminate them.
You mention their types, but you do it in a way
that mypy cannot access them.
Much better to delete them
and add corresponding type annotations.
Then humans would read them just the same,
but significantly, humans would believe them,
secure in the knowledge that
mypy
had verified them.
Oh, wait, now I see down in the code that you gave the type of everything
twice.
I imagine they're all in sync?
But I'm not going to scan back and forth to check on that.
Comments are nice.
Machine verified comments are much nicer.
If I see same thing in two ways,
I will just assume that one of them is out of sync,
because sooner or later that's sure to be the case.
Several methods are annotated def ...() -> None:,
in which case "Returns NONE" in a docstring
just isn't helpful.
Couldn't sphinx infer that from annotations?
conventional naming
def _init_positions(self) -> None:
"""
PRIVATE METHOD
Yeah, I got that loud
and clear from the function name, it's _private. You don't have to tell me
twice.
self._positions_matrix = np.zeros(shape=(self.size, 2)) | {
"domain": "codereview.stackexchange",
"id": 45147,
"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, simulation, pygame, vectorization",
"url": null
} |
python, simulation, pygame, vectorization
self._positions_matrix[:, 0] = np.random.uniform(
0, self.max_position_x, size=self.size
)
self._positions_matrix[:, 1] = np.random.uniform(
0, self.max_position_y, size=self.size
)
Sooo, this is lovely, very clear, thank you.
It calls into question the "max_position_{x,y}" decision.
You might have been happier with a "max_position" vector of 2-tuples,
as the assignments here would be more compact.
Ooohh, lookitdat, it appears _init_velocities adopted that very approach. Good.
clip
The _handle_borders method is lovely,
it does exactly what you'd expect.
We import numpy, and it turns out that is rather
a large library. If there's a math concept you can
imagine finding on wikipedia, there's a fair chance
you can find it in the numpy documentation, as well.
Here, you might prefer to use the
clip
function.
float annotations
def draw(self, screen: pygame.Surface, radius: int | float) -> None:
Thank you for the optional type annotations, they are helpful.
nit: It would be enough to declare radius: float.
Why?
https://peps.python.org/pep-0484
this PEP proposes a straightforward shortcut ... : when an argument is annotated as having type float, an argument of type int is acceptable
Linters such as mypy definitely follow this advice.
pygame_vector_pos = ...
I understand where the name for that local variable came from,
but it's a trifle verbose -- pos would suffice.
no pass
@abstractmethod
def move(self) -> None:
"""
ABSTRACT METHOD
Move the agents. MUST be overriden by subclasses.
Returns
-------
None
"""
pass | {
"domain": "codereview.stackexchange",
"id": 45147,
"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, simulation, pygame, vectorization",
"url": null
} |
python, simulation, pygame, vectorization
Returns
-------
None
"""
pass
nit: We write pass where it is syntactically necessary.
But here, a """docstring""" is present, so no need for pass.
Plus the usual remark about @abstractmethod and "ABSTRACT METHOD"
saying the same thing.
Similarly for ) -> None: and "Returns None".
Oh, wait, here's trouble!
signal error upon failure to override
... MUST be overriden by subclasses.
And then we permissively pass.
No.
Don't do that.
It would be much more helpful to raise a fatal error
explaining that subclass neglected to implement an important override.
DRY
class HumanPopulation(Population):
"""
Human agents population class. Inherits from Population class.
Yup, we got that loud and clear from the ...(Population): part,
no need to say it again in English.
discretize
The scaling on this looks ugly as both populations increase:
def bite_humans(self, human_population: HumanPopulation) -> None:
...
# For each mosquito check if it is close to a human
for mosquito_pos in self._positions_matrix:
distances = np.linalg.norm(
human_population._positions_matrix - mosquito_pos, axis=1
)
close_to_human = distances < self.bite_radius
Consider discretizing to some grid size,
and narrow the checks based on whether insect + human
are within the same grid cell.
This codebase would benefit from the addition of a robust
test suite
plus code coverage measurements.
The author was clearly trying to produce maintainable code.
As features are added in the coming months,
I am confident that the codebase will continue to be of high quality
and easily approached by new maintenance engineers that are
recruited to the team.
This code appears to achieve its design goals.
I would be willing to delegate or accept maintenance tasks on this codebase. | {
"domain": "codereview.stackexchange",
"id": 45147,
"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, simulation, pygame, vectorization",
"url": null
} |
c++, email, state-machine, sml
Title: IMAP client impementation on State Machine boost-ext/sml
Question: I made IMAP(IMAPS) notifier on boost-ext/sml state machine.
There is an opinion that networking is best done on machines.
Compile in C++20. Tested on GMail server. Uses karastojko/mailio (and therefore boost+openssl)
Just checking new emails every c_RecheckInterval_minutes minutes.
Here are two key points that concern me:
State machine definition in Impl.h inside struct ImapsSm;
State machine using in Thread.h inside void Thread::run().
Impl.h
#pragma once
namespace StateMachine {
// for action
typedef std::function< void(const std:string&) > setActiveTip_t;
// events
struct CheckAccess{};
struct Unavailable{};
struct StartLoop{};
struct HasBreak{};
struct RenewEmail{};
struct ContinueLoop{};
// dependencies
struct dependencyImaps {
const Credentials m_credentials;
std::chrono::seconds c_connectTimeout_sec;
};
struct dependencyEmailCount {
setActiveTip_t fnSetActiveTip;
unsigned long m_currentEmailCount, m_lastEmailCount;
std::string lastFrom, lastSubject
};
struct dependencyBreakableSleep {
const std::chrono::seconds c_RecheckInterval_sec;
std::condition_variable *m_pConditionVariable;
std::mutex *m_pcvMutex;
bool m_bBreak;
};
struct dependencyAvailable {
bool m_bAvailable;
}; | {
"domain": "codereview.stackexchange",
"id": 45148,
"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++, email, state-machine, sml",
"url": null
} |
c++, email, state-machine, sml
namespace Action {
struct Imap { void operator()(dependencyImaps &imaps, dependencyEmailCount& counter) {
std::unique_ptr< mailio::imaps > pmailio;
pmailio = std::make_unique< mailio::imaps >(
imaps.m_credentials.host
, imaps.m_credentials.port
, imaps.c_connectTimeout_sec
);
pmailio ->authenticate(
imaps.m_credentials.login
, imaps.m_credentials.password
, mailio::imaps::auth_method_t::LOGIN
);
const char mailbox[] = "inbox";
pmailio ->select( mailbox );
std::list< mailio::imap::search_condition_t > search_condition;
// UNSEEN exclude ALL
search_condition.emplace_back( mailio::imap::search_condition_t::UNSEEN );
std::list<unsigned long> results;
pmailio ->search( search_condition, results );
unsigned long lastSequenceNumber = results.back( );
// Find out sender and subject
mailio::message lastMessage;
bool header_only;
pmailio ->fetch( mailbox, lastSequenceNumber, lastMessage, header_only = true );
counter.m_currentEmailCount = lastSequenceNumber;
counter.lastFrom = lastMessage.from_to_string( );
counter.lastSubject = lastMessage.subject( );
} } Imap;
struct BreakableSleep { void operator()(dependencyBreakableSleep &dependency) {
std::unique_lock< std::mutex > lock( *dependency.m_pcvMutex );
std::cv_status finishedWaiting = dependency.m_pConditionVariable ->wait_until(
lock
, std::chrono::system_clock::now( ) + dependency.c_RecheckInterval_sec
);
if ( std::cv_status::no_timeout == finishedWaiting )
dependency.m_bBreak = true;
} } BreakableSleep;
struct InitialEmailCount { void operator()(dependencyEmailCount& dependency) {
dependency.m_lastEmailCount = dependency.m_currentEmailCount;
} } InitialEmailCount; | {
"domain": "codereview.stackexchange",
"id": 45148,
"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++, email, state-machine, sml",
"url": null
} |
c++, email, state-machine, sml
struct EmailCounter { void operator()(dependencyEmailCount& dependency) {
if ( dependency.m_currentEmailCount <= dependency.m_lastEmailCount )
return;
dependency.m_lastEmailCount = dependency.m_currentEmailCount;
dependency.fnSetActiveTip( std::string{ }
+ "SmallImapsNotifier: last email\n"
+ "from: '" + dependency.lastFrom + "'\n"
+ "subject: '" + dependency.lastSubject + "'\n"
);
} } EmailCounter;
struct InboxAvailable { void operator()(dependencyAvailable& dependency) {
dependency.m_bAvailable = true;
} } InboxAvailable;
} // namespace Action
struct guardAvailable {
bool operator()(dependencyAvailable& dependency) const {
return !dependency.m_bAvailable;
}
} guardAvailable;
struct guardBreak {
bool operator()(dependencyBreakableSleep &dependency) const {
return dependency.m_bBreak;
}
} guardBreak;
struct ImapsSm {
auto operator()() const noexcept {
using namespace boost::sml;
using namespace Action;
return make_transition_table(
// Using `state<>` to avoid print anonymous on sml logging in MSVC
*state<struct idle> + event<CheckAccess> / Imap = "TryInbox"_s
, "TryInbox"_s + event<Unavailable> [guardAvailable] = X
, "TryInbox"_s + event<StartLoop> / InitialEmailCount = "Waiting"_s
, "TryInbox"_s + on_entry<_> / InboxAvailable
, "Waiting"_s + event<HasBreak> [guardBreak] = X
, "Waiting"_s + event<RenewEmail> / Imap= "RenewedEmail"_s
, "Waiting"_s + on_entry<_> / BreakableSleep
, "RenewedEmail"_s + event<Unavailable> [guardAvailable] = X
, "RenewedEmail"_s + event<ContinueLoop> = "Waiting"_s
, "RenewedEmail"_s + on_entry<_> / ( InboxAvailable, EmailCounter )
, *("exceptions handling"_s) + exception<_> / [](dependencyAvailable& dependency) { dependency.m_bAvailable = false; } = X
);
}
};
} // namespace StateMachine | {
"domain": "codereview.stackexchange",
"id": 45148,
"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++, email, state-machine, sml",
"url": null
} |
c++, email, state-machine, sml
Thread.h
#pragma once
class Thread {
static constexpr std::chrono::seconds c_ReconnectTry_sec{ 60 };
static constexpr std::chrono::seconds c_ConnectTimeout_sec{ 30 };
static constexpr std::chrono::minutes c_RecheckInterval_minutes{ 5 };
Credentials m_credentials;
StateMachine::setActiveTip_t m_clbSetActiveTip;
std::condition_variable m_cv;
std::mutex m_cvMutex;
std::atomic_bool m_bStop;
std::thread m_thread;
bool breakableWaitReconnect_() {
if ( m_bStop )
return false;
std::unique_lock< std::mutex > lock( m_cvMutex );
std::cv_status waiting = m_cv.wait_until( lock,
std::chrono::system_clock::now( ) + c_ReconnectTry_sec );
return std::cv_status::timeout == waiting;
}
// thread
void run() {
namespace sml = boost::sml;
using namespace StateMachine;
do {
dependencyImaps imaps = { m_credentials, c_ConnectTimeout_sec };
dependencyEmailCount counter = { m_clbSetActiveTip };
dependencyBreakableSleep sleep = {
c_RecheckInterval_minutes
, &m_cv
, &m_cvMutex
};
sml::sm< ImapsSm > sm{ imaps, counter, sleep };
sm.process_event( CheckAccess{ } );
sm.process_event( Unavailable{ } );
sm.process_event( StartLoop{ } );
while ( !sm.is( sml::X ) ) {
sm.process_event( HasBreak{ } );
sm.process_event( RenewEmail{ } );
sm.process_event( Unavailable{ } );
sm.process_event( ContinueLoop{ } );
}
} while ( breakableWaitReconnect_( ) );
} | {
"domain": "codereview.stackexchange",
"id": 45148,
"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++, email, state-machine, sml",
"url": null
} |
c++, email, state-machine, sml
public:
Thread(
const Credentials &credentials
, StateMachine::setActiveTip_t clbSetActiveTip
)
: m_credentials( credentials )
, m_clbSetActiveTip( clbSetActiveTip )
, m_bStop( false )
{
// will be init in last order
m_thread = { &Thread::run, this };
}
void stop() {
m_bStop = true;
m_cv.notify_all( );
m_thread.join( );
}
};
demo main.cpp, with invalid login and password
#include "pch.h"
#include <mailio/imap.hpp>
#include <boost/sml.hpp>
struct Credentials {
std::string host;
uint16_t port;
std::string login, password;
};
#include "Impl.h"
#include "Thread.h"
void main() {
Credentials credentials = {
"imap.gmail.com", 993, "%login%", "%password%"
};
auto imapsThread = std::make_unique< Thread >(
credentials
, [](const std::string&str) {
std::cout << str;
}
);
getchar( );
}
How does all this correspond to the "canons" of state machines?
Not overkill?
Full code on GitHub repo
Thanks!
Answer: Unnecessary use of std::unique_ptr
You are using std::unique_ptr when there is no need for it. Both pmailio and imapsThread can just be stored by value:
struct Imap { void operator()(dependencyImaps &imaps, dependencyEmailCount& counter) {
mailio::imaps pmailio(…);
pmailio.authenticate(…);
…
}
…
void main() {
Credentials credentials = {…};
Thread imapsThread(credentials, …);
getchar();
}
Lambdas are structs
I see you write this pattern a few times:
struct Foo {
void operator()(/* arguments */…) {
/* body */
…
}
} Foo;
A lambda is just syntactic sugar for exactly that pattern! So you could also write:
auto Foo = [](/* arguments */…) {
/* body */
…
}; | {
"domain": "codereview.stackexchange",
"id": 45148,
"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++, email, state-machine, sml",
"url": null
} |
c++, email, state-machine, sml
Incorrect use of Hungarian notation
I see you are using some form of Hungarian notation. The problem with Hungarian notation is that nothing checks whether it is applied correctly. If you make mistakes, the whole benefit of Hungarian notation is kind of gone. Consider for example c_connectTimeout_sec. The c_ prefix indicates that it's a const variable, however it is not. At the same time, m_credentials is const but that's not reflected in the prefix. You also use cv for condition variables, but then why is it m_cvMutex, when that variable is not a condition variable?
My advice is to stop using Hungarian notation, except for maybe using the prefix m_ to indicate that something is a class member variable, but only because the latter is useful to avoid name conflicts with parameters and local variables.
Don't mix atomics and mutexes
Make m_bStop a regular bool, and read and modify it only when holding a lock. Consider for example that breakableWaitReconnect_() has just checked m_bStop, and its value was false. The before it does anything else, stop() is called, which sets m_bStop to true (which does nothing), and which then calls m_cv.notify_all()(which also does nothing because no other thread iswait()ing yet). Then breakableWaitReconnect_() continues, locks the mutex and callsl m_cv.wait_until(…). Now you have to wait at least 60 seconds before that thread stops.
The correct way to handle this is to use a variant of wait() that uses a predicate, and to only modify m_bStop while holding the mutex:
bool breakableWaitReconnect_() {
std::lock_guard lock(m_cvMutex);
auto waiting = m_cv.wait_for(lock, c_ReconnectTry_sec, []{
return m_bStop;
});
return std::cv_status::timeout == waiting;
}
…
void stop() {
{
std::lock_guard lock(m_cvMutex);
m_bStop = true;
}
m_cv.notify_all( );
m_thread.join( );
} | {
"domain": "codereview.stackexchange",
"id": 45148,
"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++, email, state-machine, sml",
"url": null
} |
c++, email, state-machine, sml
Use wait_for() instead of wait_until()
If you only need to wait for a given period, then use wait_for(). Apart from not needing the manual calculation of the point in time to wait until, wait_for() also uses a steady clock, which is not affected by things like daylight savings time changes, or just someone adjusting their computer's clock. This avoids your code accidentally waiting for hours instead of seconds.
About the use of state machines
There are several ways in which you could have approached this problem. The use of an explicit state machine is one way. The drawback is that you have to explicitly define all the states and their relationships with each other. Coroutines are another approach, which allows you to write code in a more natural way. Boost has coroutine libraries as well, and C++20 added native supported for coroutines, but you still need some external library at the moment to make effective use of them.
I don't think your use of Boost SML looks wrong, but I have never used it myself.
Naming things
Some of your class names are very generic, and don't describe what they actually do. Consider Thread for example. That's way more than just being something like std::thread. You could name it IMAPThread. However, while it is using a thread, that might not be the most important thing to know about it. More important would be to know if this implements a client or a server. So perhaps IMAPClient is a better name? The same goes for Credentials: perhaps IMAPClientCredentials is more accurate.
Also consider using a namespace to group your classes together, and/or use the fact that you can nest class declarations. Since everything is related to IMAP, maybe use a hierarchy like:
namespace IMAP {
class Client {
public:
class Credentials {
…
};
…
};
}
Then your main() could look like:
void main() {
using IMAP;
Client::Credentials credentials = {…};
Client client(credentials, …);
getchar();
} | {
"domain": "codereview.stackexchange",
"id": 45148,
"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++, email, state-machine, sml",
"url": null
} |
c++, game, console, hangman
Title: Little CLI game in C++ with random words
Question: the game is quite simple, you have to constantly guess the letters of a hidden word, but has a limited number of wrong attempts. The word you are looking for should be a random word from Wikipedia. I would like to get a review from you.
I used libcURL and the cURLpp wrapper.
Compilation (with Cygwin): g++ -L/usr/local/lib Hangman.cpp -o hm.exe -lcurl -lcurlpp
Hangman.cpp:
#include <iostream>
#include <vector>
#include <string>
#include <regex>
#include <curlpp/Easy.hpp>
#include <curlpp/cURLpp.hpp>
#include <curlpp/Options.hpp>
using namespace std;
string getRandomWordFromWikipedia()
{
curlpp::Cleanup myCleanup;
curlpp::Easy handle;
handle.setOpt(curlpp::options::Url(string("https://en.wikipedia.org/wiki/special:random")));
handle.setOpt(curlpp::options::FollowLocation(true));
ostringstream os;
os << handle;
string seq = os.str();
regex rgx1("<h1.+id=\"firstHeading\"[^>]*>(.+)</h1>");
regex rgx2("<[^>]+>(.+)</[^>]+>");
smatch sm1;
if (regex_search(seq, sm1, rgx1))
{
string seq2 = sm1[1];
while (seq2.find("<") != string::npos)
{
smatch sm2;
if (regex_search(seq2, sm2, rgx2))
{
seq2 = sm2[1];
}
else
{
return "";
}
}
return seq2;
}
return "";
}
struct ToFind
{
string w1;
string w2;
int tries = 0;
int right = 0;
int health = 100;
int hintsLeft = 2;
};
void initToFind(struct ToFind *stf)
{
string w1 = getRandomWordFromWikipedia();
string w2;
for (int i = 0; i < w1.size(); i++)
{
if (w1[i] == ' ')
{
w2 += " ";
}
else
{
w2 += "_ ";
}
}
stf->w1 = w1;
stf->w2 = w2;
} | {
"domain": "codereview.stackexchange",
"id": 45149,
"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++, game, console, hangman",
"url": null
} |
c++, game, console, hangman
int findInToFind(struct ToFind *stf, char c)
{
int f = 0;
for (int i = 0; i < stf->w1.size(); i++)
{
if (stf->w1[i] == c && stf->w2[i * 2] == '_')
{
f++;
stf->right++;
stf->w2[i * 2] = c;
}
}
stf->tries++;
if (f > 0)
{
stf->right++;
}
else
{
stf->health -= 10;
}
return f;
}
void printStatistics(struct ToFind *stf)
{
static int round = 1;
cout << "Round: " << round << endl;
cout << "Tries: " << stf->tries << endl;
cout << "Rights: " << stf->right << endl;
cout << "Health: " << stf->health << " from 100" << endl;
cout << "Hints left: " << stf->hintsLeft << endl;
round++;
}
int main(int argc, char const *argv[])
{
struct ToFind stf;
initToFind(&stf);
if (stf.w1.empty())
{
return EXIT_FAILURE;
}
cout << "The game begins!" << endl;
cout << "The word you are looking for has a length of " << stf.w1.size() << endl;
while (stf.w2.find("_") != string::npos && stf.health > 0)
{
printStatistics(&stf);
cout << stf.w2 << endl;
cout << "Which letter next?" << endl;
char c;
cin >> c;
int f = findInToFind(&stf, c);
if (f > 0)
{
cout << "Great, the letter " << c << " appeared " << f << " times!" << endl;
}
else
{
cout << "Unfortunately you weren't lucky this time ..." << endl;
}
}
cout << "The game is over ..." << endl;
if (stf.health > 0)
{
cout << "Great, you found the word " << stf.w1 << endl;
}
else
{
cout << "Unfortunately you didn't find the word " << stf.w1 << " and you're dead." << endl;
}
printStatistics(&stf);
cout << "Any char to continue ..." << endl;
char c;
cin >> c;
return EXIT_SUCCESS;
} | {
"domain": "codereview.stackexchange",
"id": 45149,
"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++, game, console, hangman",
"url": null
} |
c++, game, console, hangman
Answer: General Observations
An interesting new twist on an old game! Using Wikipedia as a source gives a lot of possible words.
There is a lot of good ideas here, but there can be some improvement. An example of possible improvements is to make the struct ToFind data structure more object oriented. More on this later.
The code already follows some good best practices such as always using braces ({ and }) around code blocks.
Using raw pointers (struct ToFind* stf) is generally considered a bad practice in C++, there are better ways to do what the code is doing. The use of the raw pointer makes this code look more like C rather than C++.
For performance reasons, it is better to end output lines with "\n" rather than using std::endl. std::endl flushes the output buffer which generally isn't necessary and could be a system call. Using "\n" rather than std::endl also seems to simplify the code a little bit:
int main(int argc, char const* argv[])
{
struct ToFind stf;
initToFind(&stf);
if (!stf.hasWord())
{
return EXIT_FAILURE;
}
std::cout << "The game begins!\n";
std::cout << "The word you are looking for has a length of " << stf.w1.size() << "\n";
while (stf.w2.find("_") != string::npos && stf.health > 0)
{
stf.printStatistics();
std::cout << stf.w2 << "\n";
std::cout << "Which letter next?\n";
char c;
cin >> c;
int f = findInToFind(&stf, c);
if (f > 0)
{
std::cout << "Great, the letter " << c << " appeared " << f << " times!\n";
}
else
{
std::cout << "Unfortunately you weren't lucky this time ...\n";
}
}
std::cout << "The game is over ..." << "\n";
if (stf.stillAlive())
{
std::cout << "Great, you found the word " << stf.w1 << "\n";
}
else
{
std::cout << "Unfortunately you didn't find the word " << stf.w1 << " and you're dead. \n";
}
stf.printStatistics(); | {
"domain": "codereview.stackexchange",
"id": 45149,
"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++, game, console, hangman",
"url": null
} |
c++, game, console, hangman
}
stf.printStatistics();
std::cout << "Any char to continue ...\n";
char c;
cin >> c;
return EXIT_SUCCESS;
} | {
"domain": "codereview.stackexchange",
"id": 45149,
"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++, game, console, hangman",
"url": null
} |
c++, game, console, hangman
Please note that main() is doing too much, it should be one or two more functions.
Avoid using namespace std;
If you are coding professionally you probably should get out of the habit of using the using namespace std; statement. The code will more clearly define where cout and other identifiers are coming from (std::cin, std::cout). As you start using namespaces in your code it is better to identify where each function comes from because there may be function name collisions from different namespaces. The identifiercout you may override within your own classes, and you may override the operator << in your own classes as well. This stack overflow question discusses this in more detail.
Object Oriented Code
The code could be simplified if the struct ToFind contained a constructor and some methods (member functions). Personally I would use a class rather than a struct, so that the member variables could be private, but to give you some idea look at the following code and also the modified example of main() above. Please note that making this object oriented removes the need to pass a pointer around.
struct ToFind
{
std::string w1;
std::string w2;
int tries;
int right;
int health;
int hintsLeft;
ToFind()
: tries(0), right(0), health(100), hintsLeft(2)
{
}
ToFind(std::string word)
: w1(word), tries(0), right(0), health(100), hintsLeft(2)
{
for (int i = 0; i < w1.size(); i++)
{
if (w1[i] == ' ')
{
w2 += " ";
}
else
{
w2 += "_ ";
}
}
}
void setWord(std::string word1)
{
w1 = word1;
for (int i = 0; i < w1.size(); i++)
{
if (w1[i] == ' ')
{
w2 += " ";
}
else
{
w2 += "_ ";
}
}
} | {
"domain": "codereview.stackexchange",
"id": 45149,
"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++, game, console, hangman",
"url": null
} |
c++, game, console, hangman
void printStatistics()
{
static int round = 1;
std::cout << "Round: " << round << "\n";
std::cout << "Tries: " << tries << "\n";
std::cout << "Rights: " << right << "\n";
std::cout << "Health: " << health << " from 100" << "\n";
std::cout << "Hints left: " << hintsLeft << "\n";
round++;
}
bool hasWord()
{
return !w1.empty();
}
bool stillAlive()
{
return health > 0;
}
int findInToFind(char c)
{
int f = 0;
for (int i = 0; i < w1.size(); i++)
{
if (w1[i] == c && w2[i * 2] == '_')
{
f++;
right++;
w2[i * 2] = c;
}
}
tries++;
if (f > 0)
{
right++;
}
else
{
health -= 10;
}
return f;
}
}; | {
"domain": "codereview.stackexchange",
"id": 45149,
"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++, game, console, hangman",
"url": null
} |
javascript
Title: Modernized Javascript randomULID() Generator - Smaller and Optimized
Question: I've finally finished these 2 scripts and would like to get some feedback.
Seeking feedback on a modernized ULID (Universally Unique
Lexicographically Sortable Identifier) generator in Javascript.
Reduced size compared to examples on GitHub.
Code includes functions for encoding BigInt as Base32, decoding
timestamps, and generating ULIDs.
Looking for code review and optimization suggestions if it isn't
already compliant.
As you can see, Monotonic fills the Set almost twice as fast from sheer uniqueness.
See you later UUID?
Test Results - randomULID()
- Processor.....: Intel Xeon W-1390P @ 3.5GHz 32GB RAM
- Duration......: 2.7 sec @ 366,032/s @ 366/ms
- Iterations....: 1,000,000
- Collisions....: 0
- Set Bytes.....: 26,000,000 bytes
- Set Kilobytes.: 25,391 Kilobytes
- Set Megabytes.: 25 Megabytes
- Collision Test complete!
Test Results - randomMULID()
- Processor.....: Intel Xeon W-1390P @ 3.5GHz 32GB RAM
- Duration......: 1.9 sec @ 531,350/s @ 531/ms
- Iterations....: 1,000,000
- Collisions....: 0
- Set Bytes.....: 26,000,000 bytes
- Set Kilobytes.: 25,391 Kilobytes
- Set Megabytes.: 25 Megabytes
- Collision Test complete!
ULID.js | {
"domain": "codereview.stackexchange",
"id": 45150,
"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",
"url": null
} |
javascript
"use strict";
/**
* Global variables to keep track of the last generated timestamp and random value.
*/
let lastTimestamp = 0n; // Initialize a variable to store the last used timestamp.
let lastRandomValue = 0n; // Initialize a variable to store the last used random value.
/**
* Crockford's Base32 alphabet for encoding.
*/
const alphabet = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
/**
* Encodes a given BigInt number into a Base32 string.
* @param {bigint} number - The BigInt number to encode.
* @param {number} length - The length of the encoded string.
* @returns {string} The Base32 encoded string.
*/
function encodeBase32(number, length) {
// Initialize an empty string to hold the Base32 output.
let output = "";
// Loop `length` times to create the Base32 string.
for (let i = 0; i < length; i++) {
// Mask the last 5 bits of `number`, find the corresponding alphabet, and prepend to `output`.
output = alphabet[Number(number & 0x1fn)] + output;
// Right-shift `number` by 5 bits, effectively removing the bits that were just processed.
number >>= 5n;
}
// Return the Base32-encoded string.
return output;
}
/**
* Decodes the timestamp from a given ULID string.
* The function decodeTimestamp takes a ULID string ulid and returns a
* JavaScript Date object representing the timestamp encoded in the first
* 10 characters (48 bits) of the ULID.
* @param {string} ulid - The ULID string to decode.
* @returns {Date} The decoded timestamp as a JavaScript Date object.
*/
function decodeTimestamp(ulid) {
// 01HAYR6EKZ QDS8N9Y9PPBVG7EQ
// Extract the first 10 characters (48 bits) from the ULID string, representing the timestamp.
const timePart = ulid.slice(0, 10);
// Initialize a BigInt to hold the decoded timestamp.
let timestamp = 0n;
// Loop through each character in the time part of the ULID.
for (const char of timePart) { | {
"domain": "codereview.stackexchange",
"id": 45150,
"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",
"url": null
} |
javascript
// Loop through each character in the time part of the ULID.
for (const char of timePart) {
// Left-shift `timestamp` by 5 bits and OR it with the index of `char` in the alphabet, converted to BigInt.
timestamp = (timestamp << 5n) | BigInt(alphabet.indexOf(char));
}
// Convert the BigInt timestamp to Number and return it as a JavaScript Date object.
return new Date(Number(timestamp));
}
/**
* Generates a ULID (Universally Unique Lexicographically Sortable Identifier).
* @returns {Promise<string>} A promise that resolves to a ULID string.
*
* - The function `randomULID` asynchronously generates a ULID string by
* combining a 48-bit timestamp and 80 bits of cryptographically secure
* random data. It returns a Promise that resolves to this ULID string.
*/
async function randomULID() {
// Get the current timestamp as a BigInt.
const timestamp = BigInt(Date.now());
// Create a buffer to hold 10 bytes of random data.
const randomBuffer = new Uint8Array(10);
// Populate the buffer with Web Crypto API cryptographically secure random values.
crypto.getRandomValues(randomBuffer);
// Initialize a BigInt to hold the random value.
let randomValue = 0n;
// Loop through the random buffer.
for (const byte of randomBuffer) {
// Left-shift `randomValue` by 8 bits and OR it with each byte, converted to BigInt.
randomValue = (randomValue << 8n) | BigInt(byte);
}
// Encode the timestamp using the encodeBase32 function, 10 characters long.
const timePart = encodeBase32(timestamp, 10);
// Encode the random value using the encodeBase32 function, 16 characters long.
const randomPart = encodeBase32(randomValue, 16);
// Concatenate the time and random parts to form the ULID, and return it.
return timePart + randomPart;
}
/**
* Generates a monotonic MULID (Monotonic Universally Unique Lexicographically Sortable Identifier).
* @returns {Promise<string>} A promise that resolves to a MULID string.
* | {
"domain": "codereview.stackexchange",
"id": 45150,
"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",
"url": null
} |
javascript
* @returns {Promise<string>} A promise that resolves to a MULID string.
*
* - The function `randomMULID` asynchronously generates a "Monotonic"
* MULID string by combining a 48-bit timestamp and 80 bits of
* cryptographically secure random data. It ensures that ULIDs generated
* in the same millisecond are still unique by incrementing lastRandomValue.
* It returns a Promise that resolves to this MULID string.
*
*/
async function randomMULID() {
// Get the current timestamp as a BigInt.
const currentTimestamp = BigInt(Date.now());
// If the current timestamp equals the last used timestamp,
if (currentTimestamp === lastTimestamp) {
// Increment the last random value to ensure uniqueness.
lastRandomValue++;
} else {
// Update the last used timestamp.
lastTimestamp = currentTimestamp;
// Create a buffer to hold 10 bytes of random data.
const randomBuffer = new Uint8Array(10);
// Populate the buffer with cryptographically secure random values.
crypto.getRandomValues(randomBuffer);
// Reset the last used random value.
lastRandomValue = 0n;
// Loop through the random buffer.
for (const byte of randomBuffer) {
// Left-shift `lastRandomValue` by 8 bits and OR it with each byte, converted to BigInt.
lastRandomValue = (lastRandomValue << 8n) | BigInt(byte);
}
}
// Encode the last used timestamp using encodeBase32 function, 10 characters long.
const timePart = encodeBase32(lastTimestamp, 10);
// Encode the last used random value using encodeBase32 function, 16 characters long.
const randomPart = encodeBase32(lastRandomValue, 16);
// Concatenate the time and random parts to form the ULID, and return it.
return timePart + randomPart;
}
/**
* Performs a collision test for a given ID generator function.
*
* @async
* @param {number} _iterations - The number of iterations to perform.
* @param {() => Promise<string>} generator - The generator function for producing IDs. | {
"domain": "codereview.stackexchange",
"id": 45150,
"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",
"url": null
} |
javascript
* @param {() => Promise<string>} generator - The generator function for producing IDs.
* @returns {Promise<string>} A string containing various metrics and results of the test.
*/
async function collisionTest(_iterations, generator) {
const idSet = new Set();
let collisions = 0;
const start = Date.now();
for (let i = 0; i < _iterations; i++) {
const newId = await generator();
if (idSet.has(newId)) {
collisions++;
} else {
idSet.add(newId);
}
}
const end = Date.now();
// Calculate the duration of the test in milliseconds
const _durationMiliSecond = (end - start);
// Calculate the rate of ULID generation per millisecond
const _idPerMiliSecond = (_iterations / _durationMiliSecond);
// Calculate the duration of the test in seconds
const _durationSecond = ((end - start) / 1000);
// Calculate the rate of ULID generation per second
const _idPerSecond = (_iterations / _durationSecond);
// Format the duration in milliseconds to a string with 1 decimal point
const _durationMiliSecondFormatted = (_durationMiliSecond).toLocaleString('en-US', {
maximumFractionDigits: 1
});
// Format the duration in seconds to a string with 1 decimal point
const _durationSecondFormatted = (_durationSecond).toLocaleString('en-US', {
maximumFractionDigits: 1
});
// Format the rate per millisecond to a string with 0 decimal points
const _rateMiliSecondFormatted = (_idPerMiliSecond).toLocaleString('en-US', {
maximumFractionDigits: 0
});
// Format the rate per second to a string with 0 decimal points
const _ratePerSecondFormatted = (_idPerSecond).toLocaleString('en-US', {
maximumFractionDigits: 0
});
// Format the number of iterations to a string with 0 decimal points
const _iterationsFormatted = _iterations.toLocaleString('en-US', {
maximumFractionDigits: 0
});
// Define the byte length of a single ULID for use in size calculations
const ID_FIXED_BYTE_LENGTH = 26; | {
"domain": "codereview.stackexchange",
"id": 45150,
"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",
"url": null
} |
javascript
const ID_FIXED_BYTE_LENGTH = 26;
// Calculate the total byte length of all the ULIDs stored in the Set
const _setByteLength = idSet.size * ID_FIXED_BYTE_LENGTH;
// Format the total byte length to a string with 0 decimal points
const _setByteLengthFormatted = (_setByteLength).toLocaleString('en-US', {
maximumFractionDigits: 0
});
// Convert the total byte length to kilobytes
const _setKilobyteLength = _setByteLength / 1024;
// Format the total kilobyte length to a string with 0 decimal points
const _setKilobyteLengthFormatted = (_setKilobyteLength).toLocaleString('en-US', {
maximumFractionDigits: 0
});
// Convert the total kilobyte length to megabytes
const _setMegabyteLength = _setKilobyteLength / 1024;
// Format the total megabyte length to a string with 0 decimal points
const _setMegabyteLengthFormatted = (_setMegabyteLength).toLocaleString('en-US', {
maximumFractionDigits: 0
});
// Clear/Remove all ULIDs from this set (Free Memory)
idSet.clear();
// The return statement assembles the formatted test results.
return `
Test Results - ${generator.name}()
- Processor.....: Intel Xeon W-1390P @ 3.5GHz 32GB RAM
- Duration......: ${_durationSecondFormatted} sec @ ${_ratePerSecondFormatted}/s @ ${_rateMiliSecondFormatted}/ms
- Iterations....: ${_iterationsFormatted}
- Collisions....: ${collisions}
- Set Bytes.....: ${_setByteLengthFormatted} bytes
- Set Kilobytes.: ${_setKilobyteLengthFormatted} Kilobytes
- Set Megabytes.: ${_setMegabyteLengthFormatted} Megabytes | {
"domain": "codereview.stackexchange",
"id": 45150,
"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",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.