text
stringlengths
1
2.12k
source
dict
asynchronous, concurrency, kotlin Title: Load data from database, change it asynchronously and return the new data Question: I have written this function to load data from the database, change it asynchronously and return the new data. It appears to work fine, but since I am new to Kotlin, I wanted to ask if this code is ok by industry standards. override fun update(resourceCommand: UpdateResourceCommand): List<Resource> = runBlocking { val resources = resourceCommand.resources.map { async { val resource = load(it) resource.isProtected = it.isProtected resource } }.awaitAll() return@runBlocking resources } Don't know if this matters, but I am using Kotlin with Spring-Boot. Answer: The power of coroutines in Kotlin is that they should not block a thread when used correctly. As soon as you use runBlocking, all that goes out the window. As stated in the documentation for runBlocking: Runs a new coroutine and blocks the current thread interruptibly until its completion. You haven't added the information about the load method but I do hope that's a suspend function. Otherwise using async will not have much meaning. If we check awaitAll that method says: (emphasis mine) Awaits for completion of given deferred values without blocking a thread and resumes normally with the list of values when all deferred computations are complete or resumes with the first thrown exception if any of computations complete exceptionally including cancellation. So that's fine.
{ "domain": "codereview.stackexchange", "id": 43782, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "asynchronous, concurrency, kotlin", "url": null }
asynchronous, concurrency, kotlin So that's fine. Because of the runBlocking invocation, this does not live up to industry standards regarding usage of Kotlin coroutines and, unfortunately, demonstrates a lack of understanding about coroutines. I'll be the first one to admit that I don't understand everything about coroutines (and god knows if I ever will) but this is not correct usage. The best solution would be if you could make the whole update function a suspend fun and if it could launch its own coroutine using some existing CoroutineScope. I would recommend reading through https://spring.io/guides/tutorials/spring-webflux-kotlin-rsocket/ (Disclaimer: Haven't read it fully myself as I use Ktor and not Spring Boot) and especially the part about suspending functions - except that I would recommend using fun thisIsATest() = runTest { ... } instead of runBlocking inside a test method. I would also recommend experimenting and playing around a lot with coroutines to learn them better. And read lots and lots of the documentation for methods and classes. Try to understand (at least the basics of) CoroutineScope, CoroutineContext, CoroutineDispatcher (hint: You probably want to use Dispatchers.IO for your database connection) and how they interact.
{ "domain": "codereview.stackexchange", "id": 43782, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "asynchronous, concurrency, kotlin", "url": null }
c++, programming-challenge, memory-optimization, breadth-first-search Title: LeetCode 126: Word Ladder II -- Memory limit exceeded
{ "domain": "codereview.stackexchange", "id": 43783, "lm_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++, programming-challenge, memory-optimization, breadth-first-search", "url": null }
c++, programming-challenge, memory-optimization, breadth-first-search Question: I am trying to solve LC126, and got a memory limit exceeded for the following solution. I've seen the answer here -- so I'll try to use Dijkstra as well, but I would like to understand why I get the memory limit exceeded, and to learn how I could improve my code. The main idea: BFS on paths, i.e. from start word, build the intermediate paths starting with the start word, then, extend these paths with neighbors, if not visited. Keep only paths of shortest length. vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) { vector<vector<string>> res; unordered_set<string> wordsList(wordList.begin(), wordList.end()); if (wordsList.count(endWord) == 0) { return res; } unordered_set<string> visited; queue<vector<string>> q; q.push(vector<string>({beginWord})); int min_len = wordList.size() + 1; unordered_map<string, vector<string>> neigh; for (const auto& wd: wordsList) { neigh[wd] = getNeighbors(wd, wordsList); } neigh[beginWord] = getNeighbors(beginWord, wordsList); while (! q.empty()) { vector<string> crtPath = q.front(); q.pop(); string lastNode = crtPath.back(); visited.insert(lastNode); for (const string& nn: neigh[lastNode]) { if (visited.count(nn) != 0) { continue; } vector<string> newPath(crtPath); newPath.emplace_back(nn); if (nn == endWord) { if (newPath.size() == min_len) { res.push_back(newPath); } else if (newPath.size() < min_len) { res = {newPath}; min_len = newPath.size(); } } else { if (newPath.size() <= min_len) { q.push(newPath); } } }
{ "domain": "codereview.stackexchange", "id": 43783, "lm_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++, programming-challenge, memory-optimization, breadth-first-search", "url": null }
c++, programming-challenge, memory-optimization, breadth-first-search q.push(newPath); } } } } return res; }
{ "domain": "codereview.stackexchange", "id": 43783, "lm_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++, programming-challenge, memory-optimization, breadth-first-search", "url": null }
c++, programming-challenge, memory-optimization, breadth-first-search vector<string> getNeighbors(const string& node, const unordered_set<string>&nodes) { vector<string> result; string word = node; for (int ii = 0; ii < node.length(); ++ii) { char old_char = word[ii]; for (char ch = 'a'; ch <= 'z'; ++ch) { if (ch == old_char) { continue; } word[ii] = ch; if (nodes.count(word) != 0) { result.emplace_back(word); } } word[ii] = old_char; } return result; } Answer: Enable compiler warnings and fix all of them My compiler warns about comparisons between integers of different sizes and signedness. This is because you are using int for loop indices and min_len, but .length() and .size() return a std::size_t. Make sure you also use std::size_t there. Also, std::size_t is usually the right type to use for everything that is a size, count or index. Alternatively, use range-for loops and auto to avoid having to specify a type for such things to begin with. In getNeighbors(), you could write: for (auto& cur_char: node) { auto old_char = cur_char; ... cur_char = old_char; } And in findLadders(): auto min_len = wordList.size() + 1;
{ "domain": "codereview.stackexchange", "id": 43783, "lm_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++, programming-challenge, memory-optimization, breadth-first-search", "url": null }
c++, programming-challenge, memory-optimization, breadth-first-search And in findLadders(): auto min_len = wordList.size() + 1; Memory usage You get memory limit exceeded because you are using more memory than necessary. You should then wonder about whether you are using the right algorithm, the right datastructures for that algorithm, and whether you are making unnecessary (temporary) copies of things. Let's begin with the latter: you are given wordList, but you want these to be in a std::unordered_set for quick lookups. That is understandable, but now you are making a copy of all the words. In principle, you could create a set that just stores references to the strings inside wordList, so you avoid wasting memory on copies, but unfortunately that's not trivial to do. Let's forget that for now. Another issue is that you are creating multiple data structures that are all indexed on words: there's wordsList, visited and neigh. Apart from now duplicating every word at least three times, you also have the bookkeeping overhead of three containers. I would create a single std::unordered_map, and create struct yourself to hold all the data related to a single word: struct WordInfo { bool visited; std::vector<std::string> neighbors; }; std::unordered_map<std::string, WordInfo> words; for (auto& word: wordList) words[word] = {}; You have several vectors of strings in your code. Those could be changes to be vectors of references to strings. Either use std::reference_wrapper to store references in containers, like so: std::vector<std::reference_wrapper<std::string>> result; Or you could consider storing iterators into words: std::vector<decltype(words)::iterator> result; Or indices into the original wordList: std::vector<std::size_t> result;
{ "domain": "codereview.stackexchange", "id": 43783, "lm_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++, programming-challenge, memory-optimization, breadth-first-search", "url": null }
c++, programming-challenge, memory-optimization, breadth-first-search Or indices into the original wordList: std::vector<std::size_t> result; Another issue is that before you are starting with the BFS algorithm, you are calculating the set of neighbors for every word in wordList, even if you would never reach those words during the breadth-first-search! So you need up to \$O(W^2 L)\$ of storage, where \$W\$ is the number of words and \$L\$ is the length of the words. But this is quite unnecessary: you only need to know the list of neighbors of a word when you visit that word. Then there's the BFS algorithm itself. Why do you need to "keep only paths of shortest length"? If it's truly BFS, then the moment you reach the endWord, you have a path with the shortest length, and you haven't seen any paths with a longer length yet, otherwise your algorithm is not breadth-first. You also don't need to store all paths; if you just store the predecessor of every visited node, then the moment you find an endWord you can just walk back along the predecessors until you reach startWord, and that's then one of the desired paths (in reverse). Once you have found one endWord, just finish the queue without ever pushing new entries to it. Note that Dijkstra's algorithm on a graph with only edges of the same weight is equivalent to BFS. Memory usage vs. performance Sometimes there are trade-offs to be made between fast but memory-hungry algorithms, and slow but memory-efficient algorithms. Just to show you how low you can go with memory usage, consider that you can just permute the vector wordList, and for each permutation check if there is a valid path from beginWord to endWord in it, and check its length: std::size_t pathLength(const string& beginWord, const string& endWord, const vector<string>& wordList) { /* Return length of path if there is a valid path at the start of wordList, otherwise return wordList.size(). */ ... }
{ "domain": "codereview.stackexchange", "id": 43783, "lm_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++, programming-challenge, memory-optimization, breadth-first-search", "url": null }
c++, programming-challenge, memory-optimization, breadth-first-search auto findLadders(std::string beginWord, std::string endWord, std::vector<std::string>& wordList) { std::vector<std::vector<std::string>> result; auto minSize = wordList.size(); std::sort(wordList.begin(), wordList.end()); // Find the length of the shortest paths do { minSize = std::min(minSize, pathLength(beginWord, endWord, wordList)); } while (std::next_permutation(s.begin(), s.end()) // Gather all the shortest paths do { if (pathLength(beginWord, endWord, wordList) == minSize) { result.emplace_back(wordList.begin(), wordList.begin() + minSize); } } while (std::next_permutation(s.begin(), s.end()) return result; } Apart from the input parameters and return value, the above code only needs a few tiny variables. Unfortunately, it runs very slow.
{ "domain": "codereview.stackexchange", "id": 43783, "lm_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++, programming-challenge, memory-optimization, breadth-first-search", "url": null }
python, performance, numpy, pandas, numba Title: Intercolumn statistics between columns in a dataframe Question: I have a df and need to count how many adjacent columns have the same sign as other columns based on the sign of the first column, and multiply by the sign of the first column. What I need to speed up is the calc_df function, which runs like this on my computer: %timeit calc_df(df) 6.38 s ± 170 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) The output of my code is: a_0 a_1 a_2 a_3 a_4 a_5 a_6 a_7 a_8 a_9 0 0.097627 0.430379 0.205527 0.089766 -0.152690 0.291788 -0.124826 0.783546 0.927326 -0.233117 1 0.583450 0.057790 0.136089 0.851193 -0.857928 -0.825741 -0.959563 0.665240 0.556314 0.740024 2 0.957237 0.598317 -0.077041 0.561058 -0.763451 0.279842 -0.713293 0.889338 0.043697 -0.170676 3 -0.470889 0.548467 -0.087699 0.136868 -0.962420 0.235271 0.224191 0.233868 0.887496 0.363641 4 -0.280984 -0.125936 0.395262 -0.879549 0.333533 0.341276 -0.579235 -0.742147 -0.369143 -0.272578 0 4.0 1 4.0 2 2.0 3 -1.0 4 -2.0 My code is as follows, where the generate_data function generates demo data, which is consistent with my actual data volume. import numpy as np import pandas as pd from numba import njit np.random.seed(0) pd.set_option('display.max_columns', None) pd.set_option('expand_frame_repr', False) # This function generates demo data. def generate_data() -> pd.DataFrame: col = [f'a_{x}' for x in range(10)] df = pd.DataFrame(data=np.random.uniform(-1, 1, [280000, 10]), columns=col) return df @njit def calc_numba(s: np.array) -> float: a = s[0] b = 1 for sign in s[1:]: if sign == a: b += 1 else: break b *= a return b def calc_series(s: pd.Series) -> float: return calc_numba(s.to_numpy())
{ "domain": "codereview.stackexchange", "id": 43784, "lm_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, numpy, pandas, numba", "url": null }
python, performance, numpy, pandas, numba def calc_series(s: pd.Series) -> float: return calc_numba(s.to_numpy()) def calc_df(df: pd.DataFrame) -> pd.DataFrame: df1 = np.sign(df) df['count'] = df1.apply(calc_series, axis=1) return df def main() -> None: df = generate_data() print(df.head(5)) df = calc_df(df) print(df['count'].head(5)) return if __name__ == '__main__': main() Answer: Just avoiding switching between numpy array and pandas dataframe so much can grant you an easy x4 speedup: def calc_df(df: pd.DataFrame) -> pd.DataFrame: df1 = np.sign(df) df['count'] = df1.apply(calc_series, axis=1) return df %%timeit df = generate_data() calc_df(df) 1.6 s ± 75.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) With less casting from pandas to numpy: def optimized_calc_df(df: pd.DataFrame) -> pd.DataFrame: array = np.sign(df.to_numpy()) df['count'] = np.apply_along_axis(calc_numba, 1, array) return df %%timeit odf = generate_data() optimized_calc_df(odf) 415 ms ± 16.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) Using your solution and with numpy: import numpy as np import pandas as pd from numba import njit np.random.seed(0) pd.set_option('display.max_columns', None) pd.set_option('expand_frame_repr', False) # This function generates demo data. def generate_data() -> pd.DataFrame: col = [f'a_{x}' for x in range(10)] np.random.seed(0) df = pd.DataFrame(data=np.random.uniform(-1, 1, [280000, 10]), columns=col) return df # This function generates demo data. def generate_data_array() -> np.array: np.random.seed(0) return np.random.uniform(-1, 1, [280000, 10]) %%timeit df = generate_data() df1 = np.sign(df) m = df1.eq(df1.iloc[:,0], axis=0).cummin(1) out_df = m.sum(1)*df1.iloc[:,0] 76.6 ms ± 2.6 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
{ "domain": "codereview.stackexchange", "id": 43784, "lm_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, numpy, pandas, numba", "url": null }
python, performance, numpy, pandas, numba 76.6 ms ± 2.6 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) %%timeit array = generate_data_array() array2 = np.sign(array) array3 = np.minimum.accumulate(np.equal(array2, np.expand_dims(array2[:,0], axis=1)), 1) out_array = array3.sum(axis=1) * array2[:,0] 44.3 ms ± 1.35 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
{ "domain": "codereview.stackexchange", "id": 43784, "lm_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, numpy, pandas, numba", "url": null }
c++, algorithm, primes, sieve-of-eratosthenes Title: Improved Sieve of Eratosthenes Question: How can I get to a perfect coding for this algorithm? I made the mathematical theorem, which is a development of the Sieve of Eratosthenes algorithm. I might use some help in coding. You can find the description of the code at my paper: Development of Sieve of Eratosthenes and Sieve of Sundaram's proof For more understanding you can check this paper: SEQUENCE ELIMINATION FUNCTION AND THE FORMULAS OF PRIME NUMBERS For the next development see Next level Improved Sieve of Eratosthenes #include <iostream> #include <math.h> #include <cstdlib> using namespace std; int D2SOE(int n1_m) { int n1 = 0, g = 0, z = 0, p = 0,f1=0,f3=0; cout << "\n2 3 "; bool* array = new bool[n1_m]; // Initialising the D2SOE array with false values for (int i = 0; i < n1_m; i++) array[i] = false; // The main elimination theorem for (n1=1;n1<=ceil((sqrt(2*floor((3*n1_m+1)/2.0)+1)-2)/3.0);n1++) { if (array[n1] != 0) continue; z = ((3 * n1 + 1) / 2.0); p = ((2 * z) + 1); f1 = (ceil(((7*p)-2) / 3.0) - ceil((p - 2) / 3.0)); f3 = (ceil(((7*p)-2) / 3.0) - ceil(((5 * p) - 2) / 3.0)); for (g = ceil(((4*((z*z) + z)) - 1) / 3.0); g < n1_m;g+=f1) { array[g] = true; } if ((p +1) % 3 == 0) { for (g = ceil(((4*((z*z) + z)) - 1) / 3.0) + f3; g < n1_m;g+=f1) { array[g] = true; } } else { for (g = ceil(((4*((z*z) + z)) - 1) / 3.0) - f3; g<n1_m;g+=f1) { array[g] = true; }}} // printing for loop for (int n1 = 1; n1 < n1_m; n1++) if (!array[n1]) { z = (((3 * n1) + 1) / 2.0); cout << (2 * z) + 1 << " "; } return 0; } // driver program to test above int main() { int n1_m, N = 0; cout << "\n Enter limit : "; cin >> N; n1_m = ceil((N - 2) / 3.0); D2SOE(n1_m); return 0; }
{ "domain": "codereview.stackexchange", "id": 43785, "lm_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++, algorithm, primes, sieve-of-eratosthenes", "url": null }
c++, algorithm, primes, sieve-of-eratosthenes Answer: Separation of concerns We dont't sieve primes for the sake of sieving primes. We want primes because we want to do something with them, not just print. Let D2SOE return the array it computed, and int main() int n1_m, N = 0; cout << "\n Enter limit : "; cin >> N; n1_m = ceil((N - 2) / 3.0); bool array = D2SOE(n1_m); print_primes(array, n1_m); return 0; } Overall impression: Unreadable. Please, don't }}}. Indent your code properly. ceil(((4*((z*z) + z)) - 1) / 3.0) seems very important, as it is repeated 3 times. Figure out a good name for it, and compute it once. f1 and f3 deserve better names too. After sieving, I'd expect true for primes. Correctness Didn't check it. However, A floating point math in an elementary number-theoretical problem is totally out of place. It may bite you hard when n1_m1 grows large enough. Comparing a boolean array[n1] to 0, while technically correct, gives a yucky taste. c++ I don't see why to #include <cstdlib>. using namespace std; is always wrong. Don't new. Use std::vector.
{ "domain": "codereview.stackexchange", "id": 43785, "lm_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++, algorithm, primes, sieve-of-eratosthenes", "url": null }
php, sql, mysql, mysqli Title: Queries to get products selected in multiple stores Question: Project description I'm making a website listing products. The listing goes as following (See here): Product name Shop name Price in that shop If the product appears multiple times in the table for the same user (Which means he/she selected it in multiple stores. Merge them and just show multiple shop names) Examples: Product selected in 1 Shop: Product selected in 2 Shops: Product selected in 3 Shops: and so on PS: the names are always the same in the screenshots but they could be completely different ones Database Tables: Table user_interests: user_hash | shop_id | product_id --------------------+------------+--------------- a0a080f42e6f13b3... | 626 | 547261 a0a080f42e6f13b3... | 554 | 283678 a0a080f42e6f13b3... | 554 | 8680 a0a080f42e6f13b3... | 732 | 283678 0aa1883c6411f787... | 865 | 283678 Table shop_id: shop_id | shop_name -----------+--------------- 604 | Halle 626 | Vilvoorde 605 | Heverlee Table product_price: shop_id | product_id | unit_price | ... ---------+------------+------------------- 626 | 547261 | 3,23 | ... 554 | 283678 | 4,59 | ... 732 | 283678 | 3,50 | ... 626 | 732 | 4,32 | ... 626 | 865 | 3,64 | ... Table product_extra_info: which contains extra info's Encountered Issue I am able to get a result (the one you're able to see on the screenshots) and it is displayed like I want it to be. Only problem is the code is really messy and filled with (I think) unnecessary sql requests. My comments are below the code // Merge them and count how many $checkIfExistsMultipleSql = "SELECT `product_id`, COUNT(*) FROM `user_interests` WHERE `user_hash`='$user_hash' GROUP BY `product_id` HAVING COUNT(*) >= 1; "; $checkIfExistsMultipleResult = $mysqli->query($checkIfExistsMultipleSql);
{ "domain": "codereview.stackexchange", "id": 43786, "lm_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, sql, mysql, mysqli", "url": null }
php, sql, mysql, mysqli // If not empty continue else tell user if ($checkIfExistsMultipleResult) { // Make a website element for each product while($checkrow = $checkIfExistsMultipleResult ->fetch_assoc()) { $product = $checkrow['product_id']; -------------------[1]------------------- $multipleShopsSql = "SELECT `shop_id` FROM `user_interests` WHERE `product_id`='$product' AND `user_hash`='$user_hash'"; $multipleShopsResult = $mysqli->query($multipleShopsSql); -------------------[2]------------------- $productInfoSql = "SELECT `name`, `picture`, `mesurement`, `content` FROM `products_extra_info` WHERE `product_id`='$product'"; $productInfoResult = $mysqli->query($productInfoSql); $productInfo = $productInfoResult->fetch_assoc(); I really do not like that part, I would like to "include" this one in the top one. (So what I'm trying to get is one select command which gives me a result showing this [product_id] is requested in [shop_id_1] and [shop_id_2] ...) For this one I would like to know what's better, as you can see I'm running this one, once for each product card. Is it good like that or should I run one big request and extract the data I need ? Answer: To elaborate on the Pslice's suggestion. Definitely, it must be just a single query with joins. Based on a slightly more sensible table structure, it could be like select p.id, p.name product, pp.price, s.name shop from user_interests ui join products p on p.id=ui.product_id join product_prices pp on pp.product_id=ui.product_id join shops s on s.id=pp.shop_id where ui.user_id=1 order by p.id, price And then, using PDO, we can already group the returned data by the product into a 3-dimensional array $data = $pdo->query($sql)->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC);
{ "domain": "codereview.stackexchange", "id": 43786, "lm_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, sql, mysql, mysqli", "url": null }
php, sql, mysql, mysqli that can be iterated over like this: foreach ($data as $product) { echo $product[0]['product'],"\n"; foreach ($product as $row) { echo "\t$row[price] $row[shop]\n"; } } See it in action
{ "domain": "codereview.stackexchange", "id": 43786, "lm_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, sql, mysql, mysqli", "url": null }
array, swift, ios Title: Sum of natural numbers below threshold Question: I have this code: func solution(_ num: Int) -> Int { let arrayOfTen = Array(0...num) var setOfmultiples = Set<Int>() if num <= 0 { return 0 } var sum = 0 for element in 0..<num { if element % 3 == 0 || element % 5 == 0 { setOfmultiples.insert(element) sum = setOfmultiples.reduce(0, +) } } return sum } Some tests from the website I got this exercise: import XCTest class SolutionTest: XCTestCase { static var allTests = [ ("Test Solution", testSolution), ] func testSolution() { XCTAssertEqual(solution(10), 23) XCTAssertEqual(solution(20), 78) XCTAssertEqual(solution(200), 9168) } } XCTMain([ testCase(SolutionTest.allTests) ]) from this exercise: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number passed in. Additionally, if the number is negative, return 0 (for languages that do have them). Note: If the number is a multiple of both 3 and 5, only count it once. How do I refactor it to make it more swifty? I am not that good at using functional programming so I want to understand this topic better. It seems to be working fine now. Thanks. Answer: Improving on your approach Split up your tests So they pass/fail independently: import XCTest import SumOfMultiples class SumOfMultiplesTests: XCTestCase { static var allTests = [ ("testInput10", testInput10), ("testInput20", testInput20), ("testInput200", testInput200), ] func testInput10() { XCTAssertEqual(solution(10), 23) } func testInput20() { XCTAssertEqual(solution(20), 78) } func testInput200() { XCTAssertEqual(solution(200), 9168) } } XCTMain([ testCase(SolutionTest.allTests) ])
{ "domain": "codereview.stackexchange", "id": 43787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "array, swift, ios", "url": null }
array, swift, ios (And make solution a public func, so you don't need @testable on import SumOfMultiples) arrayOfTen is unused Delete it. Also, Xcode gives warnings for a reason. Don't ignore them. Redundant sum calculation If you just add a log on every calculation of sum, you'll see it's calculated 93 times. You only return the last value of the it, so that's 92 calculations too many: Sum of [0] = 0 Sum of [0, 3] = 3 Sum of [0, 3, 5] = 8 Sum of [0, 3, 5, 6] = 14 Sum of [0, 3, 5, 6, 9] = 23 Sum of [0, 3, 5, 6, 9, 10] = 33 Sum of [0, 3, 5, 6, 9, 10, 12] = 45 Sum of [0, 3, 5, 6, 9, 10, 12, 15] = 60 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18] = 78 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20] = 98 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21] = 119 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24] = 143 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25] = 168 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27] = 195 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30] = 225 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33] = 258 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35] = 293 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36] = 329 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39] = 368 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40] = 408 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42] = 450 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45] = 495 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48] = 543 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50] = 593 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51] = 644
{ "domain": "codereview.stackexchange", "id": 43787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "array, swift, ios", "url": null }
array, swift, ios Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54] = 698 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55] = 753 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57] = 810 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60] = 870 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63] = 933 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65] = 998 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66] = 1064 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69] = 1133 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70] = 1203 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72] = 1275 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75] = 1350 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78] = 1428 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80] = 1508 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81] = 1589
{ "domain": "codereview.stackexchange", "id": 43787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "array, swift, ios", "url": null }
array, swift, ios Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84] = 1673 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85] = 1758 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87] = 1845 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90] = 1935 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93] = 2028 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95] = 2123 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96] = 2219 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99] = 2318 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100] = 2418 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102] = 2520
{ "domain": "codereview.stackexchange", "id": 43787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "array, swift, ios", "url": null }
array, swift, ios Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105] = 2625 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105, 108] = 2733 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105, 108, 110] = 2843 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105, 108, 110, 111] = 2954 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105, 108, 110, 111, 114] = 3068 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105, 108, 110, 111, 114, 115] = 3183 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105, 108, 110, 111, 114, 115, 117] = 3300 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105, 108, 110, 111, 114, 115, 117, 120] = 3420
{ "domain": "codereview.stackexchange", "id": 43787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "array, swift, ios", "url": null }
array, swift, ios Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105, 108, 110, 111, 114, 115, 117, 120, 123] = 3543 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105, 108, 110, 111, 114, 115, 117, 120, 123, 125] = 3668 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105, 108, 110, 111, 114, 115, 117, 120, 123, 125, 126] = 3794 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105, 108, 110, 111, 114, 115, 117, 120, 123, 125, 126, 129] = 3923 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105, 108, 110, 111, 114, 115, 117, 120, 123, 125, 126, 129, 130] = 4053 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105, 108, 110, 111, 114, 115, 117, 120, 123, 125, 126, 129, 130, 132] = 4185 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105, 108, 110, 111, 114, 115, 117, 120, 123, 125, 126, 129, 130, 132, 135] = 4320
{ "domain": "codereview.stackexchange", "id": 43787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "array, swift, ios", "url": null }
array, swift, ios Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105, 108, 110, 111, 114, 115, 117, 120, 123, 125, 126, 129, 130, 132, 135, 138] = 4458 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105, 108, 110, 111, 114, 115, 117, 120, 123, 125, 126, 129, 130, 132, 135, 138, 140] = 4598 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105, 108, 110, 111, 114, 115, 117, 120, 123, 125, 126, 129, 130, 132, 135, 138, 140, 141] = 4739 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105, 108, 110, 111, 114, 115, 117, 120, 123, 125, 126, 129, 130, 132, 135, 138, 140, 141, 144] = 4883 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105, 108, 110, 111, 114, 115, 117, 120, 123, 125, 126, 129, 130, 132, 135, 138, 140, 141, 144, 145] = 5028 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105, 108, 110, 111, 114, 115, 117, 120, 123, 125, 126, 129, 130, 132, 135, 138, 140, 141, 144, 145, 147] = 5175
{ "domain": "codereview.stackexchange", "id": 43787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "array, swift, ios", "url": null }
array, swift, ios Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105, 108, 110, 111, 114, 115, 117, 120, 123, 125, 126, 129, 130, 132, 135, 138, 140, 141, 144, 145, 147, 150] = 5325 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105, 108, 110, 111, 114, 115, 117, 120, 123, 125, 126, 129, 130, 132, 135, 138, 140, 141, 144, 145, 147, 150, 153] = 5478 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105, 108, 110, 111, 114, 115, 117, 120, 123, 125, 126, 129, 130, 132, 135, 138, 140, 141, 144, 145, 147, 150, 153, 155] = 5633 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105, 108, 110, 111, 114, 115, 117, 120, 123, 125, 126, 129, 130, 132, 135, 138, 140, 141, 144, 145, 147, 150, 153, 155, 156] = 5789 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105, 108, 110, 111, 114, 115, 117, 120, 123, 125, 126, 129, 130, 132, 135, 138, 140, 141, 144, 145, 147, 150, 153, 155, 156, 159] = 5948 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105, 108, 110, 111, 114, 115, 117, 120, 123, 125, 126, 129, 130, 132, 135, 138, 140, 141, 144, 145, 147, 150, 153, 155, 156, 159, 160] = 6108
{ "domain": "codereview.stackexchange", "id": 43787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "array, swift, ios", "url": null }
array, swift, ios Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105, 108, 110, 111, 114, 115, 117, 120, 123, 125, 126, 129, 130, 132, 135, 138, 140, 141, 144, 145, 147, 150, 153, 155, 156, 159, 160, 162] = 6270 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105, 108, 110, 111, 114, 115, 117, 120, 123, 125, 126, 129, 130, 132, 135, 138, 140, 141, 144, 145, 147, 150, 153, 155, 156, 159, 160, 162, 165] = 6435 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105, 108, 110, 111, 114, 115, 117, 120, 123, 125, 126, 129, 130, 132, 135, 138, 140, 141, 144, 145, 147, 150, 153, 155, 156, 159, 160, 162, 165, 168] = 6603 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105, 108, 110, 111, 114, 115, 117, 120, 123, 125, 126, 129, 130, 132, 135, 138, 140, 141, 144, 145, 147, 150, 153, 155, 156, 159, 160, 162, 165, 168, 170] = 6773 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105, 108, 110, 111, 114, 115, 117, 120, 123, 125, 126, 129, 130, 132, 135, 138, 140, 141, 144, 145, 147, 150, 153, 155, 156, 159, 160, 162, 165, 168, 170, 171] = 6944
{ "domain": "codereview.stackexchange", "id": 43787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "array, swift, ios", "url": null }
array, swift, ios Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105, 108, 110, 111, 114, 115, 117, 120, 123, 125, 126, 129, 130, 132, 135, 138, 140, 141, 144, 145, 147, 150, 153, 155, 156, 159, 160, 162, 165, 168, 170, 171, 174] = 7118 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105, 108, 110, 111, 114, 115, 117, 120, 123, 125, 126, 129, 130, 132, 135, 138, 140, 141, 144, 145, 147, 150, 153, 155, 156, 159, 160, 162, 165, 168, 170, 171, 174, 175] = 7293 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105, 108, 110, 111, 114, 115, 117, 120, 123, 125, 126, 129, 130, 132, 135, 138, 140, 141, 144, 145, 147, 150, 153, 155, 156, 159, 160, 162, 165, 168, 170, 171, 174, 175, 177] = 7470 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105, 108, 110, 111, 114, 115, 117, 120, 123, 125, 126, 129, 130, 132, 135, 138, 140, 141, 144, 145, 147, 150, 153, 155, 156, 159, 160, 162, 165, 168, 170, 171, 174, 175, 177, 180] = 7650 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105, 108, 110, 111, 114, 115, 117, 120, 123, 125, 126, 129, 130, 132, 135, 138, 140, 141, 144, 145, 147, 150, 153, 155, 156, 159, 160, 162, 165, 168, 170, 171, 174, 175, 177, 180, 183] = 7833
{ "domain": "codereview.stackexchange", "id": 43787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "array, swift, ios", "url": null }
array, swift, ios Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105, 108, 110, 111, 114, 115, 117, 120, 123, 125, 126, 129, 130, 132, 135, 138, 140, 141, 144, 145, 147, 150, 153, 155, 156, 159, 160, 162, 165, 168, 170, 171, 174, 175, 177, 180, 183, 185] = 8018 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105, 108, 110, 111, 114, 115, 117, 120, 123, 125, 126, 129, 130, 132, 135, 138, 140, 141, 144, 145, 147, 150, 153, 155, 156, 159, 160, 162, 165, 168, 170, 171, 174, 175, 177, 180, 183, 185, 186] = 8204 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105, 108, 110, 111, 114, 115, 117, 120, 123, 125, 126, 129, 130, 132, 135, 138, 140, 141, 144, 145, 147, 150, 153, 155, 156, 159, 160, 162, 165, 168, 170, 171, 174, 175, 177, 180, 183, 185, 186, 189] = 8393 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105, 108, 110, 111, 114, 115, 117, 120, 123, 125, 126, 129, 130, 132, 135, 138, 140, 141, 144, 145, 147, 150, 153, 155, 156, 159, 160, 162, 165, 168, 170, 171, 174, 175, 177, 180, 183, 185, 186, 189, 190] = 8583
{ "domain": "codereview.stackexchange", "id": 43787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "array, swift, ios", "url": null }
array, swift, ios Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105, 108, 110, 111, 114, 115, 117, 120, 123, 125, 126, 129, 130, 132, 135, 138, 140, 141, 144, 145, 147, 150, 153, 155, 156, 159, 160, 162, 165, 168, 170, 171, 174, 175, 177, 180, 183, 185, 186, 189, 190, 192] = 8775 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105, 108, 110, 111, 114, 115, 117, 120, 123, 125, 126, 129, 130, 132, 135, 138, 140, 141, 144, 145, 147, 150, 153, 155, 156, 159, 160, 162, 165, 168, 170, 171, 174, 175, 177, 180, 183, 185, 186, 189, 190, 192, 195] = 8970 Sum of [0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99, 100, 102, 105, 108, 110, 111, 114, 115, 117, 120, 123, 125, 126, 129, 130, 132, 135, 138, 140, 141, 144, 145, 147, 150, 153, 155, 156, 159, 160, 162, 165, 168, 170, 171, 174, 175, 177, 180, 183, 185, 186, 189, 190, 192, 195, 198] = 9168
{ "domain": "codereview.stackexchange", "id": 43787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "array, swift, ios", "url": null }
array, swift, ios This is trivial to fix, just move the calculation after the loop: public func solution(_ num: Int) -> Int { var setOfmultiples = Set<Int>() if num <= 0 { return 0 } for element in 0..<num { if element % 3 == 0 || element % 5 == 0 { setOfmultiples.insert(element) } } var sum = 0 sum = setOfmultiples.reduce(0, +) return sum } At that point, you can remove the needless initial value (0) and just inline it to let sum = setOfmultiples.reduce(0, +). Then sum becomes a bit superfluous, so you can just: return setOfmultiples.reduce(0, +) sum alternative approach Alternatively, you could just use sum += element in your if statement. Rather than regenerating the sum from all setOfmultiples, you'll just build it up using the value from the previous iteration, and simply adding the new value to it. At that point, you'll notice that setOfmultiples is actually never used. You were never really interested in the set, you only really cared about their eventual sum. Replace loop with filter Now that the loop only has one effect (conditionally appending to a set), we can just replace that with a filter. Since we're no longer building up setOfMultiples through mutation, we can not make this a let constant: public func solution(_ num: Int) -> Int { if num <= 0 { return 0 } let setOfmultiples = (0..<num).filter { $0 % 3 == 0 || $0 % 5 == 0 } return setOfmultiples.reduce(0, +) }
{ "domain": "codereview.stackexchange", "id": 43787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "array, swift, ios", "url": null }
array, swift, ios This happens to build up an Array<Int> instead of the previous Set<Int>. I think this is acceptable, because the de-duplication benefit of sets was never even being used Use isMultiple(of:) As a more readable alternative to the x % 3 == 0 idiom. Seems trivial, but you'd be surprised just how many people get mixed up and write x % 3 != 1 (which is wrong for negative numbers). Just search for cs.github.com for /% \d+ != 1[^\d]/ and you'll see a list of bug after buger. public func solution(_ num: Int) -> Int { if num <= 0 { return 0 } let setOfmultiples = (0..<num).filter { $0.isMultiple(of: 3) || $0.isMultiple(of: 5) } return setOfmultiples.reduce(0, +) } Inline setOfmultiples At this point, it's not doing much: public func solution(_ num: Int) -> Int { if num <= 0 { return 0 } return (0..<num) .filter { $0.isMultiple(of: 3) || $0.isMultiple(of: 5) } .reduce(0, +) } Make it lazy We never actually need the full array that's the result of that call to filter. All we're really after is the sum. We can use a lazy sequence to just yield the elements as they're needed, and reducing them into the final sum without needing to store them in memory: public func solution(_ num: Int) -> Int { if num <= 0 { return 0 } return (0..<num) .lazy .filter { $0.isMultiple(of: 3) || $0.isMultiple(of: 5) } .reduce(0, +) }
{ "domain": "codereview.stackexchange", "id": 43787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "array, swift, ios", "url": null }
array, swift, ios This reduces the space complexity of this algorithm from O(num) (storing an array with some roughly-constant proportion of all numbers in 0..<num) to just O(1) (the constant space it takes for the stack frame, lazy data structures, reduce accumulator, etc.). Importantly, because it's now O(1), this algorithm will not take more memory when given a larger input num. Remarks on this approach It's testing every single number in the range 0..<num, which could be wasteful if the factors we were interested (3 and 5) were large. Suppose they were 9,999,999 and 9,999,998 instead. Only 1 in 10 million numbers would ever be a multiple of them.
{ "domain": "codereview.stackexchange", "id": 43787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "array, swift, ios", "url": null }
python Title: Extract data from formatted text file Question: I am extracting data frome a given text file into a python dictionary for further processing Input: ---------------------------- SECTION-A ---------------------------- Parameter1 : Text 1 Parameter2 : Text 2 Parameter3 : Text 3 Parameter4 : Text 4 Parameter5 : Text 5 Parameter6 : Text 6 Parameter7 : Text 7 https://www.google.com ---------------------------- SECTION-B ---------------------------- Parameter8 : Text 8 Parameter9 : Text 9 ---------------------------- SECTION-C ---------------------------- Item C1 Item C2 Item C3 Item C4 ---------------------------- SECTION-D ---------------------------- Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Gravida cum sociis natoque penatibus et magnis dis parturient montes. Metus dictum at tempor commodo ullamcorper a lacus vestibulum sed. ---------------------------- END ---------------------------- The number of elements in section C and D may vary. I process the data section by section so that i can easily add parameters if there is an extension to the layout. Code: import re from pprint import pprint def parser(lines): SECTIONS = [ "SECTION-A", "SECTION-B", "SECTION-C", "SECTION-D", "END", ] parameter = { "Parameter1": "", "Parameter2": "", "Parameter3": "", "Parameter4": "", "Parameter5": "", "Parameter6": "", "Parameter7": "", "Parameter8": "", "Parameter9": "", } items_c = [] text_d = [] lines = [l.strip() for l in lines] def find_section(line): for s in SECTIONS: if line.find(s) > 0: return s return None
{ "domain": "codereview.stackexchange", "id": 43788, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python def assign_parameter(line): for p in parameter: if line.startswith(p): parameter[p] = line.split(":")[1] act_section = "" for line in lines: line = re.sub(" +", " ", line) # Remove excess spaces # Keep track of actual section if (s := find_section(line)) is not None: act_section = s # Process lines according to section if act_section == SECTIONS[0] or act_section == SECTIONS[1]: assign_parameter(line) if line.startswith("https://"): url = line elif act_section == SECTIONS[2]: if len(line) > 1 and not line.startswith("--"): items_c.append(line) elif act_section == SECTIONS[3]: if len(line) > 1 and not line.startswith("--"): text_d.append(line) # Append data in dictionary parameter.update({"URL": url}) parameter.update({"Items C": items_c}) parameter.update({"Description D": " ".join(text_d)}) return parameter if __name__ == "__main__": with open("test.txt", "r", encoding="utf8") as f: lines = f.readlines() pprint(parser(lines)) Output: {'Description D': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, ' 'sed do eiusmod tempor incididunt ut labore et dolore magna ' 'aliqua. Gravida cum sociis natoque penatibus et magnis dis ' 'parturient montes. Metus dictum at tempor commodo ' 'ullamcorper a lacus vestibulum sed.', 'Items C': ['Item C1', 'Item C2', 'Item C3', 'Item C4'], 'Parameter1': ' Text 1', 'Parameter2': ' Text 2', 'Parameter3': ' Text 3', 'Parameter4': ' Text 4', 'Parameter5': ' Text 5', 'Parameter6': ' Text 6', 'Parameter7': ' Text 7', 'Parameter8': ' Text 8', 'Parameter9': ' Text 9', 'URL': 'https://www.google.com'} My code is working but what could be improved or optimized?
{ "domain": "codereview.stackexchange", "id": 43788, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python My code is working but what could be improved or optimized? Answer: Dictionary updates parameter.update({"URL": url}) is a very verbose way of writing parameter["URL"] = url. Ditto for "Items C" and "Description D" fields. Unbounded split parameter[p] = line.split(":")[1] ignores the possibility of the multiple colons in the key-value pair. If you ever have a parameter line which reads: url : http://google.com/ Then you'll end up assigning http to the url key, not the remainder of the line. Limit the expected number of splits. parameter[p] = line.split(":", 1)[1] Accidental key-value updates for p in parameter: if line.startswith(p): parameter[p] = line.split(":")[1] If you have "parameter1" and "parameter10", both values will be updated when a parameter line with the longer key is encountered, like parameter10 : value. Better would be: def assign_parameters(line): if ':' in line: name, value = line.split(":", 1) # Maximum 1 split name = name.rstrip() # Remove trailing whitespace if name in parameters: parameter[name] = value #else: # LOG.warning("Unknown parameter %r", name) This uses the entire name when checking if the parameter is a known. It also eliminates the time wasted looping over every parameter name. Since you're already including the re module, why not ... def assign_parameter(line): m = re.match(r"(?P<name>[^ :]+)\s*:(?P<value>.*)", line) if m: name = m['name'] if name in parameters: parameters[name] = m['value'] #else: # LOG.warning("Unknown parameter %r", name)
{ "domain": "codereview.stackexchange", "id": 43788, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python Section collisions If a new section "SECTION-A1" appears in your input file, find_section(line) may unexpectedly return "SECTION-A"! Unknown sections If the input format changed, adding a new section after SECTION-C, ... ... ---------------------------- SECTION-C ---------------------------- Item C1 Item C2 Item C3 Item C4 ---------------------------- SECTION-NEW ------------------------------ Not a C item Another not a C item ... ... the additional lines will continue to be added to items_c! Based on if len(line) > 1 and not line.startswith("--"):, it seems clear that sections are expected to start with two or more hyphens. You should explicitly detect for section breaks, not just the start of any known section. if line.startswith("--") and line.endswith("--"): act_section = line.strip("- ") #if act_section not in SECTIONS: # LOG.warning("Unknown section %r", act_section) elif act_section == SECTION[0] or or act_section == SECTIONS[1]: ... elif act_section == SECTIONS[2]: if len(line) > 1: items_c.append(line) elif act_section == SECTIONS[3]: if len(line) > 1: text_d.append(line)
{ "domain": "codereview.stackexchange", "id": 43788, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python Notice that since --... SECTION-NAME ...-- lines are parsed separately, you no longer need to guard against lines starting with -- inside SECTIONS[2] or SECTIONS[3]. Named Sections What the heck does elif act_section == SECTIONS[2]: mean, anyway? If a new section gets added before "SECTION-C", is it going to be added to the SECTIONS list before that item? If so, you'll have to find everywhere there is SECTIONS[2] and change that to SECTIONS[3], but first you'll have to change all SECTIONS[3] to SECTIONS[4]! You're using SECTIONS[#] to avoid typing out the whole string multiple times to reduce the chance of typos and ensure it only needs to be changed in one spot if it does require changing, but it is obfuscating the code such that the reader has to refer elsewhere and count to determine what section SECTIONS[2] actually means! It needs to be commented better, but comments aren't actually tested so there is no guarantee the comments are actually correct. You need: def parser(lines): SECTION_A = "SECTION-A" SECTION_B = "SECTION-B" SECTION_C = "SECTION-C" SECTION_D = "SECTION-D" SECTION_END = "END" SECTIONS = { SECTION_A, SECTION_B, SECTION_C, SECTION_D, SECTION_END, } ... elif act_section == SECTION_A or act_section == SECTION_B: ... elif act_section == SECTION_C: ... elif act_section == SECTION_D: ... No more counting is necessary (or even possible because SECTIONS is now a set). At this point, it may be worth considering an Enum. from enum import Enum class Section(Enum): A = "SECTION-A" B = "SECTION-B" C = "SECTION-C" D = "SECTION-D" END = "END" Efficiency There is no need to read and store the entire file into memory. You can easily process the file line by line.
{ "domain": "codereview.stackexchange", "id": 43788, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python, random Title: Create different groups of students for a number of assignments Question: How can I make the code easy? The function which was developed contains the following inputs: students: a list with names of students events: an integer specifying how many group assignments should be created group size: an integer specifying how big a group can be at maximum. The function should return a list of group assignments. The following shall apply to these: Each student must appear in a group only once per group assignment. A group assignment may not appear more than once in the result. The group assignment must be random. import random Courseparticipants = [ 'LeBron James', 'Giannis Antetokounmpo', 'Kevin Durant', 'Steph Curry', 'Kyrie Irving', 'Joel Embiid', 'Kawhi Leonard', 'Paul George', 'James Harden', 'Kemba Walker', 'Khris Middleton', 'Anthony Davis', 'Nikola Jokić', 'Klay Thompson', 'Ben Simmons', 'Damian Lillard', 'Blake Griffin', 'Russell Westbrook', 'D\'Angelo Russell', 'LaMarcus Aldridge', 'Nikola Vučević', 'Karl-Anthony Towns', 'Kyle Lowry', 'Bradley Beal', 'Dwyane Wade', 'Dirk Nowitzki' ]
{ "domain": "codereview.stackexchange", "id": 43789, "lm_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, random", "url": null }
python, random def groupclassification(students, events, groupsize): group = [] counter = len(students) / group size studis = [] studis = studis + students if events > 0: while counter >= 1: part1 = int(random.random() * len(studis)) part2 = int(random.random() * len(studis)) part3 = int(random.random() * len(studis)) if part1 != part2 and part1 != part3 and part2 != part3: group = group + [[studis[part1], studis[part2], studis[part3]]] x = studis[part1] y = studis[part2] z = studis[part3] studis.remove(x) studis.remove(y) studis.remove(z) counter -= 1 print(group) if len(studis) > 0: print("The following students were lost along the way:", studis) events -= 1 grouping(students, events, groupsize) groupclassification(Courseparticipants, 5, 3) Does anyone have any suggestions as to how I can make this code easier on the eye? Be as ruthless as you please. Answer: I'd probably load the list of names from the external data source instead of hardcoding it in the code. studis gets defined as an empty list only to have students added just a line later. Don't think thats any different than studis = students.copy(), other than being much less clear about the purpose. parts can be defined in a one-liner to remove a lot of repetition: part1, part2, part3 = [int(random.random() * len(studis)) for _ in range(3)]
{ "domain": "codereview.stackexchange", "id": 43789, "lm_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, random", "url": null }
python, web-scraping, beautifulsoup, selenium Title: scraping pollution data tables from government website
{ "domain": "codereview.stackexchange", "id": 43790, "lm_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, web-scraping, beautifulsoup, selenium", "url": null }
python, web-scraping, beautifulsoup, selenium Question: i made this python program to scrape and save the daily maximum pollution values in mexico city, the data will be used in machine learning but i wonder what could be improved: from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support.ui import Select from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC import bs4 import time import csv DRIVER_PATH = r"C:\Users\HP\Downloads\chromedriver_win32\chromedriver.exe" driver = webdriver.Chrome(executable_path=DRIVER_PATH) driver.implicitly_wait(60) for i in range(3): try: driver.get("http://www.aire.cdmx.gob.mx/default.php?opc=%27aqBjnmU=%27") break except: driver.navigate().refresh() WebDriverWait(driver, 60).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,'//*[@id="contenedorinformacion03"]/div/iframe'))) airquality=driver.find_element(By.XPATH,'//*[@id="sampleform"]/div[1]/div[1]/p[1]/input[2]') airquality.click() Select(WebDriverWait(driver, 60).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="indice_aire_div"]/div[1]/table/tbody/tr/td/table/tbody/tr[1]/td/table/tbody/tr[2]/td[4]/span/select')))).select_by_value("2010") Select(WebDriverWait(driver, 60).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="indice_aire_div"]/div[1]/table/tbody/tr/td/table/tbody/tr[1]/td/table/tbody/tr[3]/td[2]/span/select')))).select_by_value("31") Select(WebDriverWait(driver, 60).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="indice_aire_div"]/div[1]/table/tbody/tr/td/table/tbody/tr[1]/td/table/tbody/tr[3]/td[3]/span/select')))).select_by_value("12") Select(WebDriverWait(driver, 60).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="indice_aire_div"]/div[1]/table/tbody/tr/td/table/tbody/tr[1]/td/table/tbody/tr[3]/td[4]/span/select')))).select_by_value("2021")
{ "domain": "codereview.stackexchange", "id": 43790, "lm_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, web-scraping, beautifulsoup, selenium", "url": null }
python, web-scraping, beautifulsoup, selenium carbonmonoxide=driver.find_element(By.XPATH,'//*[@id="indice_aire_div"]/div[1]/table/tbody/tr/td/table/tbody/tr[4]/td/span/input[2]') carbonmonoxide.click() ozone=driver.find_element(By.XPATH,'//*[@id="indice_aire_div"]/div[1]/table/tbody/tr/td/table/tbody/tr[4]/td/span/input[4]') ozone.click() zoneclicker=driver.find_element(By.XPATH,'//*[@id="indice_aire_div"]/div[1]/table/tbody/tr/td/table/tbody/tr[7]/td/span/input[6]') zoneclicker.click() dataclicker=driver.find_element(By.XPATH,'//*[@id="indice_aire_div"]/div[1]/table/tbody/tr/td/table/tbody/tr[10]/td/span/input[2]') dataclicker.click() nextpage=driver.find_element(By.XPATH,'//*[@id="indice_aire_div"]/div[1]/table/tbody/tr/td/table/tbody/tr[12]/td/div/input') nextpage.click() time.sleep(30) #bad internet makes it slow soup = bs4.BeautifulSoup(driver.page_source, features="lxml", parse_only=bs4.SoupStrainer("table")) table = soup.find("table") output_rows = [] for table_row in table.findAll('tr'): columns = table_row.findAll('td') output_row = [] for column in columns: output_row.append(column.text) output_rows.append(output_row) with open('polution.csv', 'w') as csvfile: writer = csv.writer(csvfile) writer.writerows(output_rows) ```
{ "domain": "codereview.stackexchange", "id": 43790, "lm_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, web-scraping, beautifulsoup, selenium", "url": null }
python, web-scraping, beautifulsoup, selenium Answer: Don't use Selenium. Observe that the website sends the following POST http://www.aire.cdmx.gob.mx/estadisticas-consultas/consultas/resultado_consulta.php with this request body: -----------------------------40642155113769355341724901495 Content-Disposition: form-data; name="tipo_attach" b -----------------------------40642155113769355341724901495 Content-Disposition: form-data; name="diai" 31 -----------------------------40642155113769355341724901495 Content-Disposition: form-data; name="mesi" 1 -----------------------------40642155113769355341724901495 Content-Disposition: form-data; name="anoi" 2010 -----------------------------40642155113769355341724901495 Content-Disposition: form-data; name="diaf" 12 -----------------------------40642155113769355341724901495 Content-Disposition: form-data; name="mesf" 1 -----------------------------40642155113769355341724901495 Content-Disposition: form-data; name="anof" 2021 -----------------------------40642155113769355341724901495 Content-Disposition: form-data; name="CO" on -----------------------------40642155113769355341724901495 Content-Disposition: form-data; name="O3" on -----------------------------40642155113769355341724901495 Content-Disposition: form-data; name="TZ" on -----------------------------40642155113769355341724901495 Content-Disposition: form-data; name="Q" maximos -----------------------------40642155113769355341724901495 Content-Disposition: form-data; name="inter" -----------------------------40642155113769355341724901495 Content-Disposition: form-data; name="consulta" Consulta -----------------------------40642155113769355341724901495 Content-Disposition: form-data; name="trip-start" 2022-08-18 -----------------------------40642155113769355341724901495 Content-Disposition: form-data; name="trip-end" 2022-08-24 -----------------------------40642155113769355341724901495--
{ "domain": "codereview.stackexchange", "id": 43790, "lm_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, web-scraping, beautifulsoup, selenium", "url": null }
python, web-scraping, beautifulsoup, selenium 2022-08-24 -----------------------------40642155113769355341724901495-- Use the Requests package to construct such a request dynamically in a function with parameters for the date range, contaminants, zone and output type. After that, I recommend that you use pandas.read_html to parse the output. Suggested from datetime import date from requests import Session def query( session: Session, start: date, end: date, contaminants: tuple[str, ...], zones: tuple[str, ...], criteria: str, # etc. - more params need to be reverse-engineered ) -> str: with session.post( url='http://www.aire.cdmx.gob.mx/estadisticas-consultas/consultas/resultado_consulta.php', data={ 'tipo_attach': 'b', 'diai': start.day, 'mesi': start.month, 'anoi': start.year, 'diaf': end.day, 'mesf': end.month, 'anof': end.year, 'Q': criteria, 'inter': '', 'consulta': 'Consulta', **dict.fromkeys(contaminants + zones, 'on'), } ) as resp: resp.raise_for_status() return resp.text def main() -> None: with Session() as session: html = query( session, start=date(2010, 1, 1), end=date(2021, 12, 31), contaminants=('CO', 'O3'), zones=('TZ',), criteria='maximos', ) print(html) if __name__ == '__main__': main()
{ "domain": "codereview.stackexchange", "id": 43790, "lm_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, web-scraping, beautifulsoup, selenium", "url": null }
java, concurrency, cache Title: Threadsafe LRU Cache
{ "domain": "codereview.stackexchange", "id": 43791, "lm_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, concurrency, cache", "url": null }
java, concurrency, cache Question: Trying to design a threadsafe lru cache using a reentrant lock. Currently I don't like the tryLock in a loop approach. Any inputs on making it more optimal in terms of concurrency? import java.util.ArrayDeque; import java.util.Deque; import java.util.HashMap; import java.util.Map; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; class LRUNode { String key; String value; LRUNode(String key,String value){ this.key = key; this.value = value; } } public class LRU { Lock lock; Map<String,LRUNode> map; Deque<LRUNode> deque; int capacity; int size; LRU(int capacity) { this.size = 0; this.capacity = capacity; deque = new ArrayDeque<>(); this.map = new HashMap<>(); lock = new ReentrantLock(); } public String get(String key){ try { while (!lock.tryLock()) { Thread.sleep(50); } if (map.containsKey(key)) { //update deque LRUNode lruNode = map.get(key); System.out.println("Getting " + key + " from cache"); deque.remove(lruNode); deque.offer(lruNode); return lruNode.value; } } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } return null; } public void print(){ System.out.println("----- cache contents -------"); for(Map.Entry<String,LRUNode> entry : this.map.entrySet()){ System.out.println(entry.getKey()+ " : "+ entry.getValue().value); } System.out.println("----------------------------");
{ "domain": "codereview.stackexchange", "id": 43791, "lm_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, concurrency, cache", "url": null }
java, concurrency, cache } System.out.println("----------------------------"); } public void put(String key, String value){ try { while (!lock.tryLock()) { Thread.sleep(50); } if (size == capacity) { LRUNode nodeToBeRemoved = deque.getFirst(); System.out.println("Evicting " + nodeToBeRemoved.key + " from cache"); map.remove(nodeToBeRemoved.key); deque.removeFirst(); size--; } LRUNode lruNode = new LRUNode(key, value); map.put(key, lruNode); deque.offer(lruNode); System.out.println("Added " + key + " to cache"); size++; }catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } public static void main(String[] args) { LRU lru = new LRU(3); lru.put("k1","v1"); lru.put("k2","v2"); lru.put("k3","v3"); lru.print(); lru.put("k4","v4"); lru.put("k5","v5"); lru.put("k6","v6"); lru.put("k7","v7"); lru.put("k8","v8"); lru.put("k9","v9"); lru.print(); } }
{ "domain": "codereview.stackexchange", "id": 43791, "lm_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, concurrency, cache", "url": null }
java, concurrency, cache Answer: Any inputs on making it more optimal in terms of concurrency? This is specifically addressed in the Javadoc for LinkedHashMap: If multiple threads access a linked hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be "wrapped" using the Collections.synchronizedMap method. This is best done at creation time, to prevent accidental unsynchronized access to the map: Map m = Collections.synchronizedMap(new LinkedHashMap(...)); I.e. if you do not already have a synchronized object that encloses the Map, they recommend wrapping the Map with Collections.synchronizedMap. Then you don't have to write any concurrent code of your own. So, replace your LRU lru = new LRU(3); with Map<String, String> lru = Collections.synchronizedMap(new LinkedHashMap<String, String>(3) { protected final int LIMIT; public LRUCache(int capacity) { super(2 * capacity, .75, true); LIMIT = capacity; } @Override protected boolean removeEldestEntry() { return size() > LIMIT; } }); You can then modify your print method to take a Map as an argument instead of operating on this. This version Reduces the amount of code that you have to write. Provides you with all the advantages, including edge case handling and optimizations, of the native LinkedHashMap version of a least-recently-used cache. Provides you with all the advantages, including edge case handling and optimizations, of the native concurrency wrapper for Map.
{ "domain": "codereview.stackexchange", "id": 43791, "lm_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, concurrency, cache", "url": null }
java, concurrency, cache Now, it is certainly possible that your version is superior to this in some ways. If so, you should explain what your version gives that this version does not. The default should be to use the built-in versions until you find a reason to use something else. Since you use a Map internally, you are going to get the default map behavior. One example of that is that when the third element is added, your version will exceed the load factor and double the initial capacity. This version goes ahead and does that immediately, so no overhead on the third put. It is possible to come up with better implementations of a map, given that you don't need to resize. But you don't do that. An ArrayDeque is a bad solution for a least-recently-used queue. It requires copying blocks of memory each time you remove from the middle. So the LinkedHashMap is probably superior here, as it uses a linked list. And of course, the map gives constant time accesses to any node while the linked list gives constant time removes and adds. An alternative would be to make an array and maintain the links as indexes in the array. Then you wouldn't have to keep making and destroying the nodes. You'd just keep recycling the nodes in the array. You could even make it so that put would automatically write over the least-recently-used entry. This is a place where your version could be superior to LinkedHashMap. Because your capacity is so small, you also might find a heap (PriorityQueue) to provide superior performance. Yes, it's logarithmic removes and adds rather than constant. But for a small size, it may be faster to maintain the heap than to manage the linked list (including the memory allocations). Similarly, for a capacity of three, ditching the hash map and just doing a linear scan is sensible. But of course, you may simply have picked three as a small size so that it's easy to test the logic. Perhaps in practice, this would be much larger.
{ "domain": "codereview.stackexchange", "id": 43791, "lm_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, concurrency, cache", "url": null }
beginner, bash, linux, networking Title: Find proceses listening on the network outside of default package manager Question: I have been tinkering with a script that should list things that are listening on the network, but are not part of the base packaging manager. Currently I have only done support for fedora and debian based systems. Due to constraints on the system I am working on I have to support Bash 3.2 and above. This meant I got a bunch of complaints from shellcheck. Some of the things I think I did optimally How to properly read variables into arrays on older bash versions How to set a command pkg from the commandline argument pkg (for instance) Not sure how to avoid using "$?" in the last if as it complains if I push the entire function into the condition The last part using lsof is a bit of an hack, as I was unsure on how to extract the correct path without resorting to using the PID Any feedback or improvements are more than welcome. I did run shfmt over the code, so it should be decently formatted. Example output #!/bin/bash # finds processes listening in on the network outside outside of the default package manager usage="usage $(basename "$0").sh [-h] [-f] [-a] [-w] [-v] [-p] Lists packages listening on the network outside of the default package manager where: -h, --help show this help text -f, --whitelist-file pick a file[s] containing whitelisted programs -a, --list-all display all processes listening on the network -w, --whitelist explicitly add whitelisted programs -v, --view-whitelist view the complete whitelist -p, --package-manager which package-manager to use (rpm, dkpg, ...) output: COMMAND PATH PID USER FD TYPE DEVICE SIZE/OFF NODE NAME mattermos /app/main/mattermo 3351 361000 25u IPv4 84625698 0t0 TCP 129.240...(ESTABLISHED) examples: List all processes listening on the network usit_network_listeners --list-all
{ "domain": "codereview.stackexchange", "id": 43792, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, bash, linux, networking", "url": null }
beginner, bash, linux, networking examples: List all processes listening on the network usit_network_listeners --list-all List only packages not maintained by the central package manager system usit_network_listeners --list-all Whitelist some processes usit_network_listeners --whitelist mattermos,systemd usit_network_listeners --whitelist 'mattermos systemd' Whitelist some processes using whitelist files usit_network_listeners -f /etc/uio/uio_listeners_whitelist_01.txt Multiple whitelist files is supported usit_network_listeners --whitelist foo.txt,bar.txt environment variables: The following environment variables are available USIT_LISTENER_WHITELIST USIT_LISTENER_WHITELIST_FILES These form the base for the whitelist and whitelist files respectively. Use a string with spaces or comma [,] as seperator for the values. " # Transform long options to short ones for arg in "$@"; do shift case "$arg" in '--whitelist') set -- "$@" '-w' ;; '--whitelist-file') set -- "$@" '-f' ;; '--list-all') set -- "$@" '-a' ;; '--view-whitelist') set -- "$@" '-v' ;; '--package-manager') set -- "$@" '-p' ;; '--help') set -- "$@" '-h' ;; *) set -- "$@" "$arg" ;; esac done # The '//,/ ' allows us to input variables using , seperator as well as SPACE read -ar whitelist <<<"${USIT_LISTENER_WHITELIST//,/ }" read -ar whitelist_files <<<"${USIT_LISTENER_WHITELIST_FILES//,/ }" list_all=false view_whitelist=false while getopts ":w:f:p:avh" flag; do case "${flag}" in h) echo "$usage" exit 0 ;; a) list_all=true ;; v) view_whitelist=true ;; w) whitelist+=(${OPTARG//,/ }) ;; f) whitelist_files+=(${OPTARG//,/ }) ;; p) package_manager=${OPTARG} ;; \?) printf "illegal option: -%s\n" "$OPTARG" >&2 echo "$usage" >&2 exit 1 ;; esac done
{ "domain": "codereview.stackexchange", "id": 43792, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, bash, linux, networking", "url": null }
beginner, bash, linux, networking # Some logic is needed to figure out which base package manager the system uses dpkg_equivalents=("dpkg" "apt") rpm_equivalents=("rpm" "yum" "dnf") if [ -z "${package_manager}" ]; then if dpkg --version &>/dev/null; then package_manager="dpkg" elif rpm --version &>/dev/null; then package_manager="rpm" else echo "No supported package manager found! Try specifing one with -p --package-manager" exit 1 fi fi if [[ ${dpkg_equivalents[*]} =~ ${package_manager} ]] && dpkg --version &>/dev/null; then package_manager="dpkg" elif [[ ${rpm_equivalents[*]} =~ ${package_manager} ]] && rpm --version &>/dev/null; then package_manager="rpm" else echo "ERROR: the package manager ${package_manager} is not supported on your system!" exit 1 fi # The whitelist can also come from an array of files, add these to the global whitelist while IFS= read -r whitelist_file; do if test -f "${whitelist_file}"; then readarray -t arr <"${whitelist_file}" whitelist=("${whitelist[@]}" "${arr[@]}") fi done <<<"${whitelist_files[@]}" # It could happen same file is whitelisted multiple times. We only keep unique values whitelist=($(printf "%q\n" "${whitelist[@]}" | sort -u)) if [ "${view_whitelist}" = true ]; then if ((${#whitelist[@]})); then printf "%s\n" "${whitelist[@]}" fi exit fi
{ "domain": "codereview.stackexchange", "id": 43792, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, bash, linux, networking", "url": null }
beginner, bash, linux, networking # -i : This option filters only processes whith an IPv[46] address: # -P : This option inhibits the conversion of port numbers to port names for network files. # -n : This option inhibits the conversion of network numbers to host names for network files. # -l : This option inhibits the conversion of user ID numbers to login names. # +M : Enables the reporting of portmapper registrations for local TCP and UDP ports. # The awk filters only unique PID's by _[val] looks up val in the hash _(a regular variable). # Tail is used to skip the header listeners=$( lsof -Pnl +M -i | awk -F" " '!_[$1]++' | tail -n +2 ) # A bit cumbersome but this makes sure we define the correct package system only once # Logic: If the command can not find $1 then output $2, we suppress any output as well programname="" if [ "${package_manager}" == "rpm" ]; then is_in_standard_repo() { rpm -qf "${1}" &>/dev/null } elif [ "${package_manager}" == "dpkg" ]; then is_in_standard_repo() { dpkg -S "${1}" &>/dev/null } else echo "The package manager ${package_manager} is not supported! Choose rpm (red hat) or dpkg (debian)" exit 1 fi result=() # Next step is extracting the paths from the PID's while IFS= read -r line; do programname=$(echo "${line}" | awk '{print $1}') pid=$(echo "${line}" | awk '{print $2}') path=$(lsof -p "${pid}" 2>/dev/null | awk '/txt/ {print $9}') line=${line/$programname/$programname $path} if [ "$list_all" = true ]; then result+=("${line}") else is_in_standard_repo "$path" # If path is in standard repo AND not in whitelist print the line if [ "$?" -gt 0 ] && [[ ! ${whitelist[*]} =~ ${programname} ]]; then result+=("${line}") fi fi done <<<"$listeners" # Pretty format the output printf '%s\n' "${result[@]}" | column -t
{ "domain": "codereview.stackexchange", "id": 43792, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, bash, linux, networking", "url": null }
beginner, bash, linux, networking # Pretty format the output printf '%s\n' "${result[@]}" | column -t Answer: First of all, pretty nice script! (I think you could drop the beginner tag ;-) Dodgy transformation of long options When transforming the long options to short ones, I find it a bit dodgy to use set -- "$@" .... It feels like a dirty hack to iterate over the arguments \$n\$ to \$2n\$ times, and doing that in a for arg in "$@" loop with a shift, replacing the list being iterated on. It would be cleaner to collect the transformed args in another array, and then replace $@ with the items of that array: args=() for arg; do case $arg in '--whitelist') args+=(-w) ;; '--whitelist-file') args+=(-f) ;; '--list-all') args+=(-a) ;; '--view-whitelist') args+=(-v) ;; '--package-manager') args+=(-p) ;; '--help') args+=(-h) ;; *) args+=("$arg") ;; esac done set -- "${args[@]}" This is cleaner because the underlying argument list of the loop is not replaced in the middle of iterations, and $@ is not re-copied repeatedly, but replaced once at the end. Always double-quote variables on the command line I guess you don't support spaces in parameters of -w, because that would not work here: w) whitelist+=(${OPTARG//,/ }) ;; When appending the contents of a variable to an array, the correct form is: arr+=("$somevar") A clean solution would be: IFS=, read -ra parts <<< "$OPTARG" whitelist+=("${parts[@]}") ;; Review the order or operations A sequence of operations should be in order such that: Avoid unnecessary work Related operations are close together Consider this part from the posted code, with some details hidden: if [[ ${dpkg_equivalents[*]} =~ ${package_manager} ]] && ...; then package_manager="dpkg" elif ... package_manager="rpm" else exit 1 fi while IFS= read -r whitelist_file; do # ... listeners=$(lsof ...)
{ "domain": "codereview.stackexchange", "id": 43792, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, bash, linux, networking", "url": null }
beginner, bash, linux, networking while IFS= read -r whitelist_file; do # ... listeners=$(lsof ...) programname="" if [ "${package_manager}" == "rpm" ]; then # ... else exit 1 fi while IFS= read -r line; do programname=... # ... done <<<"$listeners" At first I though that the output of lsof might not be used, since there's a conditional exit after it, independently. Then I noticed that package_manager was already validated earlier in the code. Why is it checked again? The else branch will never be taken. If the code pieces related to package_manager were closer to each other, it would be easier to see that something is off. Also notice that before the validation of package_manager, there is also an auto-detection mechanism. The validation should not be necessary when the value was set by auto-detection. The lsof should be called right before the loop that uses its result. Also, instead of storing its output in a variable, you could pipe that directly into the while loop. Finally, notice that programname is initialized too early. It appears right before an if-else, and I'm confused to not find any references to it in that if-else. It is updated in a while loop later, so it would be good to move the initialization to right in front of that loop. Don't define functions in conditional blocks It's cool that you can define functions in an if-else in Bash, but I think it's unusual. I would use a variable to store the function name, something like this: is_in_rpm_repo() { rpm -qf "${1}" &>/dev/null } is_in_standard_repo= if [ "${package_manager}" == "rpm" ]; then is_in_standard_repo=is_in_rpm_repo # ... if "$is_in_standard_repo" "$path"; then # ...
{ "domain": "codereview.stackexchange", "id": 43792, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, bash, linux, networking", "url": null }
beginner, bash, linux, networking if "$is_in_standard_repo" "$path"; then # ... Use consistent style Most conditions use [ ... ], but there is one instance of test. I recommend [ ... ] consistently. Many places use <<< "..." here-strings, but there are a few echo | .... I recommend here-strings consistently. Some of the error messages are correctly printed to stderr. Some are printed to stdout. And since it's a bit annoying to type >&2 and exit 1 repeatedly, I usually define a fatal helper function: fatal() { echo "fatal: $*" >&2 exit 1 } Use a here-document instead of a multiline double-quoted string With a multiline double-quoted string as in the definition of the usage variable, I would be afraid that someday somebody will accidentally add a double-quote somewhere in the content and forgets to escape it properly, breaking the script. I would sleep better if the long string was defined as a here-document, which is harder to mess up. read -r usage <<< EOF # ... EOF
{ "domain": "codereview.stackexchange", "id": 43792, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, bash, linux, networking", "url": null }
python, pandas, python-requests Title: python: requests large.zip -> unzip -> fix -> filter ->gunzip Question: I wrote a function to download a large zipfile 5-7gb from Iowa State MRMS data archive. The zip files appear to be malformed and results in a BadZipFileError hence the fix_badzip function which calls a subprocess to repair the zip. after the zip is repaired I have a function to filter the ZipInfo for select files. The zip file contains several grib2.gz files, to which I use gunzip to extract import uuid import gzip import shutil import zipfile import subprocess from pathlib import Path from datetime import datetime from typing import Literal, Iterable import requests import pandas as pd import numpy as np # these are enums that I defined that describe the iastate directory # from .mmmpy import MRMSFeatures, MRMSRegions GZ = ".gz" READ = "r" WRITE_BINARY = "wb" class IAStateZip(zipfile.ZipFile): def filterinfo( self, regions: list[str], # list[MRMSRegions], features: list[str], # list[MRMSFeatures], ) -> Iterable[zipfile.ZipInfo]: df = pd.DataFrame({"zipInfo": self.infolist(), "path": self.namelist()}) df = df[df["path"].str.endswith(GZ)] df.loc[:, ["validTime", "region", "feature", "name"]] = np.vstack( df["path"].str.split("/") ) region_mask = np.any( (np.array(regions)[:, np.newaxis] == df["region"].values).T, axis=1 ) feature_mask = np.any( (np.array(features)[:, np.newaxis] == df["feature"].values).T, axis=1 ) yield from df.loc[(region_mask & feature_mask), "zipInfo"]
{ "domain": "codereview.stackexchange", "id": 43793, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, python-requests", "url": null }
python, pandas, python-requests def iastate_connect(start: datetime, out: Path, fix_zip: bool = True) -> Path: url = start.strftime("https://mrms.agron.iastate.edu/%Y/%m/%d/%Y%m%d%H.zip") print("downloading mrms data from:", url) _, filename = url.rsplit("/", maxsplit=1) file = out / filename with requests.get(url, stream=True) as r: r.raise_for_status() with file.open(WRITE_BINARY) as fd: for chunk in r.iter_content(chunk_size=4096): fd.write(chunk) if fix_zip: fix_badzip(file) return file def fix_badzip(corrupt: Path, in_place:bool=True): print("attempting to resolve zipfile") tmpfile = corrupt.parent / f"{uuid.uuid1()}.zip" subprocess.call( ["zip", "-FF", corrupt.as_posix(), f"--out={tmpfile.as_posix()}"], stdout=subprocess.DEVNULL, ) if in_place: corrupt.unlink() shutil.move(tmpfile, corrupt) def main(): data = Path.cwd().parent / "data" zfile = iastate_connect( datetime.fromisoformat("2022-06-01T12"), out=data ) assert zfile.is_file() # open the zip file with IAStateZip(zfile) as zf: # filter the info inside of the zip for member in zf.filterinfo(regions=["CONUS"], features=["MergedReflectivityQC"]): # split the nested product directory directory, filename = member.filename.rsplit("/",maxsplit=1) # create a new file_path file_path = zfile.parent / directory if not file_path.exists(): file_path.mkdir(parents=True) file = file_path / filename.removesuffix(GZ) # read the member from the zip file with zf.open(member,READ) as zref: # open a new file with file.open(WRITE_BINARY) as fdst: # wrote the unziped & gunziped file to the new folder fdst.write(gzip.decompress(zref.read())) if __name__ == "__main__": main()
{ "domain": "codereview.stackexchange", "id": 43793, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, python-requests", "url": null }
python, pandas, python-requests if __name__ == "__main__": main() Answer: I would probably just delete these constants: GZ = ".gz" READ = "r" WRITE_BINARY = "wb" They're pretty obvious. These two parameters: regions: list[str], # list[MRMSRegions], features: list[str], # list[MRMSFeatures], are probably better-represented as sets. I don't think that Pandas has much advantage here - you throw away most of your data immediately after construction so you should probably just have a plain filtration loop. You should break this up: url = start.strftime("https://mrms.agron.iastate.edu/%Y/%m/%d/%Y%m%d%H.zip") into two separate variables, each using a format string: filename = f'{start:%Y%m%d%H}.zip' url = f'https://mrms.agron.iastate.edu/{start:%Y/%m/%d}/{filename}' Then don't rsplit to get the filename. Your chunk size should be much larger than 4k; try 4M. You already use shutil elsewhere; you might as well copyfileobj(r.raw, fd) rather than iter_content in a loop. Don't allow shell=True in your subprocess call.
{ "domain": "codereview.stackexchange", "id": 43793, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, python-requests", "url": null }
c#, optimization, interview-questions, fizzbuzz Title: Writing FizzBuzz Question: First of all, I came up with that question on SO already. But I am offered different solution which are "better" in some ways. The goal is to improve this specific version, not to create another one. Here is what it is about: Reading Coding Horror, I just came across the FizzBuzz another time. The original post is here. I just started to code it down. It was a job of a minute, but there are several things that I do not like. public void DoFizzBuzz() { var combinations = new Tuple<int, string>[] { new Tuple<int, string> (3, "Fizz"), new Tuple<int, string> (5, "Buzz"), }; for (int i = 1; i <= 100; i++) { bool found = false; foreach (var comb in combinations) { if (i % comb.Item1 == 0) { found = true; Console.Write(comb.Item2); } } if (!found) { Console.Write(i); } Console.Write(Environment.NewLine); } } So my questions are: How to get rid of the bool found? Is there a better way of testing than the foreach? Answer: I think if you're going to set up a set of data to iterate over you should start thinking more functionally. Why not use an array of functions and aggregate over them instead? That puts the logic in the functions, not in the function that utilises the data. For example: static void Main(string[] args) { var generators = new Func<string, int, string>[] { (s, i) => i % 3 == 0 ? s + "Fizz" : s, (s, i) => i % 5 == 0 ? s + "Buzz" : s, (s, i) => s ?? i.ToString() }; var results = Enumerable.Range(0, 100).Select(i => generators.Aggregate((string)null, (s, f) => f(s, i))).ToList(); results.ForEach(Console.WriteLine); }
{ "domain": "codereview.stackexchange", "id": 43794, "lm_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#, optimization, interview-questions, fizzbuzz", "url": null }
c#, performance Title: Randomly pick item from list with variable probabilities Question: This is supposed to randomly pick out the pieces for a Tetris clone. When a piece doesn't get drawn, its probability of getting drawn increases. I want to know if there is a way to do any part of this (or the whole idea) more efficiently. I'm also curious how you would judge the readability. Thank you. This is the class that returns a random item via DrawItem() using System; using System.Collections.Generic; using System.Linq; public class WeightedRNG<T> { private List<RNGItem<T>> _RNGItems; private Random _RNG; public WeightedRNG(IEnumerable<T> items) { PopulateList(items); _RNG = new Random(); } private void PopulateList(IEnumerable<T> items) { _RNGItems = new List<RNGItem<T>>(); foreach (T item in items) { _RNGItems.Add(new RNGItem<T>(1, item)); } } private IEnumerable<int> CompileItemsForDrawing() { for (int i = 0; i < _RNGItems.Count; i++) { for (int k = 0; k < _RNGItems[i].Weight; k++) { yield return i; } } } private int GetWeightSum() { return _RNGItems.Sum(n => n.Weight); } public T DrawItem() { int index = CompileItemsForDrawing().ToArray()[_RNG.Next(GetWeightSum())]; foreach (RNGItem<T> item in _RNGItems) { item.AddWeight(); } _RNGItems[index].ResetWeight(); return _RNGItems[index].Item; }
{ "domain": "codereview.stackexchange", "id": 43795, "lm_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", "url": null }
c#, performance return _RNGItems[index].Item; } public string[] GetAllOdds() { //this method only exists in order to have debug output in the right format for the form List<RNGItem<T>> temp = new List<RNGItem<T>>(_RNGItems); temp.Sort(); int range = GetWeightSum(); string[] ss = new string[temp.Count]; for (int i = 0; i < temp.Count; i++) { ss[i] = temp[i].Item + " " + (((double)temp[i].Weight / range) * 100).ToString("N3"); } return ss; } } And the RNGItem class that comprises the list in WeightedRNG using System; public class RNGItem<T> : IComparable<RNGItem<T>> { public int Weight { get; private set; } public T Item { get; private set; } public RNGItem(int weight, T item) { Weight = weight; Item = item; } public void AddWeight() { Weight++; } public void ResetWeight() { Weight = 1; } public int CompareTo(RNGItem<T> other) { //gets sorted in descending order return Weight.CompareTo(other.Weight) * -1; } } I used it like this for testing, a simple form with a Button and a TextBox for output: using System; using System.Windows.Forms; public partial class TetrisForm : Form { public WeightedRNG<string> WeightedRNG; public TetrisForm() { InitializeComponent(); WeightedRNG = new WeightedRNG<string>(new string[]{ "Type_A", "Type_B", "Type_C", "Type_D", "Type_E", "Type_F", "Type_G"}); } private void button1_Click(object sender, EventArgs e) { button1.Text = WeightedRNG.DrawItem(); foreach (var t in WeightedRNG.GetAllOdds()) { richTextBox1.AppendText(t + "\n"); } richTextBox1.AppendText("##########\n"); richTextBox1.ScrollToCaret(); } }
{ "domain": "codereview.stackexchange", "id": 43795, "lm_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", "url": null }
c#, performance Answer: The idea is that you have to normalize weighted probability so that they will sum up to 1. Then pick a number betwen [0-1) and then check where the probability selected fall and pick the corresponding element : // event probability land here // | // V // |__S__|__L__|__T__|__I__| (size of weighted probability will change after eachn normalization, they born equals but some block became bigger, other smaller) // // after selection change weight of not selected (increase with your policy) and re-normalize values That said i have the feeling that this is a triky way to express a simple random disrtibution, so you can basically get rid of all the weighting process and use the plain random result. So even if i am not persuaded that your goal is "valid" i have written a simple program to show you what i mean with the weighting process (that IMHO can be usefull as patter in other scenarioes). I have used a brand new conde, because as stated in the comment is not clear how to use yours. That said code proposed is really short and more like a "pseudo code" intended to portrait a clear picture about what i said before. class Program { private class TetrisPieces { public double NormalizedWeight = 0d; public double Weight = 1; public string Name = ""; } private static Random _rng = new Random(0); static void Main(string[] args) { List<TetrisPieces> tetrisPieces = new List<TetrisPieces>(); tetrisPieces.Add(new TetrisPieces() { Name = "SquaredBlock" }); tetrisPieces.Add(new TetrisPieces() { Name = "LBlock" }); tetrisPieces.Add(new TetrisPieces() { Name = "TBlock" }); tetrisPieces.Add(new TetrisPieces() { Name = "IBlock" }); Program.NormalizeWeights(tetrisPieces); //complete the initialization with first normalization of weight
{ "domain": "codereview.stackexchange", "id": 43795, "lm_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", "url": null }
c#, performance Console.WriteLine("Selection 1 : " + Program.RandomChoose(tetrisPieces).Name + " (the same value already printed by extraction debug, it's not anoter extraction)"); Console.WriteLine("Selection 2 : " + Program.RandomChoose(tetrisPieces).Name + " (the same value already printed by extraction debug, it's not anoter extraction)"); Console.WriteLine("Selection 3 : " + Program.RandomChoose(tetrisPieces).Name + " (the same value already printed by extraction debug, it's not anoter extraction)"); Console.WriteLine("Selection 4 : " + Program.RandomChoose(tetrisPieces).Name + " (the same value already printed by extraction debug, it's not anoter extraction)"); Console.WriteLine("Selection 5 : " + Program.RandomChoose(tetrisPieces).Name + " (the same value already printed by extraction debug, it's not anoter extraction)"); Console.WriteLine("Selection 6 : " + Program.RandomChoose(tetrisPieces).Name + " (the same value already printed by extraction debug, it's not anoter extraction)"); Console.WriteLine("Selection 7 : " + Program.RandomChoose(tetrisPieces).Name + " (the same value already printed by extraction debug, it's not anoter extraction)"); Console.WriteLine("Selection 8 : " + Program.RandomChoose(tetrisPieces).Name + " (the same value already printed by extraction debug, it's not anoter extraction)"); Console.ReadKey(); } private static void NormalizeWeights(List<TetrisPieces> items) { double totalWeight = items.Select(item => item.Weight).Sum(); double lowerProbability = 0d; Console.WriteLine("Normalization Debug"); foreach (var item in items) { item.NormalizedWeight = item.Weight / totalWeight; Console.WriteLine($"{item.Name} [{lowerProbability}-{lowerProbability + item.NormalizedWeight})");
{ "domain": "codereview.stackexchange", "id": 43795, "lm_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", "url": null }
c#, performance lowerProbability += item.NormalizedWeight; } } private static TetrisPieces RandomChoose(List<TetrisPieces> items) { double eventProbability = _rng.NextDouble(); Console.WriteLine("Extraction Debug : pEvent = " + eventProbability); double lowerProbability = 0d; TetrisPieces candidate = null; foreach (var item in items) { if (lowerProbability <= eventProbability && eventProbability < (lowerProbability + item.NormalizedWeight)) { candidate = item; break; } lowerProbability += item.NormalizedWeight; } if (candidate == null) { //you should never land here, but maybe rounding error may be unexpected, anyway if you are here you meant to choose the last peace Console.WriteLine("Item not choosed"); candidate = items.Last(); } Console.WriteLine("Extraction Debug : Item selected -> " + candidate.Name); var nonSelectedItems = items.Where(item => item != candidate); foreach (var item in nonSelectedItems) item.Weight++; Program.NormalizeWeights(items); return candidate; // event probability land here // | // V // |__S__|__L__|__T__|__I__| (size of weighted probability will change after eachn normalization, they born equals but some block became bigger, other smaller) // // after selection change weight of not selected (increase with your policy) and re-normalize values } }
{ "domain": "codereview.stackexchange", "id": 43795, "lm_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", "url": null }
c#, performance Here the output : Normalization Debug SquaredBlock [0-0,25) LBlock [0,25-0,5) TBlock [0,5-0,75) IBlock [0,75-1) Extraction Debug : pEvent = 0,72624326996796 Extraction Debug : Item selected -> TBlock Normalization Debug SquaredBlock [0-0,285714285714286) LBlock [0,285714285714286-0,571428571428571) TBlock [0,571428571428571-0,714285714285714) IBlock [0,714285714285714-1) Selection 1 : TBlock (the same value already printed by extraction debug, it's not anoter extraction) Extraction Debug : pEvent = 0,817325359590969 Extraction Debug : Item selected -> IBlock Normalization Debug SquaredBlock [0-0,3) LBlock [0,3-0,6) TBlock [0,6-0,8) IBlock [0,8-1) Selection 2 : IBlock (the same value already printed by extraction debug, it's not anoter extraction) Extraction Debug : pEvent = 0,768022689394663 Extraction Debug : Item selected -> TBlock Normalization Debug SquaredBlock [0-0,307692307692308) LBlock [0,307692307692308-0,615384615384615) TBlock [0,615384615384615-0,769230769230769) IBlock [0,769230769230769-1) Selection 3 : TBlock (the same value already printed by extraction debug, it's not anoter extraction) Extraction Debug : pEvent = 0,558161191436537 Extraction Debug : Item selected -> LBlock Normalization Debug SquaredBlock [0-0,3125) LBlock [0,3125-0,5625) TBlock [0,5625-0,75) IBlock [0,75-1) Selection 4 : LBlock (the same value already printed by extraction debug, it's not anoter extraction) Extraction Debug : pEvent = 0,206033154021033 Extraction Debug : Item selected -> SquaredBlock Normalization Debug SquaredBlock [0-0,263157894736842) LBlock [0,263157894736842-0,526315789473684) TBlock [0,526315789473684-0,736842105263158) IBlock [0,736842105263158-1) Selection 5 : SquaredBlock (the same value already printed by extraction debug, it's not anoter extraction) Extraction Debug : pEvent = 0,558884794618415 Extraction Debug : Item selected -> TBlock Normalization Debug SquaredBlock [0-0,272727272727273) LBlock [0,272727272727273-0,545454545454545)
{ "domain": "codereview.stackexchange", "id": 43795, "lm_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", "url": null }
c#, performance Normalization Debug SquaredBlock [0-0,272727272727273) LBlock [0,272727272727273-0,545454545454545) TBlock [0,545454545454545-0,727272727272727) IBlock [0,727272727272727-1) Selection 6 : TBlock (the same value already printed by extraction debug, it's not anoter extraction) Extraction Debug : pEvent = 0,906027066011926 Extraction Debug : Item selected -> IBlock Normalization Debug SquaredBlock [0-0,28) LBlock [0,28-0,56) TBlock [0,56-0,76) IBlock [0,76-1) Selection 7 : IBlock (the same value already printed by extraction debug, it's not anoter extraction) Extraction Debug : pEvent = 0,442177873310716 Extraction Debug : Item selected -> LBlock Normalization Debug SquaredBlock [0-0,285714285714286) LBlock [0,285714285714286-0,535714285714286) TBlock [0,535714285714286-0,75) IBlock [0,75-1) Selection 8 : LBlock (the same value already printed by extraction debug, it's not anoter extraction)
{ "domain": "codereview.stackexchange", "id": 43795, "lm_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", "url": null }
c#, performance -- EDIT : added detail about my gut feeling on necessity of balancement on evenly distributed number generator. As stated in the comment i think that a plain selection (like the first one) is all you need. I think that the balancement proposed does not change probabiliry in a signifcant way. Here my "gut feeling proof" : if there is no balancement at all the, probability for pieces in a row are : 25% 6% 1% 0.3% (negletable) With the current balancement : 25% 3% 0.3% (negletable)
{ "domain": "codereview.stackexchange", "id": 43795, "lm_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", "url": null }
c#, performance 25% 3% 0.3% (negletable) So as you can see they drop a bit faster, but this is a thing only in a very unlikely scenario. So if it's really a no-no situation that a piece is picked three time in a row, just pick them randomly and update a block list (a counter that restart every time the pieces is different of the previous and increment when they are equal). If it's really a no-no situation that a piece is picked fewer time (than three, aka two times) use a stringet block list that stop at two. Because as you can see in the probability printed, with only few selection (the 9 seleciont i made) due to the randomness and evenly distribution of PNRG you actually does not use you algorithm (even after applying weight the probability fluctuate arround 25%). To be more precise 97% of the time you algorithm is just equivalent to a simple picking, and as simple picking does not generate duplicate. If you accept single duplicate then equivalence grow to ~99%. So basically what i am saing is that if thing changes only in 3% to <1% of scenarioes (depending on how stringent are your requirements). For that reason i think it's simpler to stick to plain randomness and then validate output against a block list (in case discard and generate again and again) if really is a no-no situation (or do nothing if it's acceptable). IMHO balancements are meaningfull only if you have a non random surce, or a source with distribution different form the one you choose. But you need a raondm distribution, and you have a random distribution, so i think no balancements are needed. And last but not the least, i personally think that all this methodology (block list or balancement) will negatively affect the chance, making games predictable. Let radomness do it's work :) PS : https://tetris.fandom.com/wiki/Random_Generator here some detail on actual algorithm, as you can see it generate a random permutation of symbol list and the deal them. tetrisPieces.OrderBy ( piece => _rng.NextDouble() );
{ "domain": "codereview.stackexchange", "id": 43795, "lm_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", "url": null }
c++, algorithm, strings, hash-map Title: Finding anagram groups using hashing and mapping the alphabet to random numbers Question: I was solving Group Anagram problem in leetcode. Link for the problem https://leetcode.com/problems/group-anagrams/ Below is the code which I wrote class Solution { public: vector<vector<string>> groupAnagrams(vector<string>& inp) { if(inp.size() == 0) return vector<vector<string> > {{}}; int count = 1; map<char, long long> alphaVal; for (char i = 'a'; i <= 'z'; i++) { alphaVal[i] = int(rand()); } map<long long, vector<string> > prep; for (auto value : inp) { long long temp = 0; for (auto c_p : value) { temp += alphaVal[c_p]; } //cout << "temp " << temp << endl; prep[temp].push_back(value); } vector < vector<string> > ans; for (auto it = prep.begin(); it != prep.end(); it++) { vector<string> temp; for (int i = 0; i < it->second.size(); i++) { //cout << it->second[i] << " "; temp.push_back(it->second[i]); } ans.push_back(temp); } return ans; } }; I have two questions: Even though the above solution worked, is using random is a really good idea? Previously I wrote a logic to check the characters and store the string. map<set<char>, vector<string> > prep; for (auto value : inp) { set<char> temp; for (auto c_p : value) { temp.insert(c_p); } prep[temp].push_back(value); } For the above logic one test case failed ip: ["ddddddddddg","dgggggggggg"] op: [["ddddddddddg","dgggggggggg"]] Even though the two strings are unique, the set hash calculation says it is same. Any idea why this behavior on the selected test case? Was just curious to know. Thanks for the answers! Answer: Answering your questions Even though the above solution worked, is using random is a really good idea?
{ "domain": "codereview.stackexchange", "id": 43796, "lm_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++, algorithm, strings, hash-map", "url": null }
c++, algorithm, strings, hash-map Even though the above solution worked, is using random is a really good idea? It's not a good idea. It doesn't ensure a correct result. To paraphrase the code at a high level: Assign random long long values to the alphabet For each word in the input Sum the random value of the letters Since anagrams will have the same sum, group the words by the sum This approach is flawed, because: Words that are not anagrams may also have the same sum. With some bad luck due to the randomness, words may get assigned to the same bucket incorrectly. Although long long is a big range, it's possible that more than one letter gets assigned the same random number. That will significantly increase the risk of collisions. To group anagrams correctly, the grouping key must be something that distinctly identifies the anagrams, and never shared by words that shouldn't be in the same group. This unique key could be the map of letter counts: map<map<char, int>, vector<string>> counts2words; for (auto word : words) { map<char, int> counts; for (auto c : word) { counts[c]++; } counts2words[counts].push_back(word); } Even though the two strings are unique, the set hash calculation says it is same. Any idea why this behavior on the selected test case?
{ "domain": "codereview.stackexchange", "id": 43796, "lm_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++, algorithm, strings, hash-map", "url": null }
c++, algorithm, strings, hash-map First of all, that statement is misleading. In this example, it's much more than the hash calculation that's the same, here the two sets themselves are the same, consisting of the letters "d" and "g". But let's just assume that hash calculation for two strings S1 and S2 were the same. That wouldn't be too surprising, that's just how hash functions work. Collisions happen, that's why it's important that when working with hashes, when the hashed values are equal, you also must compare the unhashed values to verify if they are really equal. Use descriptive names The names used throughout the implementation are cryptic. See the example code above where I used a map of counts: everything has a descriptive name, except the trivial c for the letters. Drop unnecessary input validation This is unnecessary: if(inp.size() == 0) return vector<vector<string> > {{}}; For one thing, the problem description guarantees that the input is never empty. For another, the implementation naturally handles correctly the case of empty input.
{ "domain": "codereview.stackexchange", "id": 43796, "lm_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++, algorithm, strings, hash-map", "url": null }
python, sqlalchemy Title: Retrieve, parse and export data to tables via sqlalchemy Question: The project I've working on is designed with the intent of being able to quickly and efficiently identify discrepancies in live sports betting data that comes from web API's in json format. The first step is to retrieve the json's and I have incorporated async for that. Each json is structured differently so it gets parsed within it's own class called GamesDict. Once parsed it gets inserted to a database table via sqlalchemy and is ready for evaluation. A key point here is that the json files contain basic data for every game, but we also need more data that can only be obtained via a separate json URL. URL's for individual games need event_id's so that is obtained within the db_query script. Once the individual game json's for each source are obtained they can be parsed and inserted to tables similar to how it was done in the first process. This is the first iteration of the project and I know I have a lot to learn and would appreciate any feedback. These are the issues I'm dealing with right now: Stick with core or use ORM? How to organize the data - more tables or less? How to move/replace outdated entries with most recent parse_games.py BOOK = 'book3' class GamesDict: """ Class GamesDict takes a list of dictionaries and a database control object as variables. It calls on methods to parse the data pursuant to it's stat type (runline, props, etc) and then commits the data to it's corresponding table. """ def __init__(self, listofdics, db_control): self._dic = listofdics[BOOK]['eventGroup'] self.db_control = db_control self.events = self._dic.get('events',()) self.categories = self._dic.get('offerCategories',())
{ "domain": "codereview.stackexchange", "id": 43797, "lm_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, sqlalchemy", "url": null }
python, sqlalchemy self.export_gamelist() self.export_runline() self.export_moneyline() self.export_total() self.export_propshomeruns() self.export_propshits() self.export_propsrbis() self.export_propsrunsscored() self.export_propsstolenbases() self.export_propssingles() self.export_propsdoubles() self.export_propstriples() self.export_propsstrikeouts() self.export_propsoutsrecorded() self.export_propswin() self.export_propshitsallowed() self.export_propswalks() self.export_propsearnedruns() ## self.export_plateappearanceexact() def export_gamelist(self): self.gamelist = Gamelist().to_dict(self.events) GamelistControl(BOOK,self.db_control).commit_entry(self.gamelist) def export_runline(self): self.runline = Runline().to_dict(self.categories) RunlineControl(BOOK,self.db_control).commit_entry(self.runline) def export_moneyline(self): self.moneyline = Moneyline().to_dict(self.categories) MoneylineControl(BOOK,self.db_control).commit_entry(self.moneyline) def export_total(self): self.total = Total().to_dict(self.categories) TotalControl(BOOK,self.db_control).commit_entry(self.total) def export_propshomeruns(self): self.propshomeruns = PropsHomeruns().to_dict(self.categories) PropsControl(BOOK,self.db_control,'homeruns').commit_entry(self.propshomeruns) def export_propshits(self): self.propshits = PropsHits().to_dict(self.categories) PropsControl(BOOK,self.db_control,'hits').commit_entry(self.propshits) def export_propstotalbases(self): self.propstotalbases = PropsTotalBases().to_dict(self.categories) PropsControl(BOOK,self.db_control,'totalbases').commit_entry(self.propstotalbases)
{ "domain": "codereview.stackexchange", "id": 43797, "lm_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, sqlalchemy", "url": null }
python, sqlalchemy def export_propsrbis(self): self.propsrbis = PropsRBIs().to_dict(self.categories) PropsControl(BOOK,self.db_control,'rbis').commit_entry(self.propsrbis) def export_propsrunsscored(self): self.propsrunsscored = PropsRunsScored().to_dict(self.categories) PropsControl(BOOK,self.db_control,'runsscored').commit_entry(self.propsrunsscored) def export_propsstolenbases(self): self.propsstolenbases = PropsStolenBases().to_dict(self.categories) PropsControl(BOOK,self.db_control,'stolenbases').commit_entry(self.propsstolenbases) def export_propssingles(self): self.propssingles = PropsSingles().to_dict(self.categories) PropsControl(BOOK,self.db_control,'singles').commit_entry(self.propssingles) def export_propsdoubles(self): self.propsdoubles = PropsDoubles().to_dict(self.categories) PropsControl(BOOK,self.db_control,'doubles').commit_entry(self.propsdoubles) def export_propstriples(self): self.propstriples = PropsTriples().to_dict(self.categories) PropsControl(BOOK,self.db_control,'triples').commit_entry(self.propstriples) def export_propsstrikeouts(self): self.propsstrikeouts = PropsStrikeouts().to_dict(self.categories) PropsControl(BOOK,self.db_control,'strikeouts').commit_entry(self.propsstrikeouts) def export_propsoutsrecorded(self): self.propsoutsrecorded = PropsOutsRecorded().to_dict(self.categories) PropsControl(BOOK,self.db_control,'outsrecorded').commit_entry(self.propsoutsrecorded) def export_propswin(self): self.propswin = PropsWin().to_dict(self.categories) PropsControl(BOOK,self.db_control,'win').commit_entry(self.propswin) def export_propshitsallowed(self): self.propshitsallowed = PropsHitsAllowed().to_dict(self.categories) PropsControl(BOOK,self.db_control,'hitsallowed').commit_entry(self.propshitsallowed)
{ "domain": "codereview.stackexchange", "id": 43797, "lm_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, sqlalchemy", "url": null }
python, sqlalchemy def export_propswalks(self): self.propswalks = PropsWalks().to_dict(self.categories) PropsControl(BOOK,self.db_control,'walks').commit_entry(self.propswalks) def export_propsearnedruns(self): self.propsearnedruns = PropsEarnedRuns().to_dict(self.categories) PropsControl(BOOK,self.db_control,'earnedruns').commit_entry(self.propsearnedruns) ## ## def export_plateappearanceexact(self): ## self.plateappearanceexact = PAExact().to_dict(self.categories) ## PAExact(BOOK,self.db_control).commit_entry(self.plateappearanceexact) class Parser: CATEGORY: int SUBCATEGORY: int DISPLAY_NAME: str def to_dict(self, markets): return [market for market in self._get_records(markets)] @classmethod def _get_records(cls, data): raise NotImplementedError() class Gamelist(Parser): """ Class Gamelist is a dedicated parser for general game information such as event id and start time. """ CATEGORY = None SUBCATEGORY = None DISPLAY_NAME = 'Gamelist' @classmethod def _get_records(cls, events) for event in events: if "@" in event['name']: yield from cls._get_data(event) @classmethod def _get_data(cls, event) event_id = event['eventId'] game_datetime = unix(event['startDate']) away_abbr = TEAMS.get(event["teamName1"]) home_abbr = TEAMS.get(event["teamName2"]) game_ref = (f'{away_abbr}@{home_abbr}') return ((event_id, game_ref, game_datetime, BOOK)), class Category(Parser): """ Class Category takes the larger dictionary and parses it based on the statistics specific category and subcategory. """ @classmethod def _get_records(cls, data) for item in data: if item['offerCategoryId'] == cls.CATEGORY: yield from cls._get_subcatdes(item['offerSubcategoryDescriptors'])
{ "domain": "codereview.stackexchange", "id": 43797, "lm_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, sqlalchemy", "url": null }
python, sqlalchemy @classmethod def _get_subcatdes(cls, data) for item in data: if item['subcategoryId'] == cls.SUBCATEGORY: yield from cls._get_subcat(item['offerSubcategory'].get('offers')) @classmethod def _get_subcat(cls, data) for item in data: for x in item: if cls.DISPLAY_NAME in x.get('label',()) and x.get('isOpen',()): yield from cls._get_data(x) class Runline(Category): """ Class Runline is a dedicated parser for runline statistics. """ CATEGORY = 493 SUBCATEGORY = 4519 DISPLAY_NAME = 'Run Line' @classmethod def _get_data(cls, market): event_id = market['eventId'] away_team, home_team = market['outcomes'][:2] away_abbr = TEAMS.get(away_team['label']) home_abbr = TEAMS.get(home_team['label']) away_odds = away_team['oddsDecimal'] home_odds = home_team['oddsDecimal'] away_line = away_team['line'] home_line = home_team['line'] return ( (away_abbr, event_id, away_odds, away_line, BOOK), (home_abbr, event_id, home_odds, home_line, BOOK), ) class Moneyline(Category): """ Class Moneyline is a dedicated parser for moneyline statistics. """ CATEGORY = 493 SUBCATEGORY = 4519 DISPLAY_NAME = 'Moneyline' @classmethod def _get_data(cls, market): event_id = market['eventId'] away_team, home_team = market['outcomes'][:2] away_abbr = TEAMS.get(away_team['label']) home_abbr = TEAMS.get(home_team['label']) away_odds = away_team['oddsDecimal'] home_odds = home_team['oddsDecimal'] return ( (away_abbr, event_id, away_odds, BOOK), (home_abbr, event_id, home_odds, BOOK), )
{ "domain": "codereview.stackexchange", "id": 43797, "lm_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, sqlalchemy", "url": null }
python, sqlalchemy class Total(Category): """ Class Total is a dedicated parser for total statistics. """ CATEGORY = 493 SUBCATEGORY = 4519 DISPLAY_NAME = 'Total' @classmethod def _get_data(cls, market): event_id = market['eventId'] away_team, home_team = market['outcomes'][:2] line = away_team['line'] over = away_team['oddsDecimal'] under = home_team['oddsDecimal'] return ( (event_id, line, over, under, BOOK), ) class Props(Category): """ Class Props is a dedicated parser for all props statistics. """ @classmethod def _get_data(cls, market): event_id = market['eventId'] cont1, cont2 = market['outcomes'][:2] player = cont1.get('participant','') line = cont1.get('line',0) over = cont1.get('oddsDecimal','') under = cont2.get('oddsDecimal','') return ( (player, event_id, line, over, under, BOOK), ) class PropsHomeruns(Props): CATEGORY = 743 SUBCATEGORY = 6606 DISPLAY_NAME = 'Home Runs' class PropsHits(Props): CATEGORY = 743 SUBCATEGORY = 6719 DISPLAY_NAME = 'Hits' class PropsTotalBases(Props): CATEGORY = 743 SUBCATEGORY = 6606 DISPLAY_NAME = 'Total Bases' class PropsRBIs(Props): CATEGORY = 743 SUBCATEGORY = 8025 DISPLAY_NAME = 'RBIs' class PropsRunsScored(Props): CATEGORY = 743 SUBCATEGORY = 7979 DISPLAY_NAME = 'Runs' class PropsStolenBases(Props): CATEGORY = 743 SUBCATEGORY = 9872 DISPLAY_NAME = 'Stolen Bases' class PropsSingles(Props): CATEGORY = 743 SUBCATEGORY = 11031 DISPLAY_NAME = 'Singles' class PropsDoubles(Props): CATEGORY = 743 SUBCATEGORY = 11032 DISPLAY_NAME = 'Doubles' class PropsTriples(Props): CATEGORY = 743 SUBCATEGORY = 11033 DISPLAY_NAME = 'Triples'
{ "domain": "codereview.stackexchange", "id": 43797, "lm_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, sqlalchemy", "url": null }
python, sqlalchemy class PropsTriples(Props): CATEGORY = 743 SUBCATEGORY = 11033 DISPLAY_NAME = 'Triples' class PropsStrikeouts(Props): CATEGORY = 1031 SUBCATEGORY = 9885 DISPLAY_NAME = 'Strikeouts' class PropsOutsRecorded(Props): CATEGORY = 1031 SUBCATEGORY = 9883 DISPLAY_NAME = 'Outs' class PropsWin(Props): CATEGORY = 1031 SUBCATEGORY = 9884 DISPLAY_NAME = 'Win?' class PropsHitsAllowed(Props): CATEGORY = 1031 SUBCATEGORY = 9886 DISPLAY_NAME = 'Hits Allowed' class PropsWalks(Props): CATEGORY = 1031 SUBCATEGORY = 11035 DISPLAY_NAME = 'Walks' class PropsEarnedRuns(Props): CATEGORY = 1031 SUBCATEGORY = 11064 DISPLAY_NAME = 'Earned Runs' db_control.py class DBControl: def __init__(self): logging.info('[DBControl]: CONNECTING TO DATABASE') self.engine = create_engine('sqlite:///games.db', echo=False) self.inspector = inspect(self.engine) self.db_connection = self.engine.connect() self.create_session = sessionmaker(bind=self.engine) self.metadata = MetaData(bind=self.engine) class GamelistMLBControl: def __init__(self,book,db_control): self.table_name = f'{book}_gamelist' self.db_control = db_control self.table = self.check_table() def commit_entry(self,site_data): write_session = scoped_session(self.db_control.create_session) insert_stmt = insert(self.table).values(site_data) write_session.execute(insert_stmt) write_session.commit() write_session.remove()
{ "domain": "codereview.stackexchange", "id": 43797, "lm_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, sqlalchemy", "url": null }
python, sqlalchemy def check_table(self): metadata = self.db_control.metadata table_name = self.table_name if table_name not in self.db_control.inspector.get_table_names(): table_name = Table( str(table_name), metadata, Column("event_id", Integer, primary_key=True), Column("game_ref", String), Column("game_datetime", Integer), Column("book", String), ) metadata.create_all(self.db_control.engine) logging.info(f'[DBControl]: {table_name} created') else: metadata.reflect(self.db_control.engine) logging.info(f'[DBControl]: {table_name} exists') return Table(table_name, metadata, autoload=True) class GamelistControl: def __init__(self,book,db_control): self.table_name = f'{book}_gamelist' self.db_control = db_control self.table = self.check_table() def commit_entry(self,site_data): write_session = scoped_session(self.db_control.create_session) insert_stmt = insert(self.table).values(site_data) write_session.execute(insert_stmt) write_session.commit() write_session.remove()
{ "domain": "codereview.stackexchange", "id": 43797, "lm_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, sqlalchemy", "url": null }
python, sqlalchemy def check_table(self): metadata = self.db_control.metadata table_name = self.table_name if table_name not in self.db_control.inspector.get_table_names(): table_name = Table( str(table_name), metadata, Column("event_id", Integer, primary_key=True), Column("game_ref", String, primary_key=True), Column("game_datetime", Integer, primary_key=True), Column("book", String), ForeignKeyConstraint(['game_ref', 'game_datetime'], ['mlb_gamelist.game_ref', 'mlb_gamelist.game_datetime']) ) metadata.create_all(self.db_control.engine) logging.info(f'[DBControl]: {table_name} created') else: metadata.reflect(self.db_control.engine) logging.info(f'[DBControl]: {table_name} exists') return Table(table_name, metadata, autoload=True) class RunlineControl: def __init__(self,book,db_control): self.table_name = f'{book}_runline' self.db_control = db_control def commit_entry(self,site_data): write_session = scoped_session(self.db_control.create_session) insert_stmt = insert(self.check_table()).values(site_data) write_session.execute(insert_stmt) write_session.commit() write_session.remove()
{ "domain": "codereview.stackexchange", "id": 43797, "lm_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, sqlalchemy", "url": null }
python, sqlalchemy def check_table(self): metadata = MetaData(bind=self.db_control.engine) if self.table_name not in self.db_control.inspector.get_table_names(): table_name = Table( str(self.table_name), metadata, Column("team", String, primary_key=True), Column("event_id", Integer, primary_key=True), Column("odds", Integer), Column("line", Float), Column("book", String, primary_key=True), PrimaryKeyConstraint("event_id", "team", "book"), ) metadata.create_all(self.db_control.db_connection) logging.info(f'[DBControl]: {table_name} created') else: metadata.reflect(self.db_control.engine) logging.info(f'[DBControl]: {table_name} exists') return Table(table_name, metadata, autoload=True) class MoneylineControl: def __init__(self,book,db_control): self.table_name = f'{book}_moneyline' self.db_control = db_control def commit_entry(self,site_data): write_session = scoped_session(self.db_control.create_session) insert_stmt = insert(self.check_table()).values(site_data) write_session.execute(insert_stmt) write_session.commit() write_session.remove()
{ "domain": "codereview.stackexchange", "id": 43797, "lm_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, sqlalchemy", "url": null }
python, sqlalchemy def check_table(self): metadata = MetaData(bind=self.db_control.engine) if self.table_name not in self.db_control.inspector.get_table_names(): table_name = Table( str(self.table_name), metadata, Column("team", String, primary_key=True), Column("event_id", Integer, primary_key=True), Column("odds", Integer), Column("book", String, primary_key=True), PrimaryKeyConstraint("event_id", "team", "book"), ) metadata.create_all(self.db_control.db_connection) logging.info(f'[DBControl]: {table_name} created') else: metadata.reflect(self.db_control.engine) logging.info(f'[DBControl]: {table_name} exists') return Table(table_name, metadata, autoload=True) class TotalControl: def __init__(self,book,db_control): self.table_name = f'{book}_total' self.db_control = db_control def commit_entry(self,site_data): write_session = scoped_session(self.db_control.create_session) insert_stmt = insert(self.check_table()).values(site_data) write_session.execute(insert_stmt) write_session.commit() write_session.remove()
{ "domain": "codereview.stackexchange", "id": 43797, "lm_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, sqlalchemy", "url": null }
python, sqlalchemy def check_table(self): metadata = MetaData(bind=self.db_control.engine) if self.table_name not in self.db_control.inspector.get_table_names(): table_name = Table( str(self.table_name), metadata, Column("event_id", Integer, primary_key=True), Column("line", Float), Column("over", Integer), Column("under", Integer), Column("book", String, primary_key=True), PrimaryKeyConstraint("event_id", "book"), ) metadata.create_all(self.db_control.db_connection) logging.info(f'[DBControl]: {table_name} created') else: metadata.reflect(self.db_control.engine) logging.info(f'[DBControl]: {table_name} exists') return Table(table_name, metadata, autoload=True) class PropsControl: def __init__(self,book,db_control,prop): self.table_name = f'{book}_props{prop}' self.db_control = db_control def commit_entry(self,data): write_session = scoped_session(self.db_control.create_session) insert_stmt = insert(self.check_table()).values(data) write_session.execute(insert_stmt) write_session.commit() write_session.remove()
{ "domain": "codereview.stackexchange", "id": 43797, "lm_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, sqlalchemy", "url": null }
python, sqlalchemy def check_table(self): metadata = MetaData(bind=self.db_control.engine) if self.table_name not in self.db_control.inspector.get_table_names(): table_name = Table( str(self.table_name), metadata, Column("player", String, primary_key=True), Column("event_id", Integer, primary_key=True), Column("line", Float), Column("over", Integer), Column("under", Integer), Column("book", String, primary_key=True), PrimaryKeyConstraint("event_id", "player", "book"), ) metadata.create_all(self.db_control.db_connection) logging.info(f'[DBControl]: {table_name} created') else: metadata.reflect(self.db_control.engine) logging.info(f'[DBControl]: {table_name} exists') return Table(table_name, metadata, autoload=True) db_query.py from sqlalchemy import (Table, MetaData) class DBQuery: def __init__(self,books,db_control): self.books = books self.db_control = db_control self.session = self.db_control.create_session def gamelist(self,caesars_ids): meta = MetaData(self.db_control.engine) t1 = Table('mlb_gamelist', meta, autoload=True) t2 = Table('caesars_gamelist', meta, autoload=True) t3 = Table('fanduel_gamelist', meta, autoload=True) t4 = Table('draftkings_gamelist', meta, autoload=True) t5 = Table('pointsbet_gamelist', meta, autoload=True) t6 = Table('mgm_gamelist', meta, autoload=True)
{ "domain": "codereview.stackexchange", "id": 43797, "lm_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, sqlalchemy", "url": null }
python, sqlalchemy sess = self.session() data = sess.query( t1.c.event_id, t2.c.event_id, t3.c.event_id, t4.c.event_id, t5.c.event_id, t6.c.event_id ).join( t2 ).join( t3 ).join( t4 ).join( t5 ).join( t6 ) lst = [] for x in data: dic = {'caesars': caesars_ids.get(x[1]), 'fanduel': x[2], 'draftkings': x[3], 'pointsbet': x[4], 'mgm': x[5] } lst.append(dic) return lst app.py import logging from time import sleep from pprint import pprint from config import configs from extract.download import get_games, get_game from db.db_control import DBControl from db.db_query import DBQuery from pymlb.parse_games import GamesDict as MLBGamesDict from pycaesars.parse_games import GamesDict as CaesarsGamesDict from pycaesars.parse_game import GameDict as CaesarsGameDict from pyfanduel.parse_games import GamesDict as FanduelGamesDict from pyfanduel.parse_game import GameDict as FanduelGameDict from pydraftkings.parse_games import GamesDict as DraftkingsGamesDict from pypointsbet.parse_games import GamesDict as PointsbetGamesDict from pypointsbet.parse_game import GameDict as PointsbetGameDict from pymgm.parse_games import GamesDict as MGMGamesDict from pymgm.parse_game import GameDict as MGMGameDict from utils import delete_file if __name__ == "__main__": logging.basicConfig(level=logging.DEBUG) delete_file('games.db') booklist = [k for k,v in configs['books'].items() if v] logging.warning(f'[APP]: Retrieving GAMES data for {booklist}') games = get_games() db_control = DBControl()
{ "domain": "codereview.stackexchange", "id": 43797, "lm_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, sqlalchemy", "url": null }
python, sqlalchemy games = get_games() db_control = DBControl() if configs['books']['mlb']: MLBGamesDict(games,db_control) if configs['books']['caesars']: caesars = CaesarsGamesDict(games,db_control) caesars_ids = caesars.id_dict if configs['books']['fanduel']: FanduelGamesDict(games,db_control) if configs['books']['draftkings']: DraftkingsGamesDict(games,db_control) if configs['books']['pointsbet']: PointsbetGamesDict(games,db_control) if configs['books']['mgm']: MGMGamesDict(games,db_control) logging.info(f'[APP]: Retrieving GAME data') game = DBQuery(booklist,db_control).gamelist(caesars_ids) data = [] for event_ids in game: games = get_game(event_ids) data.append(games) sleep(1) if configs['books']['caesars']: CaesarsGameDict(data,db_control) if configs['books']['fanduel']: FanduelGameDict(data,db_control) if configs['books']['pointsbet']: PointsbetGameDict(data,db_control) if configs['books']['mgm']: MGMGameDict(data,db_control) parse_games.py REVISED class Parser: DISPLAY_NAME: str def __init__(self, dic): self._dic = dic[BOOK]['eventGroup'] self.events = self._dic.get('events',()) self.categories = self._dic.get('offerCategories',()) class Gamelist: DISPLAY_NAME = 'Gamelist' def __init__(self, events): self.events = events def to_dict(self): return [record for record in self.get_records()] def get_records(self): for event in self.events: if "@" in event['name']: yield from self.get_data(event)
{ "domain": "codereview.stackexchange", "id": 43797, "lm_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, sqlalchemy", "url": null }
python, sqlalchemy def get_data(self, event): book_id = endpoints.gamelist_book_id(event) away_abbr = endpoints.gamelist_away_abbr(event) home_abbr = endpoints.gamelist_home_abbr(event) game_ref = f'{away_abbr}@{home_abbr}' game_datetime = endpoints.gamelist_datetime(event) data = [book_id, game_ref, game_datetime] columns = ['book_id', 'game_ref', 'game_datetime'] return [dict(zip(columns,data))] class Category: def __init__(self, dic, category, subcategory, display_name): self.dic = dic self.category = category self.subcategory = subcategory self.display_name = display_name self.data = tuple(self.get_category()) def get_category(self): for item in self.dic: if item['offerCategoryId'] == self.category: yield from self.get_subcategory_description(item['offerSubcategoryDescriptors']) def get_subcategory_description(self, data): for item in data: if item['subcategoryId'] == self.subcategory: yield from self.get_subcategory(item['offerSubcategory'].get('offers')) def get_subcategory(self, data): for item in data: for x in item: if self.display_name in x.get('label',()) and x.get('isOpen',()): yield x class Runline: CATEGORY = 493 SUBCATEGORY = 4519 DISPLAY_NAME = 'Run Line' def __init__(self,data): self.data = Category(data, self.CATEGORY, self.SUBCATEGORY, self.DISPLAY_NAME).data def to_dict(self): return [record for record in self.get_records()] def get_records(self): for market in self.data: yield from self.get_data(market)
{ "domain": "codereview.stackexchange", "id": 43797, "lm_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, sqlalchemy", "url": null }
python, sqlalchemy def get_data(self, market): book_id = endpoints.runline_book_id(market) away_abbr = endpoints.runline_away_abbr(market) home_abbr = endpoints.runline_home_abbr(market) away_odds = endpoints.runline_away_odds(market) home_odds = endpoints.runline_home_odds(market) home_line = endpoints.runline_home_line(market) away = [book_id, away_abbr, away_odds, -home_line, BOOK] home = [book_id, home_abbr, home_odds, home_line, BOOK] columns = ['book_id', 'team', 'odds', 'line', 'book'] return [dict(zip(columns,away)), dict(zip(columns,home))] class Moneyline: CATEGORY = 493 SUBCATEGORY = 4519 DISPLAY_NAME = 'Moneyline' def __init__(self,data): self.data = Category(data, self.CATEGORY, self.SUBCATEGORY, self.DISPLAY_NAME).data def to_dict(self): return [record for record in self.get_records()] def get_records(self): for market in self.data: yield from self.get_data(market) def get_data(self, market): book_id = endpoints.moneyline_book_id(market) away_abbr = endpoints.moneyline_away_abbr(market) home_abbr = endpoints.moneyline_home_abbr(market) away_odds = endpoints.moneyline_away_odds(market) home_odds = endpoints.moneyline_home_odds(market) away = [book_id, away_abbr, away_odds, BOOK] home = [book_id, home_abbr, home_odds, BOOK] columns = ['book_id', 'team', 'odds', 'book'] return [dict(zip(columns,away)), dict(zip(columns,home))] class Total: CATEGORY = 493 SUBCATEGORY = 4519 DISPLAY_NAME = 'Total' def __init__(self,data): self.data = Category(data, self.CATEGORY, self.SUBCATEGORY, self.DISPLAY_NAME).data def to_dict(self): return [record for record in self.get_records()] def get_records(self): for market in self.data: yield from self.get_data(market)
{ "domain": "codereview.stackexchange", "id": 43797, "lm_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, sqlalchemy", "url": null }
python, sqlalchemy def get_data(self, market): book_id = endpoints.total_book_id(market) line = endpoints.total_line(market) over = endpoints.total_over(market) under = endpoints.total_under(market) data = [book_id, line, over, under, BOOK] columns = ['book_id', 'line', 'over', 'under', 'book'] return [dict(zip(columns,data))] ```
{ "domain": "codereview.stackexchange", "id": 43797, "lm_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, sqlalchemy", "url": null }
python, sqlalchemy Answer: Just... yikes, where to begin. Add PEP484 typehints. If you don't know what they are or why they're beneficial, do some Googling; but in short - a signature like def to_dict(self, markets): tells us nothing about what it actually accepts and only a guess as to what it returns. Type hints don't fix Python's broken type system (they never will), but they are a great deal better than nothing. Further to the above, a signature like def __init__(self, listofdics, db_control) accepts a listofdics (presumably : list[dict[???, ???]]). That tells us some - not enough - information about the type, and absolutely nothing about the contents. Is this games (a list of game dictionaries)? GamesDict as a class is not well-named. It isn't a dict. Call it perhaps GamesRepo, if that's what it actually is. Grammar - it's stat type -> its stat type; it's corresponding table -> its corresponding table. The OOP strategy followed in GamesDict is inappropriate. Your export_* functions set members such as self.gamelist that should actually only be local variables. Also, the sequence of calls to these export functions should not be done in the constructor; it should be a separate function called from the outside. Parser and its subclasses are also poor OOP: take _get_records_, _get_subcatdes and _get_subcat. These are all classmethods that accept the same parameter, data. It smells like data should be an instance member, and those should be parameter-less instance methods that refer to data through self. There is significant code repetition between Runline._get_data and Moneyline._get_data. This suggests that the common code should be pulled out to a common ancestor of these classes. A class like Total seems to have no actual instance data, and its _get_data returns an anonymous tuple. A more sensible pattern would be for _get_data to instantiate the class via cls(), with the anonymous tuple converted into a class instance with named parameters. By example, @dataclass class Total:
{ "domain": "codereview.stackexchange", "id": 43797, "lm_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, sqlalchemy", "url": null }
python, sqlalchemy @dataclass class Total: """ Class Total is a dedicated parser for total statistics. """ event_id: ??? line: ??? over: ??? under: ??? book: ??? CATEGORY: ClassVar[int] = 493 SUBCATEGORY: ClassVar[int] = 4519 DISPLAY_NAME: ClassVar[str] = 'Total' @classmethod def _get_data(cls, market: dict[str, Any]) -> 'Total': event_id = market['eventId'] away_team, home_team = market['outcomes'][:2] line = away_team['line'] over = away_team['oddsDecimal'] under = home_team['oddsDecimal'] return cls( (event_id, line, over, under, BOOK), )
{ "domain": "codereview.stackexchange", "id": 43797, "lm_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, sqlalchemy", "url": null }
python, sqlalchemy DBControl fails to close its connection and session. Convert it into a context manager whose __exit__ closes all resources that can be closed. You fail to show where scoped_session is imported from. I assume that this is sqlalchemy.orm.scoping.scoped_session. Your check_table pattern is fairly broken. SQLAlchemy is a complicated framework with a million and one ways for a beginner to shoot themselves in the foot. Your *Control classes should be converted into ORM classes that inherit from the declarative base. I strongly encourage you to do more reading and follow along with the official tutorial. When the dust settles, a query like this: meta = MetaData(self.db_control.engine) t1 = Table('mlb_gamelist', meta, autoload=True) t2 = Table('caesars_gamelist', meta, autoload=True) t3 = Table('fanduel_gamelist', meta, autoload=True) t4 = Table('draftkings_gamelist', meta, autoload=True) t5 = Table('pointsbet_gamelist', meta, autoload=True) t6 = Table('mgm_gamelist', meta, autoload=True) sess = self.session() data = sess.query( t1.c.event_id, t2.c.event_id, t3.c.event_id, t4.c.event_id, t5.c.event_id, t6.c.event_id ).join( t2 ).join( # ... must not re-declare the referenced Tables, and instead reference your ORM classes. Delete sleep(1).
{ "domain": "codereview.stackexchange", "id": 43797, "lm_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, sqlalchemy", "url": null }
bash, linux, networking Title: Find proceses listening on the network outside of default package manager v2 Question: So this is a follow up questions to Find proceses listening on the network outside of default package manager I managed to make it a little faster thanks to using /proc and hopefully managed to implement most of the suggestions. Some minor questions Can we get rid of the pipes in favor of here strings? I attempted but ran into issues Can we get rid of the custom readarray function? It takes too much space and is only used once. Was struggling to find a succinct replacement. As before the code needs to support bash 3.2+ so a lot of fancy features are unfortunately not available. As before it works just as intended Improved code #!/bin/bash # finds processes listening in on the network outside outside of the default package manager usage=$(cat <<-EOF $(basename "$0").sh [-h] [-f] [-a] [-w] [-v] [-p] Lists packages listening on the network outside of the default package manager where: -h, --help show this help text -f, --whitelist-file pick a file[s] containing whitelisted programs -w, --whitelist explicitly add whitelisted programs -W, --ignore-whitelist ignore the whitelist, includes env variables -v, --view-whitelist view the complete whitelist -p, --package-manager which package-manager to use (rpm, dkpg, ...) -P, --ignore-package-manager ignores the check for a working package manager output: COMMAND PATH PID USER FD TYPE DEVICE SIZE/OFF NODE NAME mattermos /app/main/mattermo 3351 361000 25u IPv4 84625698 0t0 TCP 129.240...(ESTABLISHED) examples: List all processes listening on the network usit_network_network_listening_processes --list-all List only packages not maintained by the central package manager system usit_network_network_listening_processes --list-all
{ "domain": "codereview.stackexchange", "id": 43798, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "bash, linux, networking", "url": null }
bash, linux, networking Whitelist some processes usit_network_network_listening_processes --whitelist mattermos,systemd usit_network_network_listening_processes --whitelist 'mattermos systemd' Whitelist some processes using whitelist files usit_network_network_listening_processes -f /etc/uio/uio_network_listening_processes_whitelist_01.txt Multiple whitelist files is supported usit_network_network_listening_processes --whitelist foo.txt,bar.txt environment variables: The following environment variables are available USIT_LISTENER_WHITELIST USIT_LISTENER_WHITELIST_FILES These form the base for the whitelist and whitelist files respectively. Use a string with spaces or comma [,] as seperator for the values. EOF ) fatal() { printf "ERROR: $*" >&2 exit 1 } # This is a substitute for readarray for older bash versions # https://stackoverflow.com/a/64793921/1048781 if ! type -t readarray >/dev/null; then # Very minimal readarray implementation using read. Does NOT work with lines that contain double-quotes due to eval() readarray() { local cmd opt t v=MAPFILE while [ -n "$1" ]; do case "$1" in -h|--help) echo "minimal substitute readarray for older bash"; exit; ;; -r) shift; opt="$opt -r"; ;; -t) shift; t=1; ;; -u) shift; if [ -n "$1" ]; then opt="$opt -u $1"; shift fi ;; *) if [[ "$1" =~ ^[A-Za-z_]+$ ]]; then v="$1" shift else echo -en "${C_BOLD}${C_RED}Error: ${C_RESET}Unknown option: '$1'\n" 1>&2 exit fi ;; esac done cmd="read $opt" eval "$v=()" while IFS= eval "$cmd line"; do line=$(echo "$line" | sed -e "s#\([\"\`]\)#\\\\\1#g" ) eval "${v}+=(\"$line\")" done } fi # Transform long options to short ones args=()
{ "domain": "codereview.stackexchange", "id": 43798, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "bash, linux, networking", "url": null }
bash, linux, networking # Transform long options to short ones args=() for arg; do case $arg in '--whitelist') args+=(-w) ;; '--whitelist-file') args+=(-f) ;; '--ignore-whitelist') args+=(-W) ;; '--ignore-package-manager') args+=(-P) ;; '--view-whitelist') args+=(-v) ;; '--package-manager') args+=(-p) ;; '--help') args+=(-h) ;; *) args+=("$arg") ;; esac done set -- "${args[@]}" # The '//,/ ' allows us to input variables using , seperator as well as SPACE whitelist=() whitelist_files=() read -ar whitelist <<< "${USIT_LISTENER_WHITELIST//,/ }" read -ar whitelist_files <<< "${USIT_LISTENER_WHITELIST_FILES//,/ }" view_whitelist=false ignore_whitelist=false ignore_package_manager=false while getopts ":w:f:p:vPWh" flag; do case "${flag}" in h) echo "$usage" exit 0 ;; v) view_whitelist=true ;; W) ignore_whitelist=true ;; P) ignore_package_manager=true ;; w) read -ra parts <<< "${OPTARG//,/ }" whitelist+=("${parts[@]}") ;; f) read -ra parts <<< "${OPTARG//,/ }" whitelist_files+=("${parts[@]}") ;; p) package_manager=${OPTARG} ;; \?) fatal "illegal option: -%s${OPTARG} \n\n$usage\n\n" ;; esac done
{ "domain": "codereview.stackexchange", "id": 43798, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "bash, linux, networking", "url": null }
bash, linux, networking # -i : This option filters only processes whith an IPv[46] address: # -P : This option inhibits the conversion of port numbers to port names for network files. # -n : This option inhibits the conversion of network numbers to host names for network files. # -l : This option inhibits the conversion of user ID numbers to login names. # +M : Enables the reporting of portmapper registrations for local TCP and UDP ports. # The awk filters only unique PID's by _[val] looks up val in the hash _(a regular variable). # NR > 1 is used to skip the header network_listening_processes=$( lsof -Pnl +M -i | awk 'NR>1 && !seen[$1]++ { print }' ) # we use the realpath -m to extract the execution path from the process id (pid) network_listening_processes_with_path=$( while read -r a pid b; do printf "%s %s %s %s\n" "$a" "'$(realpath -m /proc/"$pid"/exe)'" "$pid" "$b" done <<< "${network_listening_processes[@]}" ) if "${ignore_whitelist}" && "${ignore_package_manager}"; then echo "${network_listening_processes_with_path}" | column -t exit fi function is_in_array { local array="$1[@]" local seeking="${!2}" local result=1 for element in "${!array}"; do if [[ $element == "$seeking" ]]; then result=0 break fi done return $result } function is_empty_array { local array="$1[@]" for element in "${!array}"; do return 1 done return 0 } function print_array { local array="$1[@]" for element in "${!array}"; do echo "${element}" done }
{ "domain": "codereview.stackexchange", "id": 43798, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "bash, linux, networking", "url": null }
bash, linux, networking # Block of code for getting the correct package manager is_in_standard_repo_rpm() { rpm -qf "${1}" &>/dev/null } is_in_standard_repo_dpkg() { dpkg -S "${1}" &>/dev/null } is_in_standard_repo_any() { local package="${1}" return 1 } if "${ignore_package_manager}"; then package_manager="any" else dpkg_equivalents=("dpkg" "apt" "") rpm_equivalents=("rpm" "yum" "dnf" "") if is_in_array dpkg_equivalents package_manager && dpkg --version &>/dev/null; then package_manager="dpkg" elif is_in_array rpm_equivalents package_manager && rpm --version &>/dev/null; then package_manager="rpm" else fatal "No supported package manager found! Try specifying one with -p --package-manager" fi fi is_in_standard_repo () { is_in_standard_repo_$package_manager "${!1}" } # block of code for handling the whitelist if "${ignore_whitelist}"; then whitelist=() else if ! is_empty_array whitelist_files; then readarray -t whitelist_from_file < <(sort -u "${whitelist_files[@]}") whitelist+=("${whitelist_from_file[@]}") fi fi if "${view_whitelist}"; then ! is_empty_array whitelist && print_array whitelist exit fi # Finally we list every process not in the default packagen_manager # Which is listening on the network while IFS= read -r line; do programname=$(awk '{print $1}' <<< "${line}") path=$(awk '{print $2}' <<< "${line}") path_without_quotes=$(sed 's/^.\(.*\).$/\1/' <<< "${path}") if ! is_in_standard_repo path_without_quotes && ! is_in_array whitelist programname; then echo "${line}" fi done <<< "${network_listening_processes_with_path}" | column -t Answer: Use shellcheck shellcheck points out violations of good practices. Let me highlight just a few interesting ones, I recommend to review all. The variable package is unused. So you can delete the line. is_in_standard_repo_any() { local package="${1}" return 1 } Instead of: printf "ERROR: $*" >&2
{ "domain": "codereview.stackexchange", "id": 43798, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "bash, linux, networking", "url": null }
bash, linux, networking Instead of: printf "ERROR: $*" >&2 The recommended form is: printf "ERROR: %s" "$*" >&2 Note that printf doesn't print a newline by default. I think that's not good UX when the output of a script ends without a newline. You could add a \n there, but then this is really the same as what a simpler echo does, so I would just do: echo "$*" >&2 ... and there are even more, I suggest to review and address them all. Do not construct Bash function names using string concatenation This is a dirty hack: is_in_standard_repo () { is_in_standard_repo_$package_manager "${!1}" } On my first pass, I was looking for usages of is_in_standard_repo_rpm and I couldn't find it, because the function name is constructed from string parts. Confusing. As I recommended for the previous iteration, it would be better to use is_in_standard_repo as a variable, assign to it the function that should be called, and then call the function using "$is_in_standard_repo" ARGS.... Avoid indirect expansion when possible The array helper functions rely heavily on indirect expansion, that is, the ${!name} construct to refer to the variable named by $name. I find it confusing, and I would only use it as a last resort. shellcheck is also not able to handle this well, for example it reports rpm_equivalents as unused, even though it is used, with indirect expansion. You can avoid it by reworking the array helpers to take variable contents directly. Let's take for example is_in_array. Instead of taking: the name of an array to search in the name of the variable whose value to search for Make it work with: a value to search for as first argument the array elements as the remaining elements Like this: is_in_array() { local seeking=$1 shift for element; do if [[ $element == "$seeking" ]]; then return fi done return 1 } This will make the calls slightly longer: is_in_array "$package_manager" "${rpm_equivalents[@]}"
{ "domain": "codereview.stackexchange", "id": 43798, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "bash, linux, networking", "url": null }
bash, linux, networking This will make the calls slightly longer: is_in_array "$package_manager" "${rpm_equivalents[@]}" But I think it's much easier to understand the code, and this also resolve the shellcheck issues. Avoid flag variables when possible Flag variables, that are set during a loop and then acted on later are error prone. For example they might get accidentally overwritten, or not acted on at all. For example the result variable in this code: local result=1 for element in "${!array}"; do if [[ $element == "$seeking" ]]; then result=0 break fi done return $result You can avoid the flag variable by acting immediately: for element in "${!array}"; do if [[ $element == "$seeking" ]]; then return 0 fi done return 1 Although I wrote an explicit return 0, a simple return would be equivalent. Use pipes instead of storing command outputs for one-time use The network_listening_processes and network_listening_processes_with_path variables store the output of commands, and they are used only once per execution path. You could make them functions, call them when they are needed, and pipe the result for further processing: network_listening_processes() { lsof -Pnl +M -i | awk 'NR > 1 && !seen[$1]++' ) network_listening_processes_with_path() { network_listening_processes | while read -r a pid b; do printf "%s %s %s %s\n" "$a" "'$(realpath -m /proc/"$pid"/exe)'" "$pid" "$b" done ) if "${ignore_whitelist}" && "${ignore_package_manager}"; then network_listening_processes_with_path | column -t exit fi # ... network_listening_processes_with_path | while IFS= read -r line; do # ... done | column -t Read pair of variables from lines Instead of: while IFS= read -r line; do programname=$(awk '{print $1}' <<< "${line}") path=$(awk '{print $2}' <<< "${line}") # ... done
{ "domain": "codereview.stackexchange", "id": 43798, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "bash, linux, networking", "url": null }