text
stringlengths
1
2.12k
source
dict
php Is overloading really needed here? Overloading is not really needed here. You can use a more standard feature of OOP: Extending. Using this in your class would give: <?php namespace StarExplorer\Database; use PDO; class Database extends PDO { function __construct($config = ['host' => 'localhost', 'user' => 'root', 'password' => '', 'dbname' => ''], $pdoOptions = []) { $dsn = "mysql:host={$config['host']};dbname={$config['dbname']}"; parent::__construct($dsn, $config['user'], $config['password'], $pdoOptions); } } This is something IDEs can cope with. It is functionally the same as your code but simpler. This code is therefore easier to understand and, if a bug occurs, it is usually easier to trace the problem. So, in this case I would advice against the use of overloading since it clearly has its disadvantages.
{ "domain": "codereview.stackexchange", "id": 44937, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php", "url": null }
python, python-3.x, time-limit-exceeded, primes Title: Goldbach's Conjecture Question: I am doing an exercise on finding the nearest pair of prime numbers p₁ and p₂ such that: p₁ ≤ p₂ p₁ + p₂ = n (for 4 ≤ n ≤ 10⁷) p₁ and p₂ are primes p₂ - p₁ is minimal I think it should work perfectly except that it got a TLE. Can someone point out how can I avoid it? import math import random def _try_composite(a, d, n, s): if pow(a, d, n) == 1: return False for i in range(s): if pow(a, 2 ** i * d, n) == n - 1: return False return True # n is definitely composite def is_prime(n, _precision_for_huge_n=16): if n in _known_primes: return True if n in (0, 1) or any((n % p) == 0 for p in _known_primes): return False d, s = n - 1, 0 while not d % 2: d, s = d >> 1, s + 1 # Returns exact according to http://primes.utm.edu/prove/prove2_3.html if n < 1373653: return not any(_try_composite(a, d, n, s) for a in (2, 3)) if n < 25326001: return not any(_try_composite(a, d, n, s) for a in (2, 3, 5)) _known_primes = [2, 3] _known_primes += [x for x in range(5, 1000, 2) if is_prime(x)] def main(): n = int(input()) if n > 4: for smaller in range(n // 2, -1, -1): if n - smaller >= smaller: if is_prime(n - smaller) and is_prime(smaller): print (smaller, n - smaller) flag = True break else: print ('2 2') main() Answer: My solution consists of a single change: Changed the is_prime function into a prime sieve (from this answer) + lookup
{ "domain": "codereview.stackexchange", "id": 44938, "lm_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, time-limit-exceeded, primes", "url": null }
python, python-3.x, time-limit-exceeded, primes Changed the is_prime function into a prime sieve (from this answer) + lookup My final code (Also handled odd numbers just for fun, definitely not because I misread the question): def main(): import itertools import math izip = itertools.zip_longest chain = itertools.chain.from_iterable compress = itertools.compress def rwh_primes2_python3(n): """ Input n>=6, Returns a list of primes, 2 <= p < n """ zero = bytearray([False]) size = n//3 + (n % 6 == 2) sieve = bytearray([True]) * size sieve[0] = False for i in range(int(n**0.5)//3+1): if sieve[i]: k=3*i+1|1 start = (k*k+4*k-2*k*(i&1))//3 sieve[(k*k)//3::2*k]=zero*((size - (k*k)//3 - 1) // (2 * k) + 1) sieve[ start ::2*k]=zero*((size - start - 1) // (2 * k) + 1) ans = [2,3] poss = chain(izip(*[range(i, n, 6) for i in (1,5)])) ans.extend(compress(poss, sieve)) return ans string2 = "Impossible" n = int(input()) sieve = [t for t in rwh_primes2_python3(n) if t <= math.floor((n // 2) / 2) * 2 + 1][::-1] another = [t for t in rwh_primes2_python3(n) if t >= math.floor((n // 2) / 2) * 2 + 1] if n > 5 and n % 2 == 0: for smaller in sieve: if n - smaller in another: print (smaller, n - smaller) break elif n % 2 == 1 and n != 5: if n - 2 in another or n-2 in sieve: print (2, n-2) else: print ('Impossible') elif n == 4: print ('2 2') else: print ('2 3') main()
{ "domain": "codereview.stackexchange", "id": 44938, "lm_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, time-limit-exceeded, primes", "url": null }
python, performance, python-3.x, algorithm Title: Python script that makes generalized Ulam spirals Question: This is a Python script I wrote to generate generalized Ulam spirals. I call the spirals generated by my code Ulamish spirals, they are one dimensional polylines that cross all two dimensional lattice points (points where both coordinates are integers), and they grow in a counterclockwise spiral manner. And my code can generate a single spiral, two spirals that don't cross each other, and four spirals: In a single spiral, the spiral starts at the origin and goes right first, then turns up, left and down, and repeat. After every two turns the length until the next turn increments by one. The spiral is composed entirely of segments and right angles, the segments are always parallel to one of the axes. I know there can be a one-to-one mapping between natural numbers and lattice points, so I numbered the lattices as such. In a pair of spirals, the spirals both start at the origin, and together they cross all lattice points, while each cross exactly half of the infinite lattice points (which is still the same amount of infinity, of course), and they never intersect with each other. The growth of the spirals is similar to the first one, one of the spirals is rotated, and every two turns the length grows by two. I know the number of integers is equal to the number of natural numbers, and I created the second variation to map all integers to all lattices, because in the first variation I can't do so.
{ "domain": "codereview.stackexchange", "id": 44939, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x, algorithm", "url": null }
python, performance, python-3.x, algorithm Four spirals are the maximum I can come up with that together cross all lattice points and don't intersect with each other. They are like the two spirals variation, one spiral has three rotated copies, and the spirals' length grows by two after every turn. I wanted to label the lattice points with unique numbers, so I chose real integers and integers with only imaginary parts (lattices on the imaginary axis), again, they have the same number of elements as the lattices. I used infinite iterators to generate the points, and I did all these without using a single if condition, my code is very efficient, though not the most efficient as shown here. But I have implemented two generalizations that weren't covered by the answer. Below is my code: import matplotlib.pyplot as plt from itertools import cycle, islice, repeat from PIL import Image from typing import Generator, List, Tuple def step_x(x: int, y: int, sign: int, length: int) -> Tuple[zip, int]: return zip(range(x + sign, (end := x + sign * length) + sign, sign), repeat(y)), end def step_y(x: int, y: int, sign: int, length: int) -> Tuple[zip, int]: return zip(repeat(x), range(y + sign, (end := y + sign * length) + sign, sign)), end def ulamish_spiral_gen() -> Generator: x = y = length = 0 yield 0, 0 sign = cycle([1, 1, -1, -1]) while True: length += 1 arm, x = step_x(x, y, next(sign), length) yield from arm arm, y = step_y(x, y, next(sign), length) yield from arm def gather(generator: Generator, n: int) -> List[Tuple[int]]: return list(islice(generator, n)) def ulamish_spiral(n: int) -> List[Tuple[int]]: return gather(ulamish_spiral_gen(), n) def ulamish_spiral_2_gen(x: int, y: int, sign: int) -> Generator: length = 1 yield 0, 0 yield x, y while True: arm, y = step_y(x, y, next(sign), length) yield from arm length += 2 arm, x = step_x(x, y, next(sign), length) yield from arm
{ "domain": "codereview.stackexchange", "id": 44939, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x, algorithm", "url": null }
python, performance, python-3.x, algorithm def ulamish_spiral_2(n: int) -> List[List[Tuple[int]]]: return gather(ulamish_spiral_2_gen(1, 0, cycle([1, -1, -1, 1])), n), gather( ulamish_spiral_2_gen(-1, 0, cycle([-1, 1, 1, -1])), n ) def get_steps(quad: List[int]) -> cycle: return cycle([[step_x, step_y][q] for q in quad]) def ulamish_spiral_4_gen(x: int, y: int, sign: cycle, order: List[int]) -> Generator: steps = get_steps(order) order = cycle(order) stack = [x, y] length = 2 yield 0, 0 yield x, y while True: arm, stack[next(order)] = next(steps)(*stack, next(sign), length) yield from arm length += 2 def ulamish_spiral_4(n: int) -> List[List[Tuple[int]]]: return [ gather(ulamish_spiral_4_gen(x, y, cycle(sign), order), n) for x, y, sign, order in ( (1, 0, [1, -1, -1, 1], [1, 0, 1, 0]), (-1, 0, [-1, 1, 1, -1], [1, 0, 1, 0]), (0, 1, [-1, -1, 1, 1], [0, 1, 0, 1]), (0, -1, [1, 1, -1, -1], [0, 1, 0, 1]), ) ] def get_figure(length: int, x: List[int], y: List[int]) -> Tuple[plt.Axes, plt.Figure]: length /= 100 fig, ax = plt.subplots(figsize=(length, length), dpi=100, facecolor="black") ax.set_axis_off() fig.subplots_adjust(0, 0, 1, 1, 0, 0) plt.axis("scaled") ax.axis([x[0], x[1], y[0], y[1]]) return ax, fig def get_data(n: int, level: int) -> List[List[Tuple[int]]]: return [ulamish_spiral, ulamish_spiral_2, ulamish_spiral_4][level](n) def process_level_1_data( data: List[Tuple[int]], length: int ) -> Tuple[Tuple[List[int]], plt.Axes, plt.Figure]: xs, ys = zip(*data) ax, fig = get_figure(length, [min(xs) - 1, max(xs) + 1], [min(ys) - 1, max(ys) + 1]) return [(xs, ys)], ax, fig
{ "domain": "codereview.stackexchange", "id": 44939, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x, algorithm", "url": null }
python, performance, python-3.x, algorithm def process_data(data: List[List[Tuple[int]]], length: int): xmin = ymin = 1e309 xmax = ymax = -1e309 coords = [] for spiral in data: xs, ys = zip(*spiral) xmin = min(min(xs), xmin) ymin = min(min(ys), ymin) xmax = max(max(xs), xmax) ymax = max(max(ys), ymax) coords.append((xs, ys)) ax, fig = get_figure(length, [xmin - 1, xmax + 1], [ymin - 1, ymax + 1]) return coords, ax, fig def get_label(n: int, vert: bool, sign: int) -> List[str]: return [f'{i}{"i"*vert}' for i in range(0, n * sign, sign)] def get_image(fig: plt.Figure) -> Image: fig.canvas.draw() image = Image.frombytes( "RGB", fig.canvas.get_width_height(), fig.canvas.tostring_rgb() ) plt.close(fig) return image def plot_spiral(n: int, level: int, length: int = 1080) -> Image: data = get_data(n, level) if not level: coords, ax, fig = process_level_1_data(data, length) else: coords, ax, fig = process_data(data, length) for (xs, ys), labels in zip( coords, ( get_label(n, 0, 1), get_label(n, 0, -1), get_label(n, 1, 1), get_label(n, 1, -1), ), ): ax.plot(xs, ys, "o-", color="cyan", lw=2) for x, y, label in zip(xs, ys, labels): ax.annotate(label, (x, y), color="white", fontsize=16) return get_image(fig) How can I make it more efficient?
{ "domain": "codereview.stackexchange", "id": 44939, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x, algorithm", "url": null }
python, performance, python-3.x, algorithm How can I make it more efficient? Update I have considered using mathematics myself, I tried to derive a quadratic equation for it myself, but of course the shape isn't a parabola. I thought maybe the lengths of the segments are quadratic, but the curve doesn't agree with the series of lengths fully (0, 1, 1, 2, 2, 3, 3, 4, 4...), I tried to use a software to find a curve of best fit with n terms, but no matter how many terms I throw at it, the curve is always off. Surprisingly you can't write a simple equation for the above series. Then I came across this answer on Mathematics Stack Exchange, and to find the coordinate of a given number you have four different equations, all of them quadratic, and the conditions for which equation to use are also quadratic, and contains a term that has to be calculated using square root and if conditions... And the computational cost for a single term is much more expensive than just a single increment. Sure, it would be faster if I were to find the coordinate for large n, I don't need to calculate all the previous coordinates, but to get all coordinates before n, the method simply is very inefficient. Answer: Speed As in the SO question/answer, you can trivially speed them up by combining the segments with chain.from_iterable instead of your generator. Your original: def ulamish_spiral_gen_Original() -> Generator: x = y = length = 0 yield 0, 0 sign = cycle([1, 1, -1, -1]) while True: length += 1 arm, x = step_x(x, y, next(sign), length) yield from arm arm, y = step_y(x, y, next(sign), length) yield from arm
{ "domain": "codereview.stackexchange", "id": 44939, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x, algorithm", "url": null }
python, performance, python-3.x, algorithm My way: def ulamish_spiral_gen_Kelly() -> Generator: def segments(): x = y = length = 0 yield (0, 0), sign = cycle([1, 1, -1, -1]) while True: length += 1 arm, x = step_x(x, y, next(sign), length) yield arm arm, y = step_y(x, y, next(sign), length) yield arm return chain.from_iterable(segments()) I also use a generator, but it only yields the segments. Your generator instead has every single coordinate passed through it. Benchmark results for ulamish_spiral(16384) (Attempt This Online!): 1.26 ± 0.00 ms ulamish_spiral_gen_Kelly 1.63 ± 0.00 ms ulamish_spiral_gen_Original Python: 3.11.4 (main, Jun 24 2023, 10:18:04) [GCC 13.1.1 20230429] Type hints Also, you wrote lots of type hints but apparently didn't get them checked. For example, ulamish_spiral_2_gen has parameter sign: int but you use a cycle iterator as argument instead of an int. And there are more issues. Do use Mypy or so to actually get your type hints checked and fix the issues.
{ "domain": "codereview.stackexchange", "id": 44939, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x, algorithm", "url": null }
c++, performance, algorithm, interview-questions, cache Title: Caches implementation in C++ Question: I had a test task for internship where the main part was in implementing fixed size caches with different displacement policies (LRU/LFU/FIFO). I did that task, but was refused afterwards. Now I am wondering how my solution might be improved? Requirements for an implementation are: Cache must be thread-safe Operations Put and Get have to be implemented (for storing and getting values by key respectively) LRU Cache implementation: #include <cstddef> #include <list> #include <mutex> #include <stdexcept> #include <unordered_map> #include <utility> #include <limits> template <typename Key, typename Value> class lru_cache { public: using value_type = typename std::pair<Key, Value>; using value_it = typename std::list<value_type>::iterator; using operation_guard = typename std::lock_guard<std::mutex>; lru_cache(size_t max_size) : max_cache_size{max_size} { if (max_size == 0) { max_cache_size = std::numeric_limits<size_t>::max(); } } void Put(const Key& key, const Value& value) { operation_guard og{safe_op}; auto it = cache_items_map.find(key); if (it == cache_items_map.end()) { if (cache_items_map.size() + 1 > max_cache_size) { // remove the last element from cache auto last = cache_items_list.crbegin(); cache_items_map.erase(last->first); cache_items_list.pop_back(); } cache_items_list.push_front(std::make_pair(key, value)); cache_items_map[key] = cache_items_list.begin(); } else { it->second->second = value; cache_items_list.splice(cache_items_list.cbegin(), cache_items_list, it->second); } } const Value& Get(const Key& key) const { operation_guard og{safe_op}; auto it = cache_items_map.find(key);
{ "domain": "codereview.stackexchange", "id": 44940, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, algorithm, interview-questions, cache", "url": null }
c++, performance, algorithm, interview-questions, cache if (it == cache_items_map.end()) { throw std::range_error("No such key in the cache"); } else { cache_items_list.splice(cache_items_list.begin(), cache_items_list, it->second); return it->second->second; } } bool Exists(const Key& key) const noexcept { operation_guard og{safe_op}; return cache_items_map.find(key) != cache_items_map.end(); } size_t Size() const noexcept { operation_guard og{safe_op}; return cache_items_map.size(); } private: mutable std::list<value_type> cache_items_list; std::unordered_map<Key, value_it> cache_items_map; size_t max_cache_size; mutable std::mutex safe_op; }; LFU Cache implementation: #include <algorithm> #include <list> #include <atomic> #include <mutex> #include <tuple> #include <unordered_map> template <typename Key, typename Value> class lfu_cache { public: using freq_type = unsigned; using value_type = typename std::tuple<Key, Value, freq_type>; using value_it = typename std::list<value_type>::iterator; using operation_guard = typename std::lock_guard<std::mutex>; enum VTFields { key_f = 0, value_f = 1, frequency_f = 2 }; lfu_cache(size_t max_size) : max_cache_size{max_size} { if (max_size == 0) { max_cache_size = std::numeric_limits<size_t>::max(); } } void Put(const Key& key, const Value& value) { constexpr unsigned INIT_FREQ = 1; operation_guard og{safe_op}; auto it = cache_items_map.find(key);
{ "domain": "codereview.stackexchange", "id": 44940, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, algorithm, interview-questions, cache", "url": null }
c++, performance, algorithm, interview-questions, cache if (it == cache_items_map.end()) { if (cache_items_map.size() + 1 > max_cache_size) { // look for the element with the smallest frequency value auto least_fr = std::min_element(cache_items_list.cbegin(), cache_items_list.cend(), [](const value_type& a, const value_type& b) { return std::get<frequency_f>(a) < std::get<frequency_f>(b); }); cache_items_map.erase(std::get<key_f>(*least_fr)); cache_items_list.erase(least_fr); } cache_items_list.emplace_front(std::make_tuple(key, value, INIT_FREQ)); cache_items_map[key] = cache_items_list.begin(); } else { // increase frequency of the existing value "key" and assigne new value std::get<value_f>(*it->second) = value; ++(std::get<frequency_f>(*it->second)); } } const Value& Get(const Key& key) const { operation_guard og{safe_op}; auto it = cache_items_map.find(key); if (it == cache_items_map.end()) { throw std::range_error("No such key in the cache"); } else { // increment the frequency of the "key"-element ++(std::get<frequency_f>(*it->second)); return std::get<value_f>(*it->second); } } bool Exists(const Key& key) const noexcept { operation_guard og{safe_op}; return cache_items_map.find(key) != cache_items_map.end(); } size_t Size() const noexcept { operation_guard og{safe_op}; return cache_items_map.size(); } private: mutable std::list<value_type> cache_items_list; std::unordered_map<Key, value_it> cache_items_map; size_t max_cache_size; mutable std::mutex safe_op; }; FIFO Cache implementation: #include <deque> #include <iterator> #include <mutex> #include <unordered_map> #include <utility>
{ "domain": "codereview.stackexchange", "id": 44940, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, algorithm, interview-questions, cache", "url": null }
c++, performance, algorithm, interview-questions, cache template <typename Key, typename Value> class fifo_cache { public: using value_type = typename std::pair<Key, Value>; using value_it = typename std::deque<value_type>::iterator; using operation_guard = typename std::lock_guard<std::mutex>; fifo_cache(size_t max_size) : max_cache_size{max_size} { if (max_size == 0) { max_cache_size = std::numeric_limits<size_t>::max(); } } void Put(const Key& key, const Value& value) { operation_guard og{safe_op}; auto it = cache_items_map.find(key); if (it == cache_items_map.end()) { if (cache_items_map.size() + 1 > max_cache_size) { // remove the last element from cache auto last = cache_items_deque.rbegin(); cache_items_map.erase(last->first); cache_items_deque.pop_back(); } cache_items_deque.push_front(std::make_pair(key, value)); cache_items_map[key] = cache_items_deque.begin(); } else { // just update value it->second->second = value; } } const Value& Get(const Key& key) const { operation_guard og{safe_op}; auto it = cache_items_map.find(key); if (it == cache_items_map.end()) { throw std::range_error("No such key in the cache"); } return it->second->second; } bool Exists(const Key& key) const noexcept { operation_guard og{safe_op}; return cache_items_map.find(key) != cache_items_map.end(); } size_t Size() const noexcept { operation_guard og{safe_op}; return cache_items_map.size(); } private: std::deque<value_type> cache_items_deque; std::unordered_map<Key, value_it> cache_items_map; size_t max_cache_size; mutable std::mutex safe_op; }; EDIT: For those who are interesed in the result of refactoring link to the repo
{ "domain": "codereview.stackexchange", "id": 44940, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, algorithm, interview-questions, cache", "url": null }
c++, performance, algorithm, interview-questions, cache EDIT: For those who are interesed in the result of refactoring link to the repo Answer: It looks like you put together a nice package given this was an internship application. You've used templates, stl, etc. and some of the newer features of C++, so in my opinion you showed a lot of promise. Perhaps there were other factors beyond your control that affected the candidate selection. That said, to address your specific questions, here are some tips that jumped out: 1. No concrete interface defined You were given a specification of a Get/Put interface, so it would have been nice to see an abstract base class implementation that your caches inherited from that enforced the implementation of the Get/Put methods. This provides two big advantages: Future developers who want to extend your design with new cache algorithms have a 'contract' in the form of a base class they must follow which provides greater cohesion with the rest of your system. Programmers wishing to use your new cache classes in their systems can maintain pointers to the base class which allows them to remain ignorant of the implementation details for each cache type. This encapsulation is very handy as your programs grow large. 2. Duplicate code If you look at your three cache implementations, you'll notice a lot of areas that are repeated. Apart from the Get/Put methods, your thread-safety operation guards and all of your member variables could easily be pushed to a common base class. This also provides two handy features:
{ "domain": "codereview.stackexchange", "id": 44940, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, algorithm, interview-questions, cache", "url": null }
c++, performance, algorithm, interview-questions, cache Removing the thread-safety mechanism from the 'cache-algorithm' (LRU/FIFO, LFU) decouples the two distinct problems into two separate domains. This allows the thread safety implementation to be overhauled/replaced as needed in the future without touching the core algorithm code. NOT doing this isn't a show-stopper, because your locking logic was quite small, but showing an injectable thread-locking mechanism might have scored some additional 'points' in the evaluation of your code. Once you start pushing the cache_items_map, max_cache_size, safe_op members into a common base class, you'll start to notice that your 'cache-algorithm' bits of code (i.e. the actual logic for the LRU/LFU/FIFO cache lookup and rollover) is actually independent of how the data is stored in the base class. You may find that you can refactor the algorithm logic out of the class entirely into its own separate class. This would be an example of the Strategy Design Pattern 3. Test code It's been awhile since I had to do a technical interview that involved active coding, but it's good practice to create test code for any new software you write to validate your logic. I've not actually tried to compile/run your sample code above, but are you sure it works? Sure enough to send it up on a Mars rover, put it into a medical device, monitor a nuclear facility, or perform high-frequency trades on the stock market? Providing test code provides (you guessed it) two big advantages:
{ "domain": "codereview.stackexchange", "id": 44940, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, algorithm, interview-questions, cache", "url": null }
c++, performance, algorithm, interview-questions, cache Dogfooding: Test code requires you to use your shiny new classes as an application developer rather than an software architect. One of the best ways to streamline your software is to spend some time using it. You'll find the areas that are awkward to type, hard to instantiate, hard to delete, etc. Verification: It's hard to evaluate an algorithm without running it through its paces. Does creating an instance of lfu_cache and trying to populate std::numeric_limits::max() number of ints work well? How about 256byte sized structs, or 32MB pictures? Does your rollover work properly? Does the LFU really purge the least frequently used item? etc. etc. Providing verification code details exactly how your logic performs, and provides the surety to both you (and your interviewers) that your classes will work as advertised. Good luck with your job search. If you're writing code like pre-employment, I think you'll do just fine.
{ "domain": "codereview.stackexchange", "id": 44940, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, algorithm, interview-questions, cache", "url": null }
python, performance, beginner, python-3.x Title: Python script that makes ngrams Question: This is a Python script that generates ngrams using a set of rules of what letters can follow a letter stored in a dictionary. The output is then preliminarily processed using another script, then it will be filtered further using an api of sorts by number of words containing the ngrams, the result will be used in pseudoword generation. This is the generation part: from string import ascii_lowercase import sys LETTERS = set(ascii_lowercase) VOWELS = set('aeiouy') CONSONANTS = LETTERS - VOWELS BASETAILS = { 'a': CONSONANTS, 'b': 'bjlr', 'c': 'chjklr', 'd': 'dgjw', 'e': CONSONANTS, 'f': 'fjlr', 'g': 'ghjlrw', 'h': '', 'i': CONSONANTS, 'j': '', 'k': 'hklrvw', 'l': 'l', 'm': 'cm', 'n': 'gn', 'o': CONSONANTS, 'p': 'fhlprst', 'q': '', 'r': 'hrw', 's': 'chjklmnpqstw', 't': 'hjrstw', 'u': CONSONANTS, 'v': 'lv', 'w': 'hr', 'x': 'h', 'y': 'sv', 'z': 'hlvw' } tails = dict() for i in ascii_lowercase: v = BASETAILS[i] if type(v) == set: v = ''.join(sorted(v)) tails.update({i: ''.join(sorted('aeiou' + v))}) def makechain(invar, target, depth=0): depth += 1 if type(invar) == str: invar = set(invar) chain = invar.copy() if depth == target: return sorted(chain) else: for i in invar: for j in tails[i[-1]]: chain.add(i + j) return makechain(chain, target, depth) if __name__ == '__main__': invar = sys.argv[1] target = int(sys.argv[2]) if invar in globals(): invar = eval(invar) print(*makechain(invar, target), sep='\n')
{ "domain": "codereview.stackexchange", "id": 44941, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, beginner, python-3.x", "url": null }
python, performance, beginner, python-3.x I want to ask about the makechain function, I used sets because somehow the results can contain duplicates if I used lists, though the result can be cast to set, I used a nested for loop and a recursive function to simulate a variable number of for loops. For example, makechain(LETTERS, 4) is equivalent to: chain = set() for a in LETTERS: chain.add(a) for a in LETTERS: for b in tails[a]: chain.add(a + b) for a in LETTERS: for b in tails[a]: for c in tails[b]: chain.add(a + b + c) for a in LETTERS: for b in tails[a]: for c in tails[b]: for d in tails[c]: chain.add(a + b + c + d) Obviously makechain(LETTERS, 4) is much better than the nested for loop approach, it is much more flexible. I want to know, is there anyway I can use a function from itertools instead of the nested for loop to generate the same results more efficiently? I am thinking about itertools.product and itertools.combinations but I just can't figure out how to do it. Any help will be appreciated. Answer: Type checking Don't do if type(var) == cls, instead do: if isinstance(var, cls): tails This can be built via a dictionary comprehension rather than iterating over ascii_lowercase and looking up against BASETAILS every time: tails = { i: ''.join(sorted(VOWELS + v)) for i, v in BASETAILS.items() } makechain vs loops Your n-depth loops are really just a cartesian product of LETTERS and tails, which can be accomplished, as you suspected, with itertools.product: from itertools import product def build_chain(letters, tails, depth, chain=None): chain = chain if chain is not None else set() if not depth - 1: return chain.union(letters) num_tails = [letters] for _ in range(depth - 1): chain.update( ''.join(c) for c in product(*num_tails) ) last = its[-1] num_tails.append(''.join(map(tails.get, last))) return chain
{ "domain": "codereview.stackexchange", "id": 44941, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, beginner, python-3.x", "url": null }
python, performance, beginner, python-3.x return chain Where this assumes that every entry in tails.values() is a string and letters is also a string
{ "domain": "codereview.stackexchange", "id": 44941, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, beginner, python-3.x", "url": null }
php Title: Implentation of Data Access Object Pattern Question: I'm tried to implement the Data Access Object Pattern. I have a base abstract class that is then extended for a specific table. I tried following some guides, but couldn't find a lot of info on this pattern. <?php namespace NicholasJohn16\Database; use \PDO; abstract class DataAccessObject { /** * @var \PDO */ protected $pdo; protected $_tablename; public function __construct($options = ['pdo' => null]) { $this->pdo = $options['pdo']; } protected function select($id = 0) { $sql = "SELECT * FROM " . $this->_tablename; if ($id) { $sql .= " WHERE id = :id "; } $statement = $this->pdo->prepare($sql); if ($id) { $statement->bindParam('id', $id, PDO::PARAM_INT); } $statement->execute(); return $id ? $statement->fetch() : $statement->fetchAll(); } protected function insert($data, $columns = null) { $sql = "INSERT IGNORE INTO " . $this->_tablename; $keys = $columns ? $columns : array_keys($data); $names = array_map(function ($key) { return ":" . $key; }, $keys); $sql .= " (" . implode(', ', $keys) . ") "; $sql .= " VALUE "; $sql .= " ( " . implode(', ', $names) . "); "; $statement = $this->pdo->prepare($sql); $datum = is_null($columns) ? $data : array_intersect_key($data, array_flip($columns)); $statement->execute($datum); return (int) $this->pdo->lastInsertId(); } protected function update($id, $data) { $sql = "UPDATE " . $this->_tablename; $sql .= " SET "; $updates = []; foreach ($data as $key => $value) { $updates[] = "{$key} = :{$key}"; } $sql .= implode(', ', $updates); $sql .= " WHERE id = :id";
{ "domain": "codereview.stackexchange", "id": 44942, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php", "url": null }
php $sql .= implode(', ', $updates); $sql .= " WHERE id = :id"; $statement = $this->pdo->prepare($sql); $statement->execute(array_merge($data, ['id' => $id])); $error = $statement->errorInfo(); return $this->select($id); } } <?php namespace NicholasJohn16\Database; class Prices extends DataAccessObject { protected $_tablename = 'prices'; function addPrice($data) { return $this->insert($data); } } Answer: Speaking specifically of DAO, as far as I can tell, it should provide an interchangeable interface. Which means, you shouldn't extend your implementation from the base class but rather use it as a dependency. This way, by simply passing another DAO instance as a constructor parameter, you'll be able to use multiple adapters that implement different data access methods. So your implementation should be changed like class PricesModel { protected $tablename = 'prices'; protected $dao; public function __construct(DAOInterface $dao) { { $this->dao = $dao; $this->dao->setTableName($this->tablename); } function addPrice($data) { return $this->dao->insert($data); } } While your current implementation looks more like a TableGateway pattern, though I myself is not too strong in pattern taxonomy. Looking at your code from this point of view, I can suggest several improvements, given I already busied myself with a similar task. First off, what is good here the idea itself. Strangely, but many PHP users stick to raw API calls, never thinking of reducing the boilerplate code the PDO object is a dependency there is no explicit error reporting to bloat the code, which is very good. All you need is to make sure that PDO's error reporting mode is set to exceptions and the rest should be left for the common error handling And now to some essential issues
{ "domain": "codereview.stackexchange", "id": 44942, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php", "url": null }
php And now to some essential issues Security is the main concern. In the update() method, you are adding input directly to SQL, which is a BIG NO. I see you tried to implement some white list in the insert() method, which is a good thing, but it's rather clumsy. Just go one step further and add another protected variable that contains the list of all columns in the table. And filter the $data variable's keys against it to throw an error is much better than silently discard the stray column name avoid ambiguous methods. It costs you absolutely nothing to add a method that selects a single row. So I would suggest to have several methods of different purpose (the number can vary): listBySql to get the rows based on arbitrary SQL (you'll definitely need it) getBySql same as above but to get just one row read - a CRUD method to read the record by its id INSERT IGNORE - I don't know where did you get that IGNORE from but you must definitely drop it out. the table and column names must be quoted. If you intend to use this class with different databases, a dedicated method must be added, which quotes each identifier before it's added to the query Some minor issues it would be a good idea to make the identifier column configurable we don't use underscores in the property names anymore the $error = $statement->errorInfo(); looks alien and should be removed the insert/update methods can be slightly optimized. It's no use to run several loops where only one is enough. not sure if (int) with lastInsertId is a good idea. Identifiers can be strings. no sure if return $this->select($id); is really needed. Most of time you don't need the updated record while in case you need, it can be selected explicitly
{ "domain": "codereview.stackexchange", "id": 44942, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php", "url": null }
c#, .net-core Title: Classes are using interface to send different messages to a console in C# Question: This is a follow-up of my thread in Class SettingView sending messages to a console in C#. Here is the whole project on GitHub. The starting point After attending online courses covering configuration and dependency injection this is my attempt to transfer the knowledge in something I have designed. One of the goals is, to organize the files in separate projects and folders. Another goal is, to understand the mechanism of the configuration using appsettings.json, appsettings.Production.json, launchSettings.json, secrets.json and command line args. However, the focus of this code review is described in the following sub-heading. Code Program.cs using BasicCodingConsole.Views.MainView; using BasicCodingConsole.Views.SettingView; using BasicCodingLibrary.Models; using BasicCodingLibrary.ViewModels; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Serilog; var builder = new ConfigurationBuilder(); builder.SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", false, true) .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ?? "Production"}.json", true) .AddEnvironmentVariables() .AddCommandLine(args);
{ "domain": "codereview.stackexchange", "id": 44943, "lm_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#, .net-core", "url": null }
c#, .net-core Log.Logger = new LoggerConfiguration() .ReadFrom.Configuration(builder.Build()) .Enrich.FromLogContext() .WriteTo.File("LogFiles/apploggings.txt") .CreateLogger(); var host = Host.CreateDefaultBuilder() .ConfigureServices((context, services) => { services.AddLogging(); services.Configure<UserInformation>(builder.Build().GetSection("UserInformation")); services.Configure<ApplicationInformation>(builder.Build().GetSection("ApplicationInformation")); services.AddTransient<IMainView, MainView>(); services.AddTransient<IMainViewModel, MainViewModel>(); services.AddTransient<IAppSettingProvider, AppSettingProvider>(); services.AddTransient<ISettingView, SettingView>(); services.AddTransient<ISettingViewModel, SettingViewModel>(); }) .UseSerilog() .Build(); var scope = host.Services.CreateScope(); var services = scope.ServiceProvider; try { Log.Logger.Information("***** Run Application *****"); Log.Logger.Information($"EnvironmentVariable: {Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT")}"); Log.Logger.Information($"CommandLineArgument: {builder.Build().GetValue<string>("CommandLineArgument")}"); services.GetService<IMainView>()! .Run(); } catch (Exception e) { Log.Logger.Error("Unexpected Exception!", e); Console.WriteLine("Unexpected Exception!"); Console.WriteLine(e); Console.WriteLine($"\n***** Press ENTER To Continue *****"); Console.ReadLine(); } finally { Log.Logger.Information("***** End Application *****"); }
{ "domain": "codereview.stackexchange", "id": 44943, "lm_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#, .net-core", "url": null }
c#, .net-core The two views named MainView and SettingView The main goal in this code review request, however, is the implementation of interfaces and classes. My focus is on IMessage Message. Here I tried to apply knowledge from courses on the SOLID principles. This pattern is new to me. I might be overkilling. And the chosen features may be very simple or sometimes just different in text output (check for view and app). However, it should be sufficient to understand these principles. Diagram Code IMainView.cs using BasicCodingConsole.ConsoleDisplays; using BasicCodingConsole.ConsoleMenus; using BasicCodingConsole.ConsoleMessages; namespace BasicCodingConsole.Views.MainView; public interface IMainView { IMenu Menu { get; } IMessage Message { get; } IDisplay Display { get; } void Run(); } MainView.cs using BasicCodingConsole.ConsoleDisplays; using BasicCodingConsole.ConsoleMenus; using BasicCodingConsole.ConsoleMessages; using BasicCodingConsole.Views.SettingView; using BasicCodingLibrary.ViewModels; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Serilog; using System.Diagnostics; namespace BasicCodingConsole.Views.MainView; public class MainView : ViewBase, IMainView { private readonly ILogger<MainView> _logger; private readonly IConfiguration _configuration; private readonly IMainViewModel _mainViewModel; private readonly IHost _hostProvider;
{ "domain": "codereview.stackexchange", "id": 44943, "lm_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#, .net-core", "url": null }
c#, .net-core /// <summary> /// This property is providing the menu's content written to the console. /// <para></para> /// The content is implemented in file <see cref="ContentMainMenu"/>. /// </summary> public IMenu Menu => new MainMenu(); /// <summary> /// This property is providing standard messages written to the console. /// <para></para> /// The content is implemented in the files <see cref="StartingApp"/>, /// <see cref="EndingApp"/> and <see cref="ContinueMessage"/> /// </summary> public IMessage Message => new MainMessage(); /// <summary> /// This property is providing standard method used to manipulate the console. /// <para></para> /// The method's behavior is implemented in the files <see cref="ClearingApp"/> and /// <see cref="ResizingApp"/>. /// </summary> public IDisplay Display => new MainDisplay(); public MainView(ILogger<MainView> logger, IConfiguration configuration, IMainViewModel mainViewModel, IHost hostProvider) { Debug.WriteLine($"Passing <Constructor> in <{nameof(MainView)}>."); _logger = logger; _configuration = configuration; _mainViewModel = mainViewModel; _hostProvider = hostProvider; } public void Run() { Debug.WriteLine($"Passing <{nameof(Run)}> in <{nameof(MainView)}>."); _logger.LogInformation("* Load: {view}", nameof(MainView)); Message.Start(); try { bool exitApp = false; do { CheckWindowSize(); WriteMenu(Menu.CaptionItems, Menu.MenuItems, Menu.StatusItems);
{ "domain": "codereview.stackexchange", "id": 44943, "lm_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#, .net-core", "url": null }
c#, .net-core switch (Console.ReadKey(true).Key) { case ConsoleKey.Escape: exitApp = true; break; case ConsoleKey.A: CheckWindowSize(); Action_A(); break; case ConsoleKey.B: CheckWindowSize(); Action_B(); break; case ConsoleKey.C: CheckWindowSize(); Action_C(); break; default: Console.Beep(); break; } } while (exitApp == false); } catch (Exception e) { Log.Logger.Error("Unexpected Exception!", e); } Message.End(); } /// <summary> /// This method starts the logic behind this menu item. /// </summary> private void Action_A() { Display.Clear(); WriteContent(); // to do Message.Continue(); } /// <summary> /// This method starts the logic behind this menu item. /// </summary> private void Action_B() { // basics are working; improving needed string processName = @"C:\Users\jenni\source\repos\MathSolutions\FibonacciApp\bin\Debug\net7.0\FibonacciApp.exe"; string processArgs = ""; //string processArgs = "--CommandLineArgument CommandLineStringIsPassedOnByBasicCodingConsole"; // get current console state ConsoleColor foregroundColor = Console.ForegroundColor; ConsoleColor backgroundColor = Console.BackgroundColor; ProcessStartInfo startinfo = new ProcessStartInfo(processName, processArgs); // Sync startinfo.UseShellExecute = false; Process p = Process.Start(startinfo)!; p.WaitForExit();
{ "domain": "codereview.stackexchange", "id": 44943, "lm_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#, .net-core", "url": null }
c#, .net-core // Async //startinfo.UseShellExecute = true; //var task = Process.Start(startinfo)!.WaitForExitAsync(); //if (task.IsCompleted) //{ // task.Dispose(); // closing the window is not stopping the task, so this is needed! //} // set saved console state Console.ForegroundColor = foregroundColor; Console.BackgroundColor = backgroundColor; } /// <summary> /// This method starts the logic behind this menu item. /// </summary> private void Action_C() { using var scope = _hostProvider.Services.CreateScope(); var services = scope.ServiceProvider; services.GetService<ISettingView>()!.Run(); } private void WriteContent() { _mainViewModel.Get(); // reloadOnChange? would it make this call unneccessary? Console.WriteLine($"TestProperty - Default : {_configuration.GetConnectionString("Default")}"); Console.WriteLine($"TestProperty - ClassName: {_mainViewModel.ClassName}"); Console.WriteLine($"\nInformation about user <{_mainViewModel.AppSetting.UserInformation.NickName}>"); Console.WriteLine($"\tName : " + $"{_mainViewModel.AppSetting.UserInformation.Person.FirstName} " + $"{_mainViewModel.AppSetting.UserInformation.Person.LastName}"); Console.WriteLine($"\tGender: " + $"{_mainViewModel.AppSetting.UserInformation.Person.Gender}"); Console.WriteLine($"\tID : " + $"{_mainViewModel.AppSetting.UserInformation.Person.Id,4:0000}"); Console.WriteLine($"\nInformation about app <{nameof(BasicCodingConsole)}>"); Console.WriteLine($"\tLanguage : {_mainViewModel.AppSetting.ApplicationInformation.Language}"); Console.WriteLine($"\tLastLogin: {_mainViewModel.AppSetting.ApplicationInformation.LastLogin}");
{ "domain": "codereview.stackexchange", "id": 44943, "lm_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#, .net-core", "url": null }
c#, .net-core Console.WriteLine($"\nInformation about command line arguments"); Console.WriteLine($"\tArguments: {_mainViewModel.AppSetting.CommandLineArgument}"); } } ISettingView.cs using BasicCodingConsole.ConsoleDisplays; using BasicCodingConsole.ConsoleMenus; using BasicCodingConsole.ConsoleMessages; namespace BasicCodingConsole.Views.SettingView; public interface ISettingView { IMenu Menu { get; } IMessage Message { get; } IDisplay Display { get; } void Run(); } SettingView.cs using BasicCodingConsole.ConsoleDisplays; using BasicCodingConsole.ConsoleMenus; using BasicCodingConsole.ConsoleMessages; using BasicCodingLibrary.ViewModels; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using System.Diagnostics; namespace BasicCodingConsole.Views.SettingView; public class SettingView : ViewBase, ISettingView { private readonly ILogger<SettingView> _logger; private readonly IConfiguration _configuration; private readonly ISettingViewModel _settingViewModel; /// <summary> /// This property is providing the menu's content written to the console. /// <para></para> /// The content is implemented in file <see cref="ContentSettingMenu"/>. /// </summary> public IMenu Menu => new SettingMenu(); /// <summary> /// This property is providing standard messages written to the console. /// <para></para> /// The content is implemented in the files <see cref="StartingView"/>, /// <see cref="EndingView"/> and <see cref="ContinueMessage"/> /// </summary> public IMessage Message => new SettingMessage(); /// <summary> /// This property is providing standard method used to manipulate the console. /// <para></para> /// The method's behavior is implemented in the files <see cref="ClearingView"/> and /// <see cref="ResizingView"/>. /// </summary> public IDisplay Display => new SettingDisplay();
{ "domain": "codereview.stackexchange", "id": 44943, "lm_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#, .net-core", "url": null }
c#, .net-core public SettingView(ILogger<SettingView> logger, IConfiguration configuration, ISettingViewModel settingViewModel) { Debug.WriteLine($"Passing <Constructor> in <{nameof(SettingView)}>."); _logger = logger; _configuration = configuration; _settingViewModel = settingViewModel; // to do } public void Run() { Debug.WriteLine($"Passing <{nameof(Run)}> in <{nameof(SettingView)}>."); _logger.LogInformation("* Load: {view}", nameof(SettingView)); Message.Start(); WriteMenu(Menu.CaptionItems, Menu.MenuItems, Menu.StatusItems); WriteContent(); // to do Message.End(); } private void WriteContent() { string message = "This is individual text by karwenzman!"; Console.WriteLine(message); Console.WriteLine($"\nConnectionString (key = Default): {_configuration.GetConnectionString("Default")}"); } } ViewBase.cs here the code to write a menu is implemented and available for all views inheriting it. namespace BasicCodingConsole.Views; public class ViewBase { /// <summary> /// This property stores the height's minimum value of the menu's frame. /// </summary> internal const int frameHeightMinimum = 20; /// <summary> /// This property stores the width's minimum value of the menu's frame. /// </summary> internal const int frameWidthMinimum = 80;
{ "domain": "codereview.stackexchange", "id": 44943, "lm_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#, .net-core", "url": null }
c#, .net-core /// <summary> /// This property stores the messages to be written into the caption section. /// </summary> public string[]? captionMessages; /// <summary> /// This property stores the messages to be written into the menu section. /// </summary> public string[]? menuMessages; /// <summary> /// This property stores the messages to be written into the status section. /// </summary> public string[]? statusMessages; /// <summary> /// This property stores the character used for writing the menu's frame. /// </summary> public char frameCharacter; /// <summary> /// This property stores the height of the menu's frame. /// </summary> public int frameHeight; /// <summary> /// This property stores the width of the menu's frame. /// </summary> public int frameWidth; /// <summary> /// This method is writing the complete menu. /// The menu's look is depending on the provided arguments. /// </summary> /// <param name="caption">The menu's header.</param> /// <param name="menu">The menu's body.</param> /// <param name="status">The menu's footer.</param> /// <param name="frame">Character used to draw the frame. This is an optional argument.</param> protected void WriteMenu(string[]? caption, string[]? menu, string[]? status, char frame = '*') { captionMessages = caption; menuMessages = menu; statusMessages = status; frameCharacter = frame; CheckWindowSize(); Console.Clear(); //Console.CursorVisible = false; GetFrameWidth(); if (caption != null | menu != null | status != null) { WriteHorizontalFrame(); } WriteCaptionMessages(); WriteMenuMessages(); WriteStatusMessage();
{ "domain": "codereview.stackexchange", "id": 44943, "lm_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#, .net-core", "url": null }
c#, .net-core // TODO: sometimes the width is one character to wide; // is this depending on debug, production or on the kind of distribution? //Console.WriteLine($"Height - Console:{Console.WindowHeight,3} | Frame:{frameHeight,3}"); //Console.WriteLine($"Width - Console:{Console.WindowWidth,3} | Frame:{frameWidth,3}"); } /// <summary> /// This method is checking, if the console needs to be resized. /// <para></para> /// Resize may be necessary, if the user has manually altered the console size below /// a defined value that is stored in <see cref="frameHeightMinimum"/> and /// <see cref="frameWidthMinimum"/>. /// </summary> public void CheckWindowSize() { //Console.Clear(); GetFrameWidth(); } /// <summary> /// This method is drawing the content of the caption section. /// <para> /// Depending on the property <see cref="captionMessages"/> the content is drawn on screen. /// If the property is <see href="Null"/>, there is no output on the screen. /// </para> /// </summary> private void WriteCaptionMessages() { if (captionMessages == null) { return; } for (int i = 0; i < captionMessages.Length; i++) { string message = Convert.ToString(frameCharacter).PadRight(2); message += captionMessages[i].PadRight(frameWidth - 4); message += Convert.ToString(frameCharacter).PadLeft(2); Console.WriteLine(message); } WriteHorizontalFrame(); }
{ "domain": "codereview.stackexchange", "id": 44943, "lm_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#, .net-core", "url": null }
c#, .net-core Console.WriteLine(message); } WriteHorizontalFrame(); } /// <summary> /// This method is drawing the content of the menu section. /// <para> /// Depending on the property <see cref="menuMessages"/> the content is drawn on screen. /// If the property is <see href="Null"/>, there is no output on the screen. /// </para> /// </summary> private void WriteMenuMessages() { if (menuMessages == null) { return; } for (int i = 0; i < menuMessages.Length; i++) { string message = Convert.ToString(frameCharacter).PadRight(2); message += menuMessages[i].PadRight(frameWidth - 4); message += Convert.ToString(frameCharacter).PadLeft(2); Console.WriteLine(message); } WriteHorizontalFrame(); } /// <summary> /// This method is drawing the content of the status section. /// <para> /// Depending on the property <see cref="statusMessages"/> the content is drawn on screen. /// If the property is <see href="Null"/>, there is no output on the screen. /// </para> /// </summary> private void WriteStatusMessage() { if (statusMessages == null) { return; } for (int i = 0; i < statusMessages.Length; i++) { string message = Convert.ToString(frameCharacter).PadRight(2); message += statusMessages[i].PadRight(frameWidth - 4); message += Convert.ToString(frameCharacter).PadLeft(2); Console.WriteLine(message); } WriteHorizontalFrame(); }
{ "domain": "codereview.stackexchange", "id": 44943, "lm_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#, .net-core", "url": null }
c#, .net-core Console.WriteLine(message); } WriteHorizontalFrame(); } /// <summary> /// This method is drawing a single horizontal frame. /// <para> /// Depending on the properties <see cref="frameCharacter"/> /// and <see cref="frameWidth"/> the appearence will be adapted. /// </para> /// </summary> private void WriteHorizontalFrame() { Console.WriteLine(frameCharacter.ToString().PadLeft(frameWidth, frameCharacter)); } /// <summary> /// This method is checking <see cref="Console.WindowHeight"/> and <see cref="Console.WindowWidth"/> /// and altering the menu's appearance accordingly. /// </summary> private void GetFrameWidth() { bool isResize = false; frameHeight = Console.WindowHeight; frameWidth = Console.WindowWidth; // when published the behaviour is different to debug mode if (frameHeight < frameHeightMinimum) { frameHeight = frameHeightMinimum; isResize = true; } if (frameWidth < frameWidthMinimum) { frameWidth = frameWidthMinimum; isResize = true; } try { if (isResize) { // how can I make this available on all OS? not only windows? Console.Clear(); Console.SetWindowSize(frameWidth, frameHeight); } } catch (Exception e) { Console.Clear(); Console.WriteLine(e.ToString()); Console.WriteLine("An exception was raised! Press ENTER to continue."); Console.ReadLine(); } } } Interface IMessage.cs and all depending classes / interfaces Since the design of IDisplay is identical to IMessage I am skipping to put the code here. In this code review I just want to focus on IMessage. Diagram
{ "domain": "codereview.stackexchange", "id": 44943, "lm_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#, .net-core", "url": null }
c#, .net-core Code The idea here is to have one class providing members for one view. These memeber's behavior can be altered by instancing specific classes. e.g. IEnding ending = new EndingApp(); and IEnding ending = new EndingView();. And if I have to update the content of a message, I just need to update e.g. the class EndingApp. This should be a implementation of the open-closed principle and the single-responsibility principle. IMessage namespace BasicCodingConsole.ConsoleMessages; public interface IMessage : IContinuing, IEnding, IStarting { } MainMessage.cs namespace BasicCodingConsole.ConsoleMessages; public class MainMessage : IMessage { public void Continue() { IContinuing continuing = new ContinueMessage(); continuing.Continue(); } public void End() { IEnding ending = new EndingApp(); ending.End(); } public void Start() { IStarting starting = new StartingApp(); starting.Start(); } } SettingMessage.cs namespace BasicCodingConsole.ConsoleMessages; public class SettingMessage : IMessage { public void Continue() { IContinuing continuing = new ContinueMessage(); continuing.Continue(); } public void End() { IEnding ending = new EndingView(); ending.End(); } public void Start() { IStarting starting = new StartingView(); starting.Start(); } } IContinuing.cs namespace BasicCodingConsole.ConsoleMessages; public interface IContinuing { void Continue(); } ContinueMessage.cs namespace BasicCodingConsole.ConsoleMessages; public class ContinueMessage : IContinuing { public void Continue() { Console.WriteLine($"\nPress ENTER to continue..."); Console.ReadLine(); } }
{ "domain": "codereview.stackexchange", "id": 44943, "lm_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#, .net-core", "url": null }
c#, .net-core IEnding.cs namespace BasicCodingConsole.ConsoleMessages; public interface IEnding { /// <summary> /// Writing a standard message to the console and awaiting user input. /// Then, clearing the console. /// </summary> void End(); } EndingApp.cs namespace BasicCodingConsole.ConsoleMessages; public class EndingApp : IEnding { public void End() { Console.WriteLine($"\nYou are going to leave the app. Press ENTER to end the app..."); Console.ReadLine(); Console.Clear(); } } EndingView.cs namespace BasicCodingConsole.ConsoleMessages; public class EndingView : IEnding { public void End() { Console.WriteLine($"\nYou are going to leave the view. Press ENTER to continue..."); Console.ReadLine(); Console.Clear(); } } IStarting.cs namespace BasicCodingConsole.ConsoleMessages; public interface IStarting { /// <summary> /// Writing a standard message to the console and awaiting user input. /// Then, clearing the console. /// </summary> void Start(); } StartingApp.cs namespace BasicCodingConsole.ConsoleMessages; public class StartingApp : IStarting { public void Start() { string message = $"You are going to start the app."; Console.WriteLine(message); Console.WriteLine("=".PadLeft(message.Length, '=')); Console.WriteLine($"\nPress ENTER to continue..."); Console.ReadLine(); Console.Clear(); } } StartingView.cs namespace BasicCodingConsole.ConsoleMessages; public class StartingView : IStarting { public void Start() { string message = $"You are going to start the view."; Console.WriteLine(message); Console.WriteLine("=".PadLeft(message.Length, '=')); Console.WriteLine($"\nPress ENTER to continue..."); Console.ReadLine(); Console.Clear(); } } I suppose this is a lot of content and I will stop here. Mentoring is much appreciated.
{ "domain": "codereview.stackexchange", "id": 44943, "lm_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#, .net-core", "url": null }
c#, .net-core I suppose this is a lot of content and I will stop here. Mentoring is much appreciated. Answer: ViewBase Here we see copy&pasta isn't always a good coding style although we all do it sometimes to save time, but one should just check again if what we copied and pasted is what we want. What I am talking about are the comments to the const's which are just lying /// <summary> /// This property stores the height's minimum value of the menu's frame. /// </summary> internal const int frameHeightMinimum = 20 It just isn't a property is it? Let us look a few lines further... /// <summary> /// This property stores the messages to be written into the caption section. /// </summary> public string[]? captionMessages; Well, this isn't a property either. This is a public field which can be accessed and filled without validation. In addition based on the Naming-Guidelines DO use PascalCasing for all public member, type, and namespace names consisting of multiple words. this field should be named CaptionMessages. Well this where just some basics but I think you have a bigger problem. Why do you have this fields at all? What value are they having for your application? I just don't see any value at least not in your current implementation. Let's take a look at the main-purpose of this class from the outside. If one creates an instance of this class there is only one method visible: CheckWindowSize() The first question is, why is CheckWindowSize() public at all? You are calling this method from classes which inherit ViewBase hence it would be sufficient to use the protected access modifier. The next question is, why is this method just calling GetFrameWidth()? If you or Sam the maintainer would need to go bug-hunting you would need to jump around in the code-base to check what this method is doing. Now, about GetFrameWidth(), this method is solely by it's name lying. It's documentation states This method is checking and and altering the menu's appearance accordingly.
{ "domain": "codereview.stackexchange", "id": 44943, "lm_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#, .net-core", "url": null }
c#, .net-core This method is checking and and altering the menu's appearance accordingly. It doesn't get the frame width, it is checking if the height of the current console is smaller than frameHeightMinimum and it is checking if the width of the current console is smaller than frameWidthMinimum. The first question coming to my mind is, what about maximum dimensions. I would extract the checking if resizing is needed into a separate method like private bool IsViewResizingNeeded() { bool isResizingNeeded = false; frameHeight = Console.WindowHeight; frameWidth = Console.WindowWidth; if (frameHeight < frameHeightMinimum) { frameHeight = frameHeightMinimum; isResizingNeeded = true; } if (frameWidth < frameWidthMinimum) { frameWidth = frameWidthMinimum; isResizingNeeded = true; } return isResizingNeeded; } And would name the calling ResizeViewIfNeeded() and would implement it like protected void ResizeViewIfNeeded() { if (IsViewResizingNeeded()) { Console.Clear(); Console.SetWindowSize(frameWidth, frameHeight); } } As you see I have omitted the try..catch because you would better validate the values frameWidth and frameHeight before calling Console.SetWindowSize(). A prevented exception is better than a caught exception. Now the CheckWindowSize() would be superfluous hence we should remove it. This would leave the class with no public method at all. Because you don't use this class as standalone but inherit it, why don't you make it abstract? WriteMenu() The name of the method is clear and we know from its name what it should do, but why are that many arguments passed to it when there is an IMenu interface which I would expect to have properties for CaptionItems, MenuItems and StatusItems. The methods definition could then just look like protected void WriteMenu(IMenu menu, char frame = '*') This if (caption != null | menu != null | status != null)
{ "domain": "codereview.stackexchange", "id": 44943, "lm_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#, .net-core", "url": null }
c#, .net-core This if (caption != null | menu != null | status != null) will check every condition although it would be enough if one condition would be true. Passing the frameCharacter to WriteHorizontalFrame(), WriteCaptionMessages, WriteMenuMessages() and WriteStatusMessage() would make the field frameCharacter superfluous . Passing the introduced menu argument to WriteCaptionMessages, WriteMenuMessages() and WriteStatusMessage() would make the fields captionMessages, menuMessages and statusMessages superfluous as well. Why does the method WriteStatusMessage() not use the plural form??? Concatenation of strings in a loop is not a good idea because it will create new strings all the time. It is better to use a StringBuilder object instead. But while we are refactoring these methods we see that each method does indeed the same thing, they are just named differently. I would suggest to have only one method named WriteMessages(). Implementing these changes will lead to private void WriteHorizontalFrame(char frameCharacter = '*') { Console.WriteLine("".PadLeft(frameWidth, frameCharacter)); } private const char framePadding = ' '; private void WriteMessages(string[] messages, char frameCharacter = '*') { if (messages == null) { return; } StringBuilder sb = new StringBuilder(); foreach (var message in messages) { sb.Append(frameCharacter) .Append(framePadding) .Append(message.PadRight(frameWidth - 4)) .Append(framePadding) .Append(frameCharacter) .AppendLine(); } Console.Write(sb.ToString()); WriteHorizontalFrame(); } and the WriteMenu() method would look like so protected void WriteMenu(IMenu menu, char frameCharacter = '*') { Console.Clear(); ResizeViewIfNeeded();
{ "domain": "codereview.stackexchange", "id": 44943, "lm_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#, .net-core", "url": null }
c#, .net-core if (menu.CaptionItems != null || menu.MenuItems != null || menu.StatusItems != null) { WriteHorizontalFrame(frameCharacter); } WriteMessages(menu.CaptionItems, frameCharacter); WriteMessages(menu.MenuItems, frameCharacter); WriteMessages(menu.StatusItems, frameCharacter); }
{ "domain": "codereview.stackexchange", "id": 44943, "lm_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#, .net-core", "url": null }
javascript, beginner Title: JavaScript front-end 'Library App' implementation from the Odin project Question: I am currently working through the Javascript portion of the Odin Project curriculum and have completed the library app project. As far as I can see everything is working as expected and I have completed all the object requirements (users can add books to their library, delete books, and update the 'read' status of each book). I am now looking for some help/feedback on my code so that I can improve for future projects. Specifically, I am looking for some advice on how I can implement the SOLID principles and OOP within the project, but any general feedback/do's and don'ts would be greatly appreciated as well. Here is my Javascript code: let bookArray = []; class Book { constructor(title, author, numPages, status) { this.title = title; this.author = author; this.numPages = numPages; this.status = status; } } //adds each book that the user inputs into 'database' function addToLibrary(book) { bookArray.push(book); }
{ "domain": "codereview.stackexchange", "id": 44944, "lm_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, beginner", "url": null }
javascript, beginner //add new DOM element each time book is added function makeNewCard(array) { let card = document.createElement("div"); let title = document.createElement("p"); let author = document.createElement("p"); let numPages = document.createElement("p"); let statusBtn = document.createElement("button"); let removeBookBtn = document.createElement("button"); title.setAttribute("class", "title"); author.setAttribute("class", "author"); numPages.setAttribute("class", "numPages"); statusBtn.setAttribute("class", "status"); card.setAttribute("class", "book-card"); removeBookBtn.setAttribute("class", "remove-book"); //displays book array contents on the page for (let i = 0; i < array.length; i++) { title.textContent = array[i]["title"]; author.textContent = array[i]["author"]; numPages.textContent = array[i]["numPages"]; statusBtn.textContent = array[i]["status"]; removeBookBtn.textContent = "Delete"; card.dataset.index = i; } statusBtn.textContent === "Read" ? (statusBtn.style.backgroundColor = "var(--read-book)") : (statusBtn.style.backgroundColor = "var(--unread-book)"); statusBtn.addEventListener("click", (e) => //function is called with event target updateStatus(e.target) ); removeBookBtn.addEventListener("click", (e) => deleteBook(e.target)); card.append(title, author, numPages, statusBtn, removeBookBtn); document.querySelector(".library-contents").appendChild(card); }
{ "domain": "codereview.stackexchange", "id": 44944, "lm_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, beginner", "url": null }
javascript, beginner const form = document.querySelector("form"); const inputTitle = document.querySelector("#book-title"); const inputAuthor = document.querySelector("#book-author"); const inputNumPages = document.querySelector("input[type=number]"); const checkBox = document.querySelector("#book-status"); const addNewBtn = document.querySelector(".add-new"); const overlay = document.querySelector(".overlay"); //new book is added when form is submitted form.addEventListener("submit", function (e) { e.preventDefault(); const book = new Book( inputTitle.value, inputAuthor.value, inputNumPages.value, checkBox.checked === true ? "Read" : "Unread" ); addToLibrary(book); console.log(bookArray); makeNewCard(bookArray); form.classList.toggle("form-visible"); overlay.classList.toggle("overlay-visible"); return book; }); function updateStatus(button) { const arrayPosition = parseInt(button.parentElement.dataset.index); const selectedBook = bookArray[arrayPosition]; console.log(selectedBook); if (selectedBook.status === "Read") { selectedBook.status = "Unread"; button.style.backgroundColor = "var(--unread-book)"; } else { selectedBook.status = "Read"; button.style.backgroundColor = "var(--read-book)"; } console.log(selectedBook); button.textContent = selectedBook.status; } function deleteBook(deleteButtton) { const arrayPosition = parseInt(deleteButtton.parentElement.dataset.index); bookArray.splice(arrayPosition, 1); console.log(bookArray); const selectedCard = deleteButtton.parentElement; selectedCard.parentElement.removeChild(selectedCard); //make array from remaining cards on screen and reassign a data value according to their position on screen let cards = document.querySelectorAll(".book-card"); console.log(cards);
{ "domain": "codereview.stackexchange", "id": 44944, "lm_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, beginner", "url": null }
javascript, beginner for (let i = 0; i < cards.length; i++) { console.log(i); cards[i].dataset.index = i; console.log(cards[i]); } } addNewBtn.addEventListener("click", function () { form.classList.toggle("form-visible"); overlay.classList.toggle("overlay-visible"); }); HTML File Link to repository Live Project This is my first time asking for a code review so I do apologize if I have missed out any important information! Answer: Good job! This code is very clear, in large part thanks to consistent naming. function addToLibrary(book) { bookArray.push(book); } You describe bookArray as a "database", which is fine. What strikes me here is that the order of calls to this function is very important. So it feels like bookArray is doing more than maintaining a "library" or "database" -- it feels like it is actually responsible for maintaining a display order, visible to the user. So we're conflating details of the Model with details of the View. Consider taking the opportunity to alphabetize books by author or title here. The array list you chose is a perfectly good representation, but consider using an object mapping instead. (This critique is all about examining current requirements and anticipating likely new ones, rather than about "change this code to improve its correctness.") function makeNewCard(array) {
{ "domain": "codereview.stackexchange", "id": 44944, "lm_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, beginner", "url": null }
javascript, beginner function makeNewCard(array) { This is nice enough, but perhaps a little tediously long, enough that it might be worth the occasional extract method. Or imagine you had an object which maps each of {card, title, author, numPages} to element & class attributes like {"p", "title"}. Then the three three repetitive stanzas of assignments might be a natural fit for some looping. As an application is deployed and matures, I would expect that user feature requests would only cause the set of attributes to grow, e.g. {publisher, copyrightYear, coverArt}. statusBtn.textContent === "Read" ? (statusBtn.style.backgroundColor = "var(--read-book)") : (statusBtn.style.backgroundColor = "var(--unread-book)"); Here we are evaluating an expression strictly for side effects. I'm sure there are some folks who embrace that, and might even write it into their project's style guide, in which case more power to you. When I read it I find it slightly tricky, and would rather see an explicit if telling me that we're executing verbs rather than constructing some noun, some result expression value which it turns out gets discarded. const form = ... const inputNumPages = ... I again wonder if having a mapping object handy would let us move at least some of these repetitive assignments into a loop. No biggie. addToLibrary(book); console.log(bookArray); makeNewCard(bookArray);
{ "domain": "codereview.stackexchange", "id": 44944, "lm_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, beginner", "url": null }
javascript, beginner Kudos, this is lovely, keep it up! Having done the hard work of writing low-level routines which connect business domain concepts to JS primitives, now you can very concisely give this high-level description of what you want done. The logging is perhaps a bit chatty? It makes perfect sense during initial authoring and debugging. But just before a review / PR submission is the perfect time to go back through them. Consider deleting obsolete debugs, or using a logging severity level that makes it easy to crank up verbosity a month from now whilst debugging some new issue. In a few places, further down in the code, you log just an integer with no explanation of what it means or which routine logged it. If you do choose to keep those, consider logging some explanatory text along with it. function deleteBook(deleteButtton) { It is perhaps slightly painful or inconvenient to delete a book? Consider using a set or mapping object as your "database", and decide if the resulting simplification of this function helps to motivate such a change. Or just keep it in mind for next time, when you're choosing between This or That datastructure for a new project. for (let i = 0; i < cards.length; i++) { ... cards[i].dataset.index = i; Two minor concerns: Renumbering after deletion is an internal complexity that stems from your datastructure choice, rather than coming from the business domain's requirements. Currently this is a class invariant, a promise which holds true during the app's lifetime. Consider computing this as just a temp variable before the splice() deletion. And having done that, do we need such a renumbering operation at all? This application appears to achieve its design goals. I would be willing to delegate or accept maintenance tasks on this codebase.
{ "domain": "codereview.stackexchange", "id": 44944, "lm_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, beginner", "url": null }
c++, game, design-patterns, entity-component-system, glfw Title: Mouse and keyboard event system Question: I wrote a mouse and keyboard event system in C++, using the GLFW library to get mouse and keyboard states. I've been working on a 3D game engine of my own for a long time (about 9 months) and wanted to have a way to handle input independent of having to intertwine GLFW calls randomly in my code (thought this would be good design and would modularize input). This also uses an entity-component system designed by Austin Morlan and I like it a lot, it makes thinking about objects much easier, kind of like building blocks. I'm working on collision detection/response soon, but since I had the time I wondered how I did with this event system, since its mostly work of my own. I'm not sure what design pattern this would be called (maybe inversion of control?), as I'm still an amateur in software engineering, but it uses callback functions and "managers" to subscribe to certain keys and the mouse in general, something I've seen vaguely while modding games. Things I've noticed myself, but could use some clarification/justification/agreement: KeySubscription feels oddly redundant. Can this just be removed? The MouseState struct feels as though it is containing too much information and violates some principle of object oriented design. Maybe I could pass around 2 MouseState objects instead to show the currentMouseState and the previousMouseState? It would be annoying to pass around two states all the time, so maybe I could convert it to a Mouse (containing generic mouse data) and then contain a MouseState with two Mouse objects? Theres some globals around that I didn't want to pass around in every method that needs them, like mCamera (what if I want multiple cameras in the world, like with portals?), or gameWindow (multiple windows in the future?). How can I avoid this? Do I need a gigantic Engine class that keeps track of everything?
{ "domain": "codereview.stackexchange", "id": 44945, "lm_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, design-patterns, entity-component-system, glfw", "url": null }
c++, game, design-patterns, entity-component-system, glfw keyboard_manager.hpp #include <glad/glad.h> #include <GLFW/glfw3.h> #include <memory> #include <functional> #include "key_subscription.hpp" namespace Input { // Function pointer to a keyboard callback function. using key_callback_fn = std::function<void(const GLFWKey key, const bool state)>; class KeyboardManager { public: KeyboardManager(); size_t subscribe(key_callback_fn Function, std::array<GLFWKey, MAX_KEYS> Keys, size_t keysLen); void unsubscribe(size_t indexToRemove); void callbackAll(GLFWwindow* handle); private: // Array of key callbacks. std::array<key_callback_fn, MAX_KEY_CALLBACKS> keyCallbacks{}; // Map of callback functions to their key subscriptions. std::array<std::unique_ptr<KeySubscription>, MAX_KEY_CALLBACKS> callbackToSubscription{}; size_t usedCallbacks{}; }; } keyboard_manager.cpp #include "keyboard_manager.hpp" using namespace Input; KeyboardManager::KeyboardManager() : keyCallbacks(), usedCallbacks(0) { } size_t KeyboardManager::subscribe(key_callback_fn Function, std::array<GLFWKey, MAX_KEYS> Keys, size_t keysLen) { size_t newIndex = usedCallbacks; keyCallbacks[newIndex] = Function; callbackToSubscription[newIndex] = std::make_unique<KeySubscription>(Keys, keysLen); ++usedCallbacks; return newIndex; } void KeyboardManager::unsubscribe(size_t indexToRemove) { size_t lastIndex = usedCallbacks; keyCallbacks[indexToRemove] = std::move(keyCallbacks[lastIndex]); callbackToSubscription[indexToRemove] = std::move(callbackToSubscription[lastIndex]); callbackToSubscription[lastIndex].release(); --usedCallbacks; }
{ "domain": "codereview.stackexchange", "id": 44945, "lm_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, design-patterns, entity-component-system, glfw", "url": null }
c++, game, design-patterns, entity-component-system, glfw void KeyboardManager::callbackAll(GLFWwindow* handle) { for (size_t i = 0; i < usedCallbacks; i++) { const auto& Function = keyCallbacks[i]; auto& sub = *callbackToSubscription[i].get(); const auto& list = sub.getKeyList(); for (size_t j = 0; j < sub.size(); j++) { const auto& key = list[j]; const auto& state = glfwGetKey(handle, key); sub.setKeyState(key, state); } for (const auto& key_state : sub.getKeyStates()) { Function(key_state.first, key_state.second); } } } key_subscription.hpp #pragma once #include "types.hpp" #include <GLFW/glfw3.h> #include <array> #include <algorithm> #include <unordered_map> #include <format> #include <assert.h> namespace Input { // Defines the maximum number of keys a KeySubscription can subscribe to. constexpr size_t MAX_KEYS = 8; // Defines the maximum number of callback functions that can be stored in the KeyboardManager. constexpr size_t MAX_KEY_CALLBACKS = 64; // Enumeration of the GLFW keys used in this program. enum GLFWKey { Space = GLFW_KEY_SPACE, A = GLFW_KEY_A, D = GLFW_KEY_D, F = GLFW_KEY_F, Q = GLFW_KEY_Q, S = GLFW_KEY_S, W = GLFW_KEY_W, Escape = GLFW_KEY_ESCAPE }; class KeySubscription { public: KeySubscription(); KeySubscription(std::array<GLFWKey, MAX_KEYS> _keysList, size_t _keySize) { keySize = _keySize; assert(keySize <= MAX_KEYS && std::format("Maximum number of keys is {}, provided {}", MAX_KEYS, keySize).c_str()); std::copy(std::begin(_keysList), std::end(_keysList), std::begin(keysList)); for (size_t i = 0; i < keySize; i++) { keyStates.insert({ keysList[i], GLFW_RELEASE }); } }
{ "domain": "codereview.stackexchange", "id": 44945, "lm_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, design-patterns, entity-component-system, glfw", "url": null }
c++, game, design-patterns, entity-component-system, glfw // Get the keys list. const std::array<GLFWKey, MAX_KEYS>& getKeyList() const { return keysList; } // Get the key states. std::unordered_map<GLFWKey, bool> getKeyStates() const { return keyStates; } // Sets the key state. void setKeyState(GLFWKey key, bool state); // Get the number of keys used. size_t size() const { return keySize; } private: // The list of keys subscribed. std::array<GLFWKey, MAX_KEYS> keysList{}; // The key states. std::unordered_map<GLFWKey, bool> keyStates{}; // The number of keys subscribed. size_t keySize; }; } key_subscription.cpp #include "key_subscription.hpp" using namespace Input; KeySubscription::KeySubscription() : keysList(), keyStates() { keySize = 0; } void KeySubscription::setKeyState(GLFWKey key, bool state) { keyStates.at(key) = state; } mouse_manager.hpp #pragma once #include <glad/glad.h> #include <GLFW/glfw3.h> #include <functional> #include <memory> #include <array> namespace Input { // The mouse state. using MouseState = struct { double mouseXo; double mouseYo; double lastMouseX; double lastMouseY; double deltaX; double deltaY; }; // Function pointer to a mouse callback function. using mouse_callback_fn = std::function<void(const MouseState& mouse)>; // Defines the maximum number of callback functions that can be stored in the MouseManager. constexpr size_t MAX_MOUSE_CALLBACKS = 64; class MouseManager { public: MouseManager(); // Subscribe to the mouse manager with a function. void subscribe(mouse_callback_fn Function); void unsubscribe(mouse_callback_fn Function);
{ "domain": "codereview.stackexchange", "id": 44945, "lm_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, design-patterns, entity-component-system, glfw", "url": null }
c++, game, design-patterns, entity-component-system, glfw void unsubscribe(mouse_callback_fn Function); // Updates the mouse state. Called automatically by glfw. void updateMouseState(double xpos, double ypos); private: // Array of mouse callback functions. std::array<std::shared_ptr<mouse_callback_fn>, MAX_MOUSE_CALLBACKS> mouseCallbacks{}; size_t usedCallbacks{}; // Map of mouse callback functions to their indices. std::unordered_map<std::shared_ptr<mouse_callback_fn>, size_t> mouseCallbackToIndex{}; // The internal mouse state. MouseState mouse{}; void callbackAll(); }; } mouse_manager.cpp #include "mouse_manager.hpp" using namespace Input; MouseManager::MouseManager() : mouseCallbacks(), mouseCallbackToIndex(), usedCallbacks(0) { mouse = MouseState {}; } void MouseManager::subscribe(mouse_callback_fn Function) { auto sharedFunction = std::make_shared<mouse_callback_fn>(Function); size_t newIndex = usedCallbacks; mouseCallbacks[newIndex] = sharedFunction; mouseCallbackToIndex.insert({ sharedFunction, newIndex }); ++usedCallbacks; } void MouseManager::unsubscribe(mouse_callback_fn Function) { auto sharedFunction = std::make_shared<mouse_callback_fn>(Function); size_t indexToRemove = mouseCallbackToIndex[sharedFunction]; size_t lastIndex = usedCallbacks; mouseCallbacks[indexToRemove] = mouseCallbacks[lastIndex]; mouseCallbacks[lastIndex] = 0; mouseCallbackToIndex.erase(sharedFunction); --usedCallbacks; } void MouseManager::updateMouseState(double xpos, double ypos) { if (!mouse.lastMouseX || !mouse.lastMouseY) { mouse.lastMouseX = xpos; mouse.lastMouseY = ypos; } double xo = xpos - mouse.lastMouseX; double yo = mouse.lastMouseY - ypos; mouse.lastMouseX = xpos; mouse.lastMouseY = ypos; mouse.deltaX = xo; mouse.deltaY = yo; callbackAll(); }
{ "domain": "codereview.stackexchange", "id": 44945, "lm_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, design-patterns, entity-component-system, glfw", "url": null }
c++, game, design-patterns, entity-component-system, glfw callbackAll(); } void MouseManager::callbackAll() { for (size_t i = 0; i < usedCallbacks; i++) { const auto& Function = mouseCallbacks[i]; (*Function.get())(mouse); } } window.hpp #pragma once #include <glad/glad.h> #include <GLFW/glfw3.h> #include <cstdint> #include <string> #include "input_manager.hpp" #define BASIC_TITLE "Physics and rendering demo {}" class Window { private: GLFWwindow* handle; const uint16_t width; const uint16_t height; std::string title; Input::KeyboardManager keyboardManager; Input::MouseManager mouseManager; public: Window(const uint16_t _width, const uint16_t _height, std::string _title); ~Window(); GLFWwindow* getHandle(); void updateTitle(std::string title); uint16_t getWidth(); uint16_t getHeight(); void updateKeyboard(); Input::KeyboardManager& getKeyboardManager(); Input::MouseManager& getMouseManager(); }; window.cpp Window::Window(const uint16_t _width, const uint16_t _height, std::string _title) : width(_width), height(_height), title(_title) { // Unrelated window stuff... // Prepare our input managers. mouseManager = Input::MouseManager(); keyboardManager = Input::KeyboardManager(); glfwSetWindowUserPointer(handle, this); auto cursorPosCallback = [](GLFWwindow* handle, double xpos, double ypos) { static_cast<Window*>(glfwGetWindowUserPointer(handle))->mouseManager.updateMouseState(xpos, ypos); }; glfwSetCursorPosCallback(handle, cursorPosCallback); // We callback the keyboard manager's callbacks later with our other stuff. } // Unrelated window stuff... Input::KeyboardManager& Window::getKeyboardManager() { return keyboardManager; } Input::MouseManager& Window::getMouseManager() { return mouseManager; } void Window::updateKeyboard() { keyboardManager.callbackAll(handle); } main.cpp (consumer perspective) // Global scoped window std::unique_ptr<Window> gameWindow;
{ "domain": "codereview.stackexchange", "id": 44945, "lm_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, design-patterns, entity-component-system, glfw", "url": null }
c++, game, design-patterns, entity-component-system, glfw main.cpp (consumer perspective) // Global scoped window std::unique_ptr<Window> gameWindow; void main_input(Input::GLFWKey key, bool state) { using namespace Input; if (key == GLFWKey::Escape && state == GLFW_PRESS) { glfwSetWindowShouldClose(gameWindow->getHandle(), true); } } void start() { // Other stuff... gameWindow->getKeyboardManager().subscribe(&main_input, {Input::GLFWKey::Escape}, 1); } // ... render_system.hpp // Externs extern Coordinator gCoordinator; extern std::unique_ptr<Window> gameWindow; using namespace Systems; // Global camera for now Entity mCamera; void camera_movement(const Input::GLFWKey key, const bool state) { using namespace Input; auto& transform = gCoordinator.getComponent<Components::Transform>(mCamera); const auto& orientation = gCoordinator.getComponent<Components::Orientation>(mCamera); auto& camera = gCoordinator.getComponent<Components::Camera>(mCamera); static float speed = 0.1f; if (key == GLFWKey::W && state == GLFW_PRESS) { transform.Position += speed * orientation.Front; } else if (key == GLFWKey::A && state == GLFW_PRESS) { transform.Position -= speed * orientation.Right; } else if (key == GLFWKey::S && state == GLFW_PRESS) { transform.Position -= speed * orientation.Front; } else if (key == GLFWKey::D && state == GLFW_PRESS) { transform.Position += speed * orientation.Right; } } // FPS camera void camera_look(const Input::MouseState& mouse) { static double sensitivity = 0.05f; auto& orientation = gCoordinator.getComponent<Components::Orientation>(mCamera); auto& camera = gCoordinator.getComponent<Components::Camera>(mCamera); double yawOff = mouse.deltaX * sensitivity; double pitchOff = mouse.deltaY * sensitivity; camera.Yaw += yawOff; camera.Pitch += pitchOff; if (camera.Pitch > 89.0f) camera.Pitch = 89.0f; if (camera.Pitch < -89.0f) camera.Pitch = -89.0f;
{ "domain": "codereview.stackexchange", "id": 44945, "lm_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, design-patterns, entity-component-system, glfw", "url": null }
c++, game, design-patterns, entity-component-system, glfw camera.update(orientation); } void RenderSystem::init() { mCamera = gCoordinator.createEntity(); gCoordinator.addComponent(mCamera, Components::Transform{ .Position = glm::vec3(0.0f), .Rotation = glm::vec3(0.0f), .Scale = glm::vec3(0.0f) }); gCoordinator.addComponent(mCamera, Components::Orientation{ .Front = glm::vec3(0.0f, 0.0f, -1.0f), .Up = glm::vec3(0.0f, 1.0f, 0.0f), .Right = glm::vec3(1.0f, 0.0f, 0.0f) }); gCoordinator.addComponent(mCamera, Components::Camera{ .Projection = Components::Camera::createProjection(45.0f, 0.1f, 1000.0f, 1920.0f, 1080.0f), .Pitch = 0.0f, .Yaw = -90.0f }); gameWindow->getKeyboardManager().subscribe(&camera_movement, {Input::GLFWKey::W, Input::GLFWKey::A, Input::GLFWKey::S, Input::GLFWKey::D }, 4); gameWindow->getMouseManager().subscribe(&camera_look); // Shader stuff... } Answer: Unsafe use of using namespace Don't rely on using namespace Input to define class member functions of classes that were declared inside a namespace Input scope. Instead, use a namespace Input scope again: #include "keyboard_manager.hpp" namespace Input { KeyboardManager::KeyBoardManager(): keyCallbacks(), usedCallbacks(0) { } … }
{ "domain": "codereview.stackexchange", "id": 44945, "lm_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, design-patterns, entity-component-system, glfw", "url": null }
c++, game, design-patterns, entity-component-system, glfw namespace Input { KeyboardManager::KeyBoardManager(): keyCallbacks(), usedCallbacks(0) { } … } This makes it explicit that you are defining that function inside namespace Input. If you merely use using namespace Input, then you are relying on name resolution finding the right namespace, which might not do the right thing if you have multiple namespaces that have a class KeyboardManager defined in them. Even if that's unlikely, it's better to avoid the possibility. Unnecessary constructors You didn't need to declare an explicit constructor for KeyboardManager; you already used default member initialization, so keyCallbacks and usedCallbacks get initialized even if you don't add a constructor. Just remove it. The same goes for MouseManager. For KeySubscription you can also simplify the default constructor it if you add default member initialization for keySize: class KeySubscription { public: KeySubscription() = default; … private: … size_t keySize{}; };
{ "domain": "codereview.stackexchange", "id": 44945, "lm_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, design-patterns, entity-component-system, glfw", "url": null }
c++, game, design-patterns, entity-component-system, glfw Here you cannot simply remove it because you have non-default constructor as well. Use std::vector for variable sized arrays I see you use std::array in combination with some variable to keep track of how many elements of the array are actually in use. In that case, I recommend using std::vector instead. It avoids having to worry about the maximum size of the array, and it will keep track of its size itself. If you want to avoid memory allocations from happening while your game is running (which could affect your framerate), you can use reserve() to reserve memory for vectors. Unnecessary use of std::unique_ptr and std::shared_ptr You are using std::unique_ptr to store subscriptions in the array callbackToSubscription. However, you did not have to do this, you could store KeySubscriptions by value in the array. Of course, that might waste a lot of space, but that's because you were using std::array. That problem goes away if you also use std::vector: class KeyboardManager { … private: … std::vector<KeySubscription> callbackToSubscriptions; }; This avoids all the hassle of std::make_unique(), std::move(), and keeping correct counts: size_t KeyboardManager::subscribe(key_callback_fn Function, std::vector<GLFWKey> Keys) { … callbackToSubscription.push_back(Keys); … } You are also using std::shared_ptr in MouseManager. I guess it's to work around the fact that you can't use a std::function directly as a key for std::unordered_map. However, this doesn't do what you think it does. It won't cause the function itself to be compared, rather just a pointer to the std::function object referencing to the actual callback function. When you do this in MouseManager::unsubscribe(): auto sharedFunction = std::make_shared<mouse_callback_fn>(Function);
{ "domain": "codereview.stackexchange", "id": 44945, "lm_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, design-patterns, entity-component-system, glfw", "url": null }
c++, game, design-patterns, entity-component-system, glfw You are creating a brand new std::function object with its own address. Comparing sharedFunction with any other std::shared_ptr<mouse_callback_fn> in mouseCallbackToIndex will return false. So in: size_t indexToRemove = mouseCallbackToIndex[sharedFunction];
{ "domain": "codereview.stackexchange", "id": 44945, "lm_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, design-patterns, entity-component-system, glfw", "url": null }
c++, game, design-patterns, entity-component-system, glfw On the right hand side, mouseCallbackToIndex[sharedFunction] will try to look up sharedFunction, finds that it doesn't exist, and will create a new entry in the std::unordered_map. The value of that entry will be zero. So indexToRemove will always be zero. There is unfortunately no safe way to compare std::functions with each other. So instead you should do something like you did in KeyboardManager, where you let subscribe() return an index, and pass that index to unsubscribe(). However, that brings me to: Your unsubscribe() functions are completely wrong Apart from the problem with MouseManager::unsubscribe() which I mentioned above, there are also several problem with KeyboardManager::unsubscribe(). Let's start with lastIndex = usedCallbacks. Please note that usedCallbacks is the number of active elements in the arrays, however C++ starts indexing at zero. So the index of the last element is actually usedCallbacks - 1. At best you are thus accessing an unused element, at worst you are reading past the end of the array. Second, while moving the last element into the place of an earlier erased element is a nice way to get an array without any holes, the problem is that you just invalidated the index of the last element. So if someone subscribes two functions, gets indexes 0 and 1. It then unsubscribes index 0, which means whatever was at index 1 gets moved into index 0. But it doesn't know that, so when it wants to unsubscribe the second function it will call unsubscribe(1), which doesn't do what you want. A third issue is that you called release() on an element that you already move-assigned from in the previous line. This is unnecessary, and in general you should never access any values after you've std::move()d them, as their state might be undefined.
{ "domain": "codereview.stackexchange", "id": 44945, "lm_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, design-patterns, entity-component-system, glfw", "url": null }
c++, game, design-patterns, entity-component-system, glfw A typical solution to the second problem is to never shuffle entries around; this way you avoid invalidating indexes. However, that will create holes in your array or vector. You want to be able to reuse those efficiently, so you can have another vector keep track of the unused indexes in the other vectors. Consider listening for events instead of polling state Your code seems to be geared towards polling the state of all the keys you are interested in, every time callbackAll() is called. I assume that will be once per frame. However, most frames nothing will change, and if something changes it most likely be one or two keys at a time. However, with your approach you have to call glfwGetKey() for all keys you are interested in for every frame, and then you also call all registered callback functions every frame, regardless of any activity. All these function calls do have some cost. Instead, consider having your KeyboardManager call glfwSetKeyCallback() so it will get notified when a key's state has changed. Then it can look up if any of the subscribers are interested in that key, and only then call the registered callback functions of those subscribers. A similar thing can be done with mouse events. Once a frame you have to call glfwPollEvents(), probably at the point where you called the callbackAll() functions before. Answers to your questions
{ "domain": "codereview.stackexchange", "id": 44945, "lm_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, design-patterns, entity-component-system, glfw", "url": null }
c++, game, design-patterns, entity-component-system, glfw KeySubscription feels oddly redundant. Can this just be removed? Yes, I think you can just replace this with a std::vector<GLFWKey>. The MouseState struct feels as though it is containing too much information and violates some principle of object oriented design. Maybe I could pass around 2 MouseState objects instead to show the currentMouseState and the previousMouseState? You could do that. But maybe some subscribers don't even care about the previous state? A subscriber can always store the previous state themselves if they are interested in that. It would be annoying to pass around two states all the time, so maybe I could convert it to a Mouse (containing generic mouse data) and then contain a MouseState with two Mouse objects? If you wanted to pass the current and previous states, that would indeed be a nice way of doing it. Theres some globals around that I didn't want to pass around in every method that needs them, like mCamera (what if I want multiple cameras in the world, like with portals?), or gameWindow (multiple windows in the future?). How can I avoid this? Do I need a gigantic Engine class that keeps track of everything? Putting everything in a class is a good way of doing it. That class doesn't necessarily have to be "gigantic", and even if it is, it's not worse than having that same gigantic amount of state as global variables. Also, it doesn't all have to go into the same class. Only if you have several functions that need access to all the information in your program does it make sense to put everything into such a class. Also consider that some of the state can be moved into existing classes. For example, since the camera is mostly important to the rendering, maybe move mCamera into RenderSystem?
{ "domain": "codereview.stackexchange", "id": 44945, "lm_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, design-patterns, entity-component-system, glfw", "url": null }
c#, multithreading, concurrency, redis, connection-pool Title: Parallel handling db queries is very slow in C# Question: I have SignalR app that publishes sent messages to Redis. My console app subscribe to channel where these messages are sent, deserializes it and saves in database. Problem is with handling these events, as I want to make it in parallel. If many events are published, then the code crashes on opening database connection, because every thread want its own connection, so limit of physical connections is exceeded. So I use SemaphoreSlim to use threads that are available on my machine (8 logical threads). The problem is that the performance is very slow: about 300 inserts to DB per second. I think it's not due to my hardware, as it's pretty good (i7-9700F, 16GB RAM). The application runs at WSL2 (Ubuntu-22.04). That's code: using Dapper; using Messages.Save.Dtos; using Microsoft.Extensions.Configuration; using Npgsql; using StackExchange.Redis; using System.Diagnostics.CodeAnalysis; using System.Text.Json; using System.Text.Json.Nodes; var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json") .Build(); const int MESSAGE_MAX_SENT_AT_OFFSET = 60; RedisChannel UserChannel = new RedisChannel("*SignalRHub.MessagingHub:user:*", RedisChannel.PatternMode.Pattern); RedisChannel GroupChannel = new RedisChannel("*SignalRHub.MessagingHub:group:*", RedisChannel.PatternMode.Pattern); var connectionMultiplexer = ConnectionMultiplexer.Connect(configuration.GetConnectionString("Redis")); var yugabyteConnectionString = configuration.GetConnectionString("YugabyteDB"); var semaphore = new SemaphoreSlim(Environment.ProcessorCount); async void Handler(RedisChannel channel, RedisValue value) { await semaphore.WaitAsync(); await HandleMessageAsync(channel, value); semaphore.Release(); }
{ "domain": "codereview.stackexchange", "id": 44946, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, multithreading, concurrency, redis, connection-pool", "url": null }
c#, multithreading, concurrency, redis, connection-pool var subscriber = connectionMultiplexer.GetSubscriber(); await subscriber.SubscribeAsync(UserChannel, Handler); await subscriber.SubscribeAsync(GroupChannel, Handler); async Task HandleMessageAsync(RedisChannel channel, RedisValue value) { if (channel.IsNullOrEmpty || value.IsNullOrEmpty) return; var saveMessageDto = ReadMessage(value); if (!ValidateMessage(saveMessageDto)) return; using var connection = new NpgsqlConnection(yugabyteConnectionString); await connection.OpenAsync(); var isUserGroupMember = await connection.QuerySingleAsync<bool>(@"SELECT EXISTS( SELECT 1 FROM ConversationMembers WHERE ConversationId=@ConversationId AND UserId=@UserId)::boolean", new { saveMessageDto.ConversationId, UserId = saveMessageDto.SenderId }); if (!isUserGroupMember) return; await connection.ExecuteAsync("INSERT INTO Messages(ConversationId, Message, SentAt) VALUES(@ConversationId, @Message, @SentAt);", new { saveMessageDto.ConversationId, saveMessageDto.Message, saveMessageDto.SentAt }); } static SaveMessageDto? ReadMessage(RedisValue value) { try { var str = value.ToString(); var startIndex = str.IndexOf('{'); var endIndex = str.LastIndexOf('}'); var json = JsonNode.Parse(str.AsSpan(startIndex, endIndex - startIndex + 1).ToString())?.AsObject(); if (json is null || !json.TryGetPropertyValue("arguments", out JsonNode? argsNode) || argsNode is not JsonArray arguments || !arguments.Any()) return null; return JsonSerializer.Deserialize<SaveMessageDto>(arguments[0], new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); } catch { return null; } }
{ "domain": "codereview.stackexchange", "id": 44946, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, multithreading, concurrency, redis, connection-pool", "url": null }
c#, multithreading, concurrency, redis, connection-pool static bool ValidateMessage([NotNullWhen(true)] SaveMessageDto? saveMessageDto) { // some ultra lighweight validation (no impact on performance) return true; } await Task.Delay(Timeout.Infinite); Answer: performance is very slow: about 300 inserts to DB per second. There are two sections of code I have performance concerns about. But first, it would really be worth your while to put a bunch of transaction data into a million-line .CSV and run this single-threaded using a single DB connection, to verify that DB performance is what you think it is. Do it with "small" and "large" BEGIN ... COMMIT transactions, as discussed below. connection pooling using var connection = new NpgsqlConnection(yugabyteConnectionString); await connection.OpenAsync(); It's not clear to me that this does what you hope it does. We hope it pulls from a connection pool and the await (almost always) immediately moves on since it finds a connection that is already open. My concern is that perhaps this always allocates a new local ephemeral TCP port number, does {SYN, SYN-ACK, ACK} 3-way handshake, waits for the listening daemon to fork off a new worker, and then the await completes. It would be worth verifying, even with simple tools like netstat -an. Notice that this concern disappears completely when doing the proposed single-thread benching, as a single persistent connection would be used for that. If you have N threads, I wonder if you'd like to allocate an array that stores N persistent connections. We happen to be holding a mutex (semaphore) upon entry, but with the array that's not even relevant since the i-th thread enjoys exclusive access to the i-th connection. large transactions await connection.ExecuteAsync("INSERT INTO Messages(ConversationId, Message, SentAt) VALUES(@ConversationId, @Message, @SentAt);",
{ "domain": "codereview.stackexchange", "id": 44946, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, multithreading, concurrency, redis, connection-pool", "url": null }
c#, multithreading, concurrency, redis, connection-pool I don't know what your "is user group member" fraction might be, so having done a million SELECTs I'm not sure if we do nearly a million INSERTs or just some small number of them. Let's assume the fraction is 90%, so we usually do the INSERT. I am concerned that perhaps you're effectively sending the following to the database: BEGIN transaction INSERT COMMIT transaction If so, then we would expect DB performance to plummet, perhaps to as low as a mere 300 tx/sec. Databases really want to see "large" transactions if we hope to achieve high throughput. The COMMIT says "persist this to disk and wait for that I/O to complete, so we can survive powerfail". (OTOH, sometimes we need tiny transactions for correctness. It's not clear that your use case fits into that, since you reported performance in terms of throughput rather than 95th-percentile latency.) Here's an easy test you can shoehorn into the current code. For each input we currently do one SELECT and (roughly) one INSERT. Suppose we added a 2nd or even a 3rd useless "busy work" INSERT to the mix. Make a prediction about what reduced performance numbers you anticipate. Then do the experiment to verify. What I'm shooting for is that each HandleMessageAsync call would do BEGIN SELECT INSERT INSERT INSERT COMMIT If my guess about "short transactions" is correct, then you might consider adopting this approach:
{ "domain": "codereview.stackexchange", "id": 44946, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, multithreading, concurrency, redis, connection-pool", "url": null }
c#, multithreading, concurrency, redis, connection-pool If my guess about "short transactions" is correct, then you might consider adopting this approach: In addition to current threads, launch a single "writer" worker, which listens on a FIFO. Threads issue SELECTs to their heart's content. (Maybe without even holding the semaphore.) Rather than sending INSERTs directly, threads append such data to the FIFO. The writer thread bufers up K requests, perhaps ten or a hundred, and issues a "big" transaction of BEGIN / INSERT / INSERT ... / COMMIT. In the 1980's Oracle described this performance trick, applied across several unrelated users, as "group commit". Put e.g. a 30 msec timeout on it, so final messages won't get stalled when we go idle. Writer thread sends K wakeup notices, perhaps via K semaphores, letting those threads report "success" to their end users. If we're concerned about same userid showing up repeatedly within a small time window, we can always finesse that with a local cache of items recently sent & received from the database.
{ "domain": "codereview.stackexchange", "id": 44946, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, multithreading, concurrency, redis, connection-pool", "url": null }
java Title: Combine null check with try-catch block Question: I have this code: CompletableFuture<UaaToken> completableFuture = CompletableFuture.supplyAsync (()-> client.getAction(.........); Token token = null; try { token = completableFuture.get(); } catch (Exception ex) { logger.error("error get token", ex); } if (token == null) { logger.error("No response from server"); throw InternalErrorException.builder().internalError().build(); } else { ....... } How I can combine try-catch block with if block codes so that both checks are made? Answer: 1.) Specific Exceptions : As per the specification of completableFuture.get(), it throws following exceptions. Unchecked Exceptions CancellationException – if this future was cancelled Checked Exceptions ExecutionException – if this future completed exceptionally InterruptedException – if the current thread was interrupted while waiting However you've wrapped them in catch block with generic Exception which is not ideal as it would remove the clarity of actual exception that happened. So instead of enclosing with Exception you should put the exception it can actually throw which is defined in contract. try { token = completableFuture.get(); } catch (InterruptedException | ExecutionException ex) { logger.error("error getting token", ex); } Another extra : You can also wrap both the exceptions into your custom exception and rethrow from this catch block If you want this to be handled from the caller. try { token = completableFuture.get(); } catch (InterruptedException | ExecutionException ex) { logger.error("error getting token", ex); throw new TokenFetchException("error getting token", ex); } 2.) Wrapping your token null logic. You can easily include that logic in the try catch block but I would ask few questions to you. What is type of your InternalErrorException class. An checked or unchecked exception ?
{ "domain": "codereview.stackexchange", "id": 44947, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java", "url": null }
java What is type of your InternalErrorException class. An checked or unchecked exception ? If it is checked exception then either you'd need to add throws clause to this method or handle it inside catch clause. If it is unchecked exception, make sure you add the documentation to the method with @throws. What are the specific errors you getting when merging if else block inside try catch block ? 3.) Use optionals Instead of throwing Exception in case of null, you can use Optional idioms introduced from Java8 onwards. If token can be null then you can return Optional.empty() which makes your method's return type Optional<T> Using Optional will depend on various invariants that you are currently adhering to. So it may or may not be possible to use it. But try to incorporate that practice wherever if possible. 4.) Logging when you're throwing this exception, No clear message will be printed as to what caused this. I might not be aware of internalError() method but you can include clear message as to why it failed in the exception somehow. InternalErrorException.builder().internalError().build(); To capture a failure, the detail message of an exception should contain the values of all parameters and fields that contributed to the exception. In other words, the detail message of an exception should capture the failure for subsequent analysis.
{ "domain": "codereview.stackexchange", "id": 44947, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java", "url": null }
python, performance, python-3.x Title: Python IP geolocation script Question: These are two Python scripts I wrote to convert a GIGANTIC text file of over 100MiB in size (the current version is 152.735MiB) to an SQLite3 database to use for geolocation, and the script that queries the converted SQLite3 database to geolocate a given IP address. The text file is the data dump of IPFire location database, and is updated daily. The repository is here. I found the repository because of this, and if you are to run my script you need to read the COPYING document, because my script automatically downloads the latest version of the text file. My scripts do many things, and I will list the things they do one by one. First as mentioned above, the first script downloads the countries.txt and database.txt from the repository. It then decodes the bytes into string and splits the lines into a list of strings, in preparation for further processing. The content of countries.txt is like this: AD EU Andorra AE AS United Arab Emirates AF AS Afghanistan There are 254 such lines: each line represents a country, and each line has 3 fields; the fields are separated by tabs, and they correspond to country code, continent code and country name, respectively. There is no continent name field, so I searched online and created the following dictionary: CONTINENT_CODES = { "AF": "Africa", "AN": "Antarctica", "AS": "Asia", "EU": "Europe", "NA": "North America", "OC": "Oceania", "SA": "South America", } I split the lines by tab and inserted the corresponding continent name field; after this process the data becomes like this: [ ["AD", "Andorra", "EU", "Europe"], ["AE", "United Arab Emirates", "AS", "Asia"], ["AF", "Afghanistan", "AS", "Asia"] ]
{ "domain": "codereview.stackexchange", "id": 44948, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x", "url": null }
python, performance, python-3.x I then sorted the data (even though the data is already sorted), and created a dictionary where each key is the first element of the row, and value is the index of the row, to find the row index given country code, the data is like this: { "AD": 0, "AE": 1, "AF": 2 } So that I can use a one-byte integer reference for the country and save space. The content of database.txt is much more complicated. It starts with comments, the comment lines start with a hash (#) sign, they are easy to ignore. It is then followed by the block for autonomous systems, the lines are like this: aut-num: AS1 name: LVLT-1 aut-num: AS2 name: UDEL-DCN aut-num: AS3 name: MIT-GATEWAYS
{ "domain": "codereview.stackexchange", "id": 44948, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x", "url": null }
python, performance, python-3.x aut-num: AS3 name: MIT-GATEWAYS There are many lines like these; 291,670 lines to be exact. Every two consecutive non-empty lines correspond to an autonomous system; I'll call these two lines entries. Every pair of entries is separated by an empty line. Each data line starts with some Latin letters and dashes (-), followed by a colon (:), and then some spaces and then some arbitrary characters (you will see later). These lines represent key/value pairs; the key is the string before the first colon and the value is the string after the first colon and many spaces. For autonomous systems, the lines correspond to the ASN and name of each autonomous system. Splitting the data lines by colon once (because the value can contain colons), we can get the key and padded value; we can then call value.strip() to remove leading and trailing spaces. And I removed 'AS' part of each ASN then cast the string to integer, to save space. But identifying when a entry starts and ends is trickier than you might think. I can't just use indexing and split on every third line, because the block is followed by the block for IPv4 networks which has variable line numbers for each entry, so I used a list to cache the current lines, set the cache to initially empty, on empty lines, if cache is not empty, collect the cached items and clear the cache, else add the current data to cache. Then we get the block for IPv4 networks, the lines are like this: net: 1.0.0.0/8 country: AU net: 1.0.0.0/24 country: AU aut-num: 13335 is-anycast: yes net: 1.0.1.0/24 country: CN There are 4,774,208 lines for the IPv4 block, followed by 1,255,713 lines for IPv6 block: net: 2000::/12 aut-num: 3356 net: 2001::/32 aut-num: 6939
{ "domain": "codereview.stackexchange", "id": 44948, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x", "url": null }
python, performance, python-3.x net: 2001::/32 aut-num: 6939 net: 2001:4:112::/48 aut-num: 112
{ "domain": "codereview.stackexchange", "id": 44948, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x", "url": null }
python, performance, python-3.x All consecutive non-empty lines are equivalent to dictionaries, as explained above. These dictionaries contain information about the slash notation of the networks, ASN of the network, country of the network, and additional information. But there are many problems with these blocks. First and most obvious is that these dictionaries don't always have the same number of keys; multiple keys may be missing. The 'net' key is always present, all other keys can be missing. A full dictionary has the following keys: "net", "aut-num", "country", "is-anonymous-proxy", "is-anycast", "is-satellite-provider", "drop". If any key is missing, it means the omitted value is falsy. For country and ASN, fill the missing value with None; the last 4 values are booleans, and if they appear the value is always 'yes', replace with True, else fill with False. Then there are lot of overlapping network ranges and adjacent ranges with same data. I need to ignore the smaller range if the overlapping ranges have same data, and subtract the smaller range from the larger range and overwrite the larger range with the smaller range's data if the overlapping ranges have different data, and then merge adjacent ranges with same data... See this question for more details, and though I have written a truly correct version to discretize the ranges when they don't intersect and when they overlap one is always subset of another (which is the case for the data), my code takes twice as much time as the accepted answer's solution to execute given the same data, so I used code from that answer to do this. And this is the only code in my scripts that isn't originally wrote by me.
{ "domain": "codereview.stackexchange", "id": 44948, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x", "url": null }
python, performance, python-3.x And then the data contains many duplicate combinations of ASN, country and booleans. I replaced the country with the reference to the corresponding row in the countries table, packed the booleans into a 4-bit integer, and cast the triplet to tuple, so that I can use the tuple as a key. I then look up the table containing unique combinations of the triplets, check if the tuple is present and add it if not present, then replace the combination with the index of the tuple in the unique combinations table, to save space. And then, because I merged the overlapping networks, I need to convert the ranges back to correct network slash notations. At first I just used binary decomposition of the number of addresses and just add a network for each power, however I got errors like this when I tried to verify the networks: ValueError: 1.0.1.0/23 has host bits set
{ "domain": "codereview.stackexchange", "id": 44948, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x", "url": null }
python, performance, python-3.x So I find the index of the first bit that isn't set after the last set bit in the start of the range, and get the binary decomposition of the count, find the first power with value greater than or equal to the index using binary search (bisect_left). If found, add network slash notation and pop the value, else pop the value before insertion index and add all values between the popped value (not-including) and the index (including) to stack. I do this repeatedly until stack is empty. And I wrote a script to geolocate a given IP address using the database I created with the first script. First of all, I have benchmarked SQLite3, and for my disk-based database, querying anything takes milliseconds because of I/O delay. This is unacceptable so I load everything into memory upfront. I only use SQLite3 to serialize the data. And then I checked whether the IP address is reserved before the actual processing; an exception is raised if the IP is reserved. The range an IP belongs to is found using binary search on the start column: if the IP is less than or equal to the corresponding end IP, the IP belongs to the range, and the information about the network is retrieved using indexing on the corresponding third column, the result of the query is used to index NETWORK_INFORMATION list, and then the corresponding ASN and country is retrieved using indexing again. Script to create the database import gc import re import requests import sqlite3 import time from bisect import bisect_left from collections import deque from enum import Enum from ipaddress import IPv4Network, IPv6Network from pathlib import Path from typing import Any, Deque, Generator, Iterable, Iterator, List, Sequence, Tuple script_start = time.time()
{ "domain": "codereview.stackexchange", "id": 44948, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x", "url": null }
python, performance, python-3.x script_start = time.time() MAX_SQLITE_INT = 2**63 - 1 MAX_IPV4 = 2**32 - 1 MAX_IPV6 = 2**128 - 1 IPV6DIGITS = set("0123456789abcdef:") le255 = r"(25[0-5]|2[0-4]\d|[01]?\d\d?)" IPV4_PATTERN = re.compile(rf"^{le255}\.{le255}\.{le255}\.{le255}$") EMPTY = re.compile(r":?\b(?:0\b:?)+") FIELDS = re.compile(r"::?|[\da-f]{1,4}") JSON_TYPES = {True: "true", False: "false", None: "null"} KEYS_RENAME = [ ("net", "network"), ("aut-num", "ASN"), ("country", "country_code"), ("is-anonymous-proxy", "is_anonymous_proxy"), ("is-anycast", "is_anycast"), ("is-satellite-provider", "is_satellite_provider"), ("drop", "bad"), ] CONTINENT_CODES = { "AF": "Africa", "AN": "Antarctica", "AS": "Asia", "EU": "Europe", "NA": "North America", "OC": "Oceania", "SA": "South America", } DEFAULTS = { "network": None, "ASN": None, "country_code": None, "is_anonymous_proxy": False, "is_anycast": False, "is_satellite_provider": False, "bad": False, } COLUMNS_SQL = """ create table if not exists {}( network text primary key, network_info int not null ); """ Path("D:/network_guard/IPFire_locations.db").unlink(missing_ok=True) sqlite3.register_adapter(int, lambda x: hex(x) if x > MAX_SQLITE_INT else x) sqlite3.register_converter("integer", lambda b: int(b, 16 if b[:2] == b"0x" else 10)) conn = sqlite3.connect( "D:/network_guard/IPFire_locations.db", detect_types=sqlite3.PARSE_DECLTYPES ) cur = conn.cursor() data_loading_start = time.time() COUNTRY_CODES = requests.get( "https://git.ipfire.org/?p=location/location-database.git;a=blob_plain;f=countries.txt;hb=HEAD" ).content Path("D:/network_guard/countries.txt").write_bytes(COUNTRY_CODES) COUNTRY_CODES = [i.split("\t") for i in COUNTRY_CODES.decode().splitlines()] COUNTRY_CODES = sorted([(a, c, b, CONTINENT_CODES[b]) for a, b, c in COUNTRY_CODES]) COUNTRY_INDEX = {e[0]: i for i, e in enumerate(COUNTRY_CODES)}
{ "domain": "codereview.stackexchange", "id": 44948, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x", "url": null }
python, performance, python-3.x DATA = requests.get( "https://git.ipfire.org/?p=location/location-database.git;a=blob_plain;f=database.txt;hb=HEAD" ).content Path("D:/network_guard/database.txt").write_bytes(DATA) DATA = (i for i in DATA.decode().splitlines() if not i.startswith("#")) print(f"downloading data: {time.time() - data_loading_start:.3f} seconds") cur.execute( """ create table if not exists Country_Codes( country_code text primary key, country_name text not null, continent_code text not null, continent_name text not null ) """ ) cur.execute( """ create table if not exists Autonomous_Systems( ASN int primary key, entity text not null ) """ ) cur.execute( """ create table if not exists Network_Information( ASN int, country_code int, booleans int ) """ ) cur.execute(COLUMNS_SQL.format("IPv4")) cur.execute(COLUMNS_SQL.format("IPv6")) cur.executemany("insert into Country_Codes values (?, ?, ?, ?);", COUNTRY_CODES) conn.commit() KEY_ORDER = [ "ASN", "country_code", "is_anonymous_proxy", "is_anycast", "is_satellite_provider", "bad", ] def parse_ipv4(ip: str) -> int: assert (match := IPV4_PATTERN.match(ip)) a, b, c, d = match.groups() return (int(a) << 24) + (int(b) << 16) + (int(c) << 8) + int(d) def to_ipv4(n: int) -> str: assert 0 <= n <= MAX_IPV4 return f"{n >> 24 & 255}.{n >> 16 & 255}.{n >> 8 & 255}.{n & 255}" def preprocess_ipv6(ip: str) -> Tuple[list, bool, int]: assert 2 < len(ip) <= 39 and not set(ip) - IPV6DIGITS compressed = False terminals = False segments = ip.lower().split(":") if not segments[0]: assert not segments[1] terminals = 1 compressed = True segments = segments[2:] if not segments[-1]: assert not compressed and not segments[-2] terminals = 2 segments = segments[:-2] return segments, compressed, terminals
{ "domain": "codereview.stackexchange", "id": 44948, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x", "url": null }
python, performance, python-3.x return segments, compressed, terminals def split_ipv6(ip: str) -> Deque[str]: segments, compressed, terminals = preprocess_ipv6(ip) chunks = deque() if terminals == 1: chunks.append("::") length = len(segments) minus_one = compressed or terminals or "" in segments if (minus_one and length == 8) or (not minus_one and length < 8) or length > 8: raise ValueError(f"{ip} is invalid") for seg in segments: if not seg: assert not compressed chunks.append("::") compressed = True else: assert len(seg) <= 4 chunks.append(seg) if terminals == 2: chunks.append("::") return chunks def parse_ipv6(ip: str) -> int: if ip == "::": return 0 segments = split_ipv6(ip) pos = 7 n = 0 for i, seg in enumerate(segments): if seg == "::": pos = len(segments) - i - 2 else: n += int(seg, 16) << pos * 16 pos -= 1 return n def to_ipv6(n: int, compress: bool = True) -> str: assert 0 <= n <= MAX_IPV6 ip = "{:039_x}".format(n).replace("_", ":") if compress: ip = ":".join(s.lstrip("0") if s != "0000" else "0" for s in ip.split(":")) longest = max(EMPTY.findall(ip), key=len, default="") if len(longest) > 3: ip = ip.replace(longest, "::", 1) return ip class IPv4(Enum): parser = parse_ipv4 formatter = to_ipv4 power = 32 maximum = MAX_IPV4 class IPv6(Enum): parser = parse_ipv6 formatter = to_ipv6 power = 128 maximum = MAX_IPV6 class IP_Address: def __str__(self) -> str: return self.string def __int__(self) -> int: return self.integer def __repr__(self) -> str: return f"IP_Address(integer={self.integer}, string='{self.string}', version={self.version.__name__})"
{ "domain": "codereview.stackexchange", "id": 44948, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x", "url": null }
python, performance, python-3.x def __init__(self, value: int | str, version: IPv4 | IPv6 = None) -> None: if isinstance(value, str): self.from_string(value, version) else: self.from_integer(value, version) self.maxpower = 32 if self.version == IPv4 else 128 self.hexadecimal = ( f"{self.integer:08x}" if version == IPv4 else f"{self.integer:032x}" ) self.pointer = None def from_string(self, value: str, version: IPv4 | IPv6) -> None: if not version: version = IPv4 if IPV4_PATTERN.match(value) else IPv6 self.integer = version.parser(value) self.string = value self.version = version def from_integer(self, value: int, version: IPv4 | IPv6) -> None: assert isinstance(value, int) if not version: version = IPv4 if 0 <= value <= MAX_IPV4 else IPv6 self.string = version.formatter(value) self.integer = value self.version = version def get_pointer(self) -> str: if not self.pointer: if self.version == IPv4: self.pointer = ".".join(self.string.split(".")[::-1]) + ".in-addr.arpa" else: self.pointer = ".".join(self.hexadecimal[::-1]) + ".ip6.arpa" return self.pointer def parse_network(network: str) -> Tuple[int, int]: start, slash = network.split("/") start = IP_Address(start) slash = int(slash) count = 2 ** (start.maxpower - slash) end = IP_Address(start.integer + count - 1) return start.integer, end.integer ASN = deque() IPV4_TABLE = deque() IPV6_TABLE = deque() NETWORK_INFO = {} def parse_entry(entry: Deque[tuple]) -> list: entry = dict(entry) entry = { new_key: v if (v := entry.get(key, DEFAULTS[new_key])) != "yes" else True for key, new_key in KEYS_RENAME } assert (network := entry["network"]) asn = entry["ASN"] if asn != None: entry["ASN"] = int(asn)
{ "domain": "codereview.stackexchange", "id": 44948, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x", "url": null }
python, performance, python-3.x info = [entry[k] for k in KEY_ORDER] info[1] = COUNTRY_INDEX.get(info[1]) number = sum(p for b, p in zip(info[2:], (8, 4, 2, 1)) if b) return [ *parse_network(network), NETWORK_INFO.setdefault((*info[:2], number), len(NETWORK_INFO)), ] data_processing_start = time.time() entry = deque() for line in DATA: if not line: if entry: if entry[0][0] == "aut-num": ASN.append((int(entry[0][1][2:]), entry[1][1])) else: assert entry[0][0] == "net" ip = entry[0][1].split("/")[0] table = IPV4_TABLE if IPV4_PATTERN.match(ip) else IPV6_TABLE table.append(parse_entry(entry)) entry = deque() else: key, val = line.split(":", 1) entry.append((key, val.strip())) print(f"converting data: {time.time() - data_processing_start:.3f} seconds") def discrete_segments(ranges: List[Tuple[int, int, Any]]) -> Generator: ranges.append((1e309, None, None)) stack = [] current = ranges[0][0] for start, end, data in ranges: while stack and stack[-1][0] < start: end2, data2 = stack.pop() if current <= end2: yield current, end2, data2 current = end2 + 1 if stack and current < start: yield current, start - 1, stack[-1][1] current = start if not stack or stack[-1][1] != data or end > stack[-1][0]: stack.append((end, data)) def merge(segments: Iterator) -> Generator: start, end, data = next(segments) for start2, end2, data2 in segments: if data == data2 and end + 1 == start2: end = end2 else: yield start, end, data start, end, data = start2, end2, data2 yield start, end, data
{ "domain": "codereview.stackexchange", "id": 44948, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x", "url": null }
python, performance, python-3.x def discretize(ranges: List[Tuple[int, int, Any]]) -> List[Tuple[int, int, Any]]: if not ranges: return [] result = list(merge(discrete_segments(ranges))) ranges.pop() return result def binary_decompose(n: int, power: int) -> List[int]: return [ power - i for i, d in enumerate(bin(n).removeprefix("0b")[::-1]) if d == "1" ][::-1] def to_network(item: Sequence, version: IPv4 | IPv6 = IPv4) -> Generator[tuple, None, None]: start, end, data = item power = version.power.value formatter = version.formatter powers = binary_decompose(end - start + 1, power) while powers: min_slash = f"{start:0{power}b}".rindex("1") + 1 index = bisect_left(powers, min_slash) if index == (l := len(powers)): for i, n in enumerate( range(powers.pop(-1) + 1, min_slash + 1), start=l - 1 ): powers.insert(i, n) continue yield (f"{formatter(start)}/{(slash := powers.pop(index))}", data) start += 1 << power - slash data_analyzing_start = time.time() ANALYZED_IPV4 = [] for networks in map(to_network, merge(discrete_segments(IPV4_TABLE))): ANALYZED_IPV4.extend(networks) del IPV4_TABLE gc.collect() IPV4_TABLE = ANALYZED_IPV4 ANALYZED_IPV6 = [] for networks in map( lambda x: to_network(x, IPv6), merge(discrete_segments(IPV6_TABLE)) ): ANALYZED_IPV6.extend(networks) del IPV6_TABLE gc.collect() IPV6_TABLE = ANALYZED_IPV6 NETWORK_INFO = list(NETWORK_INFO) print(f"analyzing data: {time.time() - data_analyzing_start:.3f} seconds")
{ "domain": "codereview.stackexchange", "id": 44948, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x", "url": null }
python, performance, python-3.x data_saving_start = time.time() cur.executemany("insert into Autonomous_Systems values (?, ?);", ASN) cur.executemany(f"insert into IPv4 values ({', '.join(['?']*2)});", IPV4_TABLE) cur.executemany(f"insert into IPv6 values ({', '.join(['?']*2)});", IPV6_TABLE) cur.executemany( f"insert into Network_Information values ({', '.join(['?']*3)});", NETWORK_INFO ) conn.commit() print(f"SQLite3 serializing: {time.time() - data_saving_start:.3f} seconds") def json_repr(row: Sequence) -> str: items = deque() for e in row: if isinstance(e, (int, float)) and not isinstance(e, bool): items.append(f"{e}") elif isinstance(e, str): item = e.replace('"', '\\"') items.append(f'"{item}"') else: items.append(JSON_TYPES[e]) return "[" + ", ".join(items) + "]" def pretty_table(table: Iterable[Sequence]) -> str: return "[\n" + "\n".join(f"\t{json_repr(row)}," for row in table)[:-1] + "\n]" data_serializing_start = time.time() Path("D:/network_guard/IPv4_table.json").write_text(pretty_table(IPV4_TABLE)) Path("D:/network_guard/IPv6_table.json").write_text(pretty_table(IPV6_TABLE)) Path("D:/network_guard/Autonomous_Systems.json").write_text( pretty_table(ASN), encoding="utf8" ) Path("D:/network_guard/Country_Codes.json").write_text( pretty_table(COUNTRY_CODES), encoding="utf8" ) Path("D:/network_guard/Network_Information.json").write_text(pretty_table(NETWORK_INFO)) print(f"JSON serializing: {time.time() - data_serializing_start:.3f} seconds") data_verifying_start = time.time() IPV4_NETWORKS = [IPv4Network(a) for a, _ in IPV4_TABLE] IPV6_NETWORKS = [IPv6Network(a) for a, _ in IPV6_TABLE] for a, b in zip(IPV4_NETWORKS, IPV4_NETWORKS[1:]): assert a.network_address + a.num_addresses <= b.network_address
{ "domain": "codereview.stackexchange", "id": 44948, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x", "url": null }
python, performance, python-3.x for a, b in zip(IPV6_NETWORKS, IPV6_NETWORKS[1:]): assert a.network_address + a.num_addresses <= b.network_address print(f"verifying data: {time.time() - data_verifying_start:.3f} seconds") print(f"full script: {time.time() - script_start:.3f} seconds") Script to query the database import gc import json import re import sqlite3 from bisect import bisect from collections import deque from enum import Enum from typing import Deque, Tuple MAX_IPV4 = 2**32 - 1 MAX_IPV6 = 2**128 - 1 MAX_SQLITE_INT = 2**63 - 1 le255 = r"(25[0-5]|2[0-4]\d|[01]?\d\d?)" IPV4_PATTERN = re.compile(rf"^{le255}\.{le255}\.{le255}\.{le255}$") IPV6DIGITS = set("0123456789abcdef:") EMPTY = re.compile(r":?\b(?:0\b:?)+") FIELDS = re.compile(r"::?|[\da-f]{1,4}") SUAB4 = [ (0x00000000, 0x00FFFFFF), (0x0A000000, 0x0AFFFFFF), (0x64400000, 0x647FFFFF), (0x7F000000, 0x7FFFFFFF), (0xA9FE0000, 0xA9FEFFFF), (0xAC100000, 0xAC1FFFFF), (0xC0000000, 0xC00000FF), (0xC0000200, 0xC00002FF), (0xC0586300, 0xC05863FF), (0xC0A80000, 0xC0A8FFFF), (0xC6120000, 0xC613FFFF), (0xC6336400, 0xC63364FF), (0xCB007100, 0xCB0071FF), (0xE0000000, 0xFFFFFFFF), ]
{ "domain": "codereview.stackexchange", "id": 44948, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x", "url": null }
python, performance, python-3.x SUAB6 = [ ( 0x0, 0x1 ), ( 0xFFFF << 0x20, (1 << 0x30) - 1 ), ( 0xFFFF << 0x30, (0xFFFF0000 + 1 << 0x20) - 1 ), ( 0x64FF9B << 0x60, ((0x64FF9B << 0x40) + 1 << 0x20) - 1 ), ( 0x64FF9B0001 << 0x50, (0x327FCD8000 + 1 << 0x51) - 1 ), ( 0x1 << 0x78, ((0x1 << 0x38) + 1 << 0x40) - 1 ), ( 0x2001 << 0x70, (0x20010000 + 1 << 0x60) - 1 ), ( 0x1000801 << 0x65, (0x2001002 + 1 << 0x64) - 1 ), ( 0x40021B7 << 0x63, (0x20010DB8 + 1 << 0x60) - 1 ), ( 0x1001 << 0x71, (0x2002 + 1 << 0x70) - 1 ), ( 0x3F << 0x7A, (0x7E + 1 << 0x79) - 1 ), ( 0x1FD << 0x77, (0x3FA + 1 << 0x76) - 1 ), ( 0xFF << 0x78, (1 << 0x80) - 1 ), ] SUAB6_STARTS, SUAB6_ENDS = zip(*SUAB6) SUAB6_FIRST_FIELDS = {f for s, e in SUAB6 for f in range(s >> 112, (e >> 112) + 1)} SUAB4_STARTS, SUAB4_ENDS = zip(*SUAB4) SUAB4_FIRST_BYTES = {b for s, e in SUAB4 for b in range(s >> 24, (e >> 24) + 1)} COUNTRY_FIELDS = ("Country_Code", "Country_Name", "Continent_Code", "Continent_Name") FLAGS = ("is_anonymous_proxy", "is_anycast", "is_satellite_provider", "bad") def is_reserved_ipv4(ip: int) -> bool: if ip >> 24 not in SUAB4_FIRST_BYTES: return False i = bisect(SUAB4_STARTS, ip) - 1 return SUAB4_STARTS[i] <= ip <= SUAB4_ENDS[i] def is_reserved_ipv6(ip: int) -> bool: if ip >> 112 not in SUAB6_FIRST_FIELDS: return False i = bisect(SUAB6_STARTS, ip) - 1 return SUAB6_STARTS[i] <= ip <= SUAB6_ENDS[i] def parse_ipv4(ip: str) -> int: assert (match := IPV4_PATTERN.match(ip)) a, b, c, d = match.groups() return (int(a) << 24) + (int(b) << 16) + (int(c) << 8) + int(d) def to_ipv4(n: int) -> str: assert 0 <= n <= MAX_IPV4 return f"{n >> 24 & 255}.{n >> 16 & 255}.{n >> 8 & 255}.{n & 255}"
{ "domain": "codereview.stackexchange", "id": 44948, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x", "url": null }
python, performance, python-3.x def preprocess_ipv6(ip: str) -> Tuple[list, bool, int]: assert 2 < len(ip) <= 39 and not set(ip) - IPV6DIGITS compressed = False terminals = False segments = ip.lower().split(":") if not segments[0]: assert not segments[1] terminals = 1 compressed = True segments = segments[2:] if not segments[-1]: assert not compressed and not segments[-2] terminals = 2 segments = segments[:-2] return segments, compressed, terminals def split_ipv6(ip: str) -> Deque[str]: segments, compressed, terminals = preprocess_ipv6(ip) chunks = deque() if terminals == 1: chunks.append("::") length = len(segments) minus_one = compressed or terminals or "" in segments if ( (minus_one and length == 8) or (not minus_one and length < 8) or length > 8 ): raise ValueError(f"{ip} is invalid") for seg in segments: if not seg: assert not compressed chunks.append("::") compressed = True else: assert len(seg) <= 4 chunks.append(seg) if terminals == 2: chunks.append("::") return chunks def parse_ipv6(ip: str) -> int: if ip == "::": return 0 segments = split_ipv6(ip) pos = 7 n = 0 for i, seg in enumerate(segments): if seg == "::": pos = len(segments) - i - 2 else: n += int(seg, 16) << pos * 16 pos -= 1 return n def to_ipv6(n: int, compress: bool = True) -> str: assert 0 <= n <= MAX_IPV6 ip = "{:039_x}".format(n).replace("_", ":") if compress: ip = ":".join(s.lstrip("0") if s != "0000" else "0" for s in ip.split(":")) longest = max(EMPTY.findall(ip), key=len, default="") if len(longest) > 3: ip = ip.replace(longest, "::", 1) return ip
{ "domain": "codereview.stackexchange", "id": 44948, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x", "url": null }
python, performance, python-3.x return ip def parse_ipv4_network(data: Tuple[str, int]) -> Tuple[int]: network, inforef = data start, slash = network.split("/") start = parse_ipv4(start) return start, start + (1 << 32 - int(slash)) - 1, inforef def parse_ipv6_network(data: Tuple[str, int]) -> Tuple[int]: network, inforef = data start, slash = network.split("/") start = parse_ipv6(start) return start, start + (1 << 128 - int(slash)) - 1, inforef sqlite3.register_adapter(int, lambda x: hex(x) if x > MAX_SQLITE_INT else x) sqlite3.register_converter("integer", lambda b: int(b, 16 if b[:2] == b"0x" else 10)) conn = sqlite3.connect( "D:/network_guard/IPFire_locations.db", detect_types=sqlite3.PARSE_DECLTYPES ) cur = conn.cursor() cur.execute("select * from Country_Codes;") COUNTRIES = cur.fetchall() cur.execute("select * from Autonomous_Systems;") AUTONOMOUS_SYSTEMS = dict(cur.fetchall()) cur.execute("select * from Network_Information;") NETWORK_INFORMATION = cur.fetchall() cur.execute("select * from IPv4;") IPV4_STARTS, IPV4_ENDS, IPV4_INFOREFS = zip(*map(parse_ipv4_network, cur.fetchall())) cur.execute("select * from IPv6;") IPV6_STARTS, IPV6_ENDS, IPV6_INFOREFS = zip(*map(parse_ipv6_network, cur.fetchall())) gc.collect() def repr_ipv4(integer: int, string: str) -> dict: return { "string": string, "decimal": integer, "hexadecimal": f"{integer:08x}", "binary": f"{integer:032b}", } def repr_ipv6(integer: int, string: str) -> dict: return { "string": string, "decimal": integer, "hexadecimal": "{:039_x}".format(integer), "binary": f"{integer:0128b}", } def parse_network_info(index: int, reference: list) -> dict: asn, country, flags = NETWORK_INFORMATION[reference[index]] if asn is not None: asn = {"ASHandle": f"AS{asn}", "entity": AUTONOMOUS_SYSTEMS[asn], "number": asn} if country is not None: country = dict(zip(COUNTRY_FIELDS, COUNTRIES[country]))
{ "domain": "codereview.stackexchange", "id": 44948, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x", "url": null }
python, performance, python-3.x if country is not None: country = dict(zip(COUNTRY_FIELDS, COUNTRIES[country])) return { "Autonomous_System": asn, "Country": country, "Flags": dict(zip(FLAGS, (bool(flags & i) for i in (8, 4, 2, 1)))), } def get_ipv4_info(ip: int) -> dict: if is_reserved_ipv4(ip): raise ValueError(f"{ip} is a reserved IPv4 address") i = bisect(IPV4_STARTS, ip) - 1 if not (start := IPV4_STARTS[i]) <= ip <= (end := IPV4_ENDS[i]): return None return to_network(start, end, IPv4) | parse_network_info(i, IPV4_INFOREFS) def get_ipv6_info(ip: int) -> dict: if is_reserved_ipv6(ip): raise ValueError(f"{ip} is a reserved IPv6 address") i = bisect(IPV6_STARTS, ip) - 1 if not (start := IPV6_STARTS[i]) <= ip <= (end := IPV6_ENDS[i]): return None return to_network(start, end, IPv6) | parse_network_info(i, IPV6_INFOREFS) class IPv4(Enum): parser = parse_ipv4 formatter = to_ipv4 power = 32 maximum = MAX_IPV4 query = get_ipv4_info repr = repr_ipv4 class IPv6(Enum): parser = parse_ipv6 formatter = to_ipv6 power = 128 maximum = MAX_IPV6 query = get_ipv6_info repr = repr_ipv6 def to_network(start: int, end: int, version: IPv4 | IPv6) -> dict: start_ip = version.formatter(start) count = end - start + 1 slash = version.power.value - (count).bit_length() + 1 mask = ((1 << slash) - 1) << (version.power.value - slash) return { "network": f"{start_ip}/{slash}", "version": version.__name__, "start": version.repr(start, start_ip), "end": version.repr(end, version.formatter(end)), "count": count, "slash": slash, "netmask": version.repr(mask, version.formatter(mask)), } def get_ipinfo(ip: int | str, version: IPv4 | IPv6 = None) -> dict: if version: if isinstance(ip, str): ip = version.parser(ip)
{ "domain": "codereview.stackexchange", "id": 44948, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x", "url": null }
python, performance, python-3.x assert 0 <= ip <= version.maximum.value return version.query(ip) if isinstance(ip, str): version = IPv4 if IPV4_PATTERN.match(ip) else IPv6 elif ip < 0 or ip > MAX_IPV6: raise ValueError(f"{ip} is not a valid IP address") else: version = IPv4 if ip <= MAX_IPV4 else IPv6 return get_ipinfo(ip, version) if __name__ == '__main__': print(json.dumps(get_ipinfo('142.250.65.174'), indent=4)) print(json.dumps(get_ipinfo('2404:6800:4003:c03::88'), indent=4)) Timing downloading data: 9.618 seconds converting data: 36.807 seconds analyzing data: 11.901 seconds SQLite3 serializing: 5.419 seconds JSON serializing: 2.775 seconds verifying data: 19.156 seconds full script: 86.491 seconds
{ "domain": "codereview.stackexchange", "id": 44948, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x", "url": null }
python, performance, python-3.x Example output { "network": "142.250.0.0/15", "version": "IPv4", "start": { "string": "142.250.0.0", "decimal": 2398748672, "hexadecimal": "8efa0000", "binary": "10001110111110100000000000000000" }, "end": { "string": "142.251.255.255", "decimal": 2398879743, "hexadecimal": "8efbffff", "binary": "10001110111110111111111111111111" }, "count": 131072, "slash": 15, "netmask": { "string": "255.254.0.0", "decimal": 4294836224, "hexadecimal": "fffe0000", "binary": "11111111111111100000000000000000" }, "Autonomous_System": { "ASHandle": "AS15169", "entity": "GOOGLE", "number": 15169 }, "Country": { "Country_Code": "US", "Country_Name": "United States of America", "Continent_Code": "NA", "Continent_Name": "North America" }, "Flags": { "is_anonymous_proxy": false, "is_anycast": false, "is_satellite_provider": false, "bad": false } } { "network": "2404:6800::/32", "version": "IPv6", "start": { "string": "2404:6800::", "decimal": 47875086406289890508775266669543030784, "hexadecimal": "2404_6800_0000_0000_0000_0000_0000_0000", "binary": "00100100000001000110100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" }, "end": { "string": "2404:6800:ffff:ffff:ffff:ffff:ffff:ffff", "decimal": 47875086485518053023039604263086981119, "hexadecimal": "2404_6800_ffff_ffff_ffff_ffff_ffff_ffff", "binary": "00100100000001000110100000000000111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111" }, "count": 79228162514264337593543950336, "slash": 32, "netmask": { "string": "ffff:ffff::", "decimal": 340282366841710300949110269838224261120,
{ "domain": "codereview.stackexchange", "id": 44948, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x", "url": null }
python, performance, python-3.x "string": "ffff:ffff::", "decimal": 340282366841710300949110269838224261120, "hexadecimal": "ffff_ffff_0000_0000_0000_0000_0000_0000", "binary": "11111111111111111111111111111111000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" }, "Autonomous_System": { "ASHandle": "AS15169", "entity": "GOOGLE", "number": 15169 }, "Country": { "Country_Code": "AU", "Country_Name": "Australia", "Continent_Code": "OC", "Continent_Name": "Oceania" }, "Flags": { "is_anonymous_proxy": false, "is_anycast": false, "is_satellite_provider": false, "bad": false } }
{ "domain": "codereview.stackexchange", "id": 44948, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x", "url": null }
python, performance, python-3.x I have checked the memory usage of the interpreter in task manager. Right before running the code to create the database, it uses around 193MiB RAM. Right after the script is completed and without doing anything else, the interpreter uses around 1223MiB RAM, so my data takes about 1030MiB. That is more than 1GiB, and this is after my compression. I closed the interpreter and opened another section; It uses around 60MiB RAM upon start. I pasted the code to query the database and run the code; the interpreter uses around 360MiB RAM after that, so loading the data from the SQLite3 database takes around 300MiB RAM. I didn't use the IPv4Network and IPv6Network classes from the ipaddress module, because as you can clearly see from my timing, converting the data to the classes is extremely slow. It takes around 15 seconds, but my code takes around 6 seconds. There are other IP geolocation database text dumps that I have access to, and my code can be trivially modified to convert those files as well. How can I improve my code? Answer: Here are a few suggestions that immediately come to mind. First, concerning the database creation script: You specify 'D:/network_guard/IPFire_locations.db' in multiple locations. Better would be to define a constant such as DB_PATH and use that instead. You delete the database file but then when you go to create the database tables you use the "if exits" clause, which seems superfluous.
{ "domain": "codereview.stackexchange", "id": 44948, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x", "url": null }
python, performance, python-3.x You are reading the entire input text file into variable DATA followed by writing it out to disk and its processing for loading the database. You could save memory by getting the URL contents line by line. For example: with Path("D:/network_guard/database.txt").open("w") as database_txt: resp = requests.get( "https://git.ipfire.org/?p=location/location-database.git;a=blob_plain;f=database.txt;hb=HEAD", stream=True ) entry = deque() for line in resp.iter_lines(): line = line.decode() print(line, file=database_txt) if line.startswith("#"): continue if not line: if entry: if entry[0][0] == "aut-num": ASN.append((int(entry[0][1][2:]), entry[1][1])) else: assert entry[0][0] == "net" ip = entry[0][1].split("/")[0] table = IPV4_TABLE if IPV4_PATTERN.match(ip) else IPV6_TABLE table.append(parse_entry(entry)) entry = deque() else: key, val = line.split(":", 1) entry.append((key, val.strip())) In function parse_ipv4 you have assert (match := IPV4_PATTERN.match(ip)). If you should compile with optimization, the assert expression will not be evaluated and match will be undefined. I would recommend that you change this to: match = IPV4_PATTERN.match(ip) assert match As for the script to query the database: parse_ipv4 should be changed as described above. Function get_ipinfo uses unnecessary recursion that neither improves efficiency not clarity. Change to: def get_ipinfo(ip: int | str, version: IPv4 | IPv6 = None) -> dict: if not version: if isinstance(ip, str): version = IPv4 if IPV4_PATTERN.match(ip) else IPv6 elif ip < 0 or ip > MAX_IPV6: raise ValueError(f"{ip} is not a valid IP address") else: version = IPv4 if ip <= MAX_IPV4 else IPv6
{ "domain": "codereview.stackexchange", "id": 44948, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x", "url": null }
python, performance, python-3.x if isinstance(ip, str): ip = version.parser(ip) assert 0 <= ip <= version.maximum.value return version.query(ip) General Remarks You have functions (such as parse_ipv4, to_ipv4, parse_ipv6, to_ipv6 etc.) and code fragments that are common to both scripts and should be placed in a module that can be imported. For example, you might take the code fragment you use to connect to the database and place them in a function connect: def connect(): sqlite3.register_adapter(int, lambda x: hex(x) if x > MAX_SQLITE_INT else x) sqlite3.register_converter("integer", lambda b: int(b, 16 if b[:2] == b"0x" else 10)) return sqlite3.connect( "D:/network_guard/IPFire_locations.db", detect_types=sqlite3.PARSE_DECLTYPES ) In function parse_ipv4 you must decide whether you are assuming the input is correct and you just need to parse the input string into its 4 decimal numbers or whether you want to rigorously validate the input string because it might be invalid. If the former, then you could use a more efficient method such as splitting the input on '.'. If the latter, then you should not use an assert statement to check whether the regex succeeded in matching the input. As I have mentioned, if you compile with optimization, then the assert statement will never be executed. Instead you should explicitly check match with an if statement and raise, for example, a ValueError if match is None. You should not in general be using assert statements to validate user input. Also, in a regex \d is not equivalent to [0-9] unless the re.ASCII flag is set. You should be using [0-9] instead. Since you are not using the ipaddress module, it would be less confusing if you did not import it. In your script to create the database, you have: table = IPV4_TABLE if IPV4_PATTERN.match(ip) else IPV6_TABLE If you assume that the input data is valid, I would think this could be more cheaply calculated with: table = IPV4_TABLE if '.' in ip else IPV6_TABLE
{ "domain": "codereview.stackexchange", "id": 44948, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x", "url": null }
python, performance, python-3.x You are using a deque as your "cache" but only appending items to it. For what it's worth, I benchmarked the repeated creation of a deque followed by appending N tuples of two integers to it and then did the same for a list. I determined that on my desktop running Python 3.8.5 that for small values of N (<= 10) that the deque is slower (for N == 4, it is 12% slower). As N increases beyond 10 then the deque starts to outperform the list (for N == 1_000_000, the list is 15% slower). Comments in your code would aid readability and maintainability.
{ "domain": "codereview.stackexchange", "id": 44948, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x", "url": null }
c, integer Title: C function to read only numeric values Question: I'm learning C and as exercise I'm trying to implement a custom function to parse a input from user and return successfully only if the input is a number. These are my files, how could I improve it? my_main.c #include "my_utils.h" void main() { int a; char num[10]; size_t l = sizeof(num); a = read_int(&a, num, l, message); printf("The number is %d", a); } my_utils.h #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int read_int(int *a, char *num, size_t l, const char *message) { int err; size_t length; do { if (message) printf(message); fgets(num, l, stdin); length = strlen(num); err = 0; int i; for (i = 0; i < l; i++) { if (!isdigit(num[i]) && num[i] != '\n' && num[i] != '\0' && num[i] != EOF) { if(i == 0 && num[i] == '-') //-123 is a valid input, 1-23 is not continue; printf("Only numbers allowed. Try again\n"); err = 1; if (length > 0 && num[length - 1] != '\n') { //stdin flush int c; while ((c = getchar()) != '\n' && c != EOF) ; } break; } if (num[i] == '\n' && num[i + 1] == '\0') { break; } } } while (err != 0); *a = atoi(num); if (length > 0 && num[length - 1] != '\n') { int c; while ((c = getchar()) != '\n' && c != EOF) ; } return *a; } Maybe (surely?) is overkill to handle only a int input, but I'd like to know if there are best practice or whatever a newbie should know to improve. Thanks Answer: Definition of function main The definition of the function main should start with int main( void ) instead of: void main()
{ "domain": "codereview.stackexchange", "id": 44949, "lm_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, integer", "url": null }
c, integer instead of: void main() The return type of void is illegal in ISO C, unless your platform happens to support it as an extension. However, even if your platform does support void, using it is generally not recommended, because otherwise, your code may not be portable to other platforms. See the following Stack Overflow question for further information: What should main() return in C and C++? Add include guards to header files You should generally add include guards to header files, for example #ifndef MY_UTILS_H_INCLUDED #define MY_UTILS_H_INCLUDED at the start of the file, and then #endif
{ "domain": "codereview.stackexchange", "id": 44949, "lm_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, integer", "url": null }
c, integer at the start of the file, and then #endif at the end of the file. This will ensure that the header file will only be included once per translation unit (.c source code file). Otherwise, you may get errors if the same header file is included more than once in the same translation unit. See the following question for further information: Why are #ifndef and #define used in C++ header files? On some platforms, you can simply write #pragma once at the start of the file, in order to achieve the same effect. However, this is not guaranteed to work on all platforms. See the following question for further information: #pragma once vs include guards? Functions should be defined in source files, not header files In your posted code, you are defining the function read_int in a header file. However, this is generally a bad idea, because if this header is included by more than one translation unit (.c source file), then your program will likely fail to compile/link, due to violating the one-definition rule. For this reason, functions should generally be defined in .c source files and not in header files. Header files should generally only contain function declarations, but not definitions. I therefore suggest that you move the definition of the function read_int to a file with the name my_utils.c and that you compile that file together with my_main.c. The file my_utils.h should only contain a declaration of the function read_int: int read_int(int *a, char *num, size_t l, const char *message); Don't call printf using a format string from an unknown source The line printf(message);
{ "domain": "codereview.stackexchange", "id": 44949, "lm_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, integer", "url": null }
c, integer Don't call printf using a format string from an unknown source The line printf(message); is dangerous, because message is interpreted as a pointer to the format string. This string is supplied by the caller and it is unclear whether it may contain % characters, which have a special meaning in a printf format string. For example, if the format string happens to contain %s, then the function printf will attempt to de-reference the non-existant pointer parameter, which will likely cause the program to crash. For this reason, it would be safer to write printf( "%s", message ); or fputs( message, stdout ); instead. That way, if the string happens to contain a %, this character will not have any special meaning; it will be printed like any other character. Always check the return value of fgets It is possible for the function fgets to fail, for example due to an I/O error or if the user triggers end-of-file on the terminal/console (for example by pressing CTRL-D on Linux or CTRL-Z on Windows). Therefore, you should generally always check the return value of fgets and, if an error occurred, act accordingly. If fgets returns NULL, then num is not guaranteed to point to a null-terminated string. If you call length = strlen(num); and num does not point to a null-terminated string, then your program will invoke undefined behavior (i.e. your program may crash). The parameters of the function read_int are unnecessarily cumbersome You have defined the function read_int with the following parameters and return type: int read_int(int *a, char *num, size_t l, const char *message)
{ "domain": "codereview.stackexchange", "id": 44949, "lm_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, integer", "url": null }
c, integer The function is passing back the result value both as a return value and via the pointer parameter a. In other words, the function is passing the same value back to the calling function twice, although once would be sufficient. I recommend that you only use the return value. That way, you can eliminate the parameter a. Also, there is no reason for the function read_int to use a memory buffer supplied by the caller. If the function uses its own memory buffer instead, then you can also eliminate the parameters num and l. Use strtol instead of atoi I recommend that you use the function strtol instead of atoi. This has the following advantages: The function strtol will tell you if the value is outside of the representable range of the integer data type, whereas the function atoi will invoke undefined behavior in that case. The function strtol will tell you how many characters were successfully converted, by passing an optional pointer to the first character that was not parsed. That way, it is no longer necessary for you to call isdigit on every single character in order to determine whether the input is valid. Also, this will automatically allow the digits to be prefixed with + or - and you will no longer have to handle these cases yourself. Code example Here is the definition of my function get_int_from_user, which I have been using regularly and is intended to do the same thing as your function read_int. It follows all the advice mentioned above. #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <limits.h> #include <errno.h> //This function will attempt to read one integer from the user. If //the input is invalid, it will automatically reprompt the user, //until the input is valid. int get_int_from_user( const char *prompt ) { //loop forever until user enters a valid number for (;;) { char buffer[1024], *p; long l; //prompt user for input fputs( prompt, stdout );
{ "domain": "codereview.stackexchange", "id": 44949, "lm_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, integer", "url": null }
c, integer //prompt user for input fputs( prompt, stdout ); //get one line of input from input stream if ( fgets( buffer, sizeof buffer, stdin ) == NULL ) { fprintf( stderr, "Unrecoverable input error!\n" ); exit( EXIT_FAILURE ); } //make sure that entire line was read in (i.e. that //the buffer was not too small) if ( strchr( buffer, '\n' ) == NULL && !feof( stdin ) ) { int c; printf( "Line input was too long!\n" ); //discard remainder of line do { c = getchar(); if ( c == EOF ) { fprintf( stderr, "Unrecoverable error reading from input!\n" ); exit( EXIT_FAILURE ); } } while ( c != '\n' ); continue; } //attempt to convert string to number errno = 0; l = strtol( buffer, &p, 10 ); if ( p == buffer ) { printf( "Error converting string to number!\n" ); continue; } //make sure that number is representable as an "int" if ( errno == ERANGE || l < INT_MIN || l > INT_MAX ) { printf( "Number out of range error!\n" ); continue; } //make sure that remainder of line contains only whitespace, //so that input such as "6abc" gets rejected for ( ; *p != '\0'; p++ ) { if ( !isspace( (unsigned char)*p ) ) { printf( "Unexpected input encountered!\n" ); //cannot use `continue` here, because that would go to //the next iteration of the innermost loop, but we //want to go to the next iteration of the outer loop goto continue_outer_loop; } } return l; continue_outer_loop: continue; } }
{ "domain": "codereview.stackexchange", "id": 44949, "lm_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, integer", "url": null }
c, integer return l; continue_outer_loop: continue; } } This code was copied from this answer of mine to another question. See that answer for further explanation of my code.
{ "domain": "codereview.stackexchange", "id": 44949, "lm_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, integer", "url": null }