body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I'm learning Python and would appreciate any (and all) feedback to improve myself.</p>
<p>input/output example:</p>
<pre><code>>>> list_of_words = ['deltas', 'retainers', 'desalt', 'pants', 'slated', 'generating', 'ternaries', 'smelters', 'termless', 'salted', 'staled', 'greatening', 'lasted', 'resmelts']
>>> sort_anagrams(list_of_words)
[['deltas', 'desalt', 'slated', 'salted', 'staled', 'lasted'], ['retainers', 'ternaries'], ['pants'], ['generating', 'greatening'], ['smelters', 'termless', 'resmelts']]
</code></pre>
<p>Here is the code I wrote, it worked well for the above list. Looking for feedback on complexity, overall design, readability and any other thing that pops to mind when reviewing, thanks!</p>
<pre><code># process list of strings, construct nested list of anagrams.
list_of_strings = ['deltas', 'retainers', 'desalt', 'pants', 'slated', 'generating', 'ternaries', 'smelters', 'termless', 'salted', 'staled', 'greatening', 'lasted', 'resmelts']
list_of_lists = []
temp_list = []
def sort_anagrams(list_of_strings):
if len(list_of_strings) > 1:
temp_list = [list_of_strings[0]] # create temp list to be eventually appended to main list
popped_list = list_of_strings # list of anagrams to remove from source list after iteration, without deleting source list
popped_list.pop(0) # remove the first item as it's already in the temp_list
strings_to_pop = []
for string in popped_list:
if sorted(string) == sorted(temp_list[0]):
temp_list.append(string) # passing anagram test so append to temp_list
strings_to_pop.append(string) # create list of items to remove popped_list
list_of_lists.append(temp_list) # append temp_list as a list element
for string in strings_to_pop:
popped_list.remove(string) # remove all strings that were deemed anagram to remove possible duplications
sort_anagrams(popped_list) # running the function again on list remainder
elif len(list_of_strings) == 1:
temp_list.append(list_of_strings[0])
list_of_strings.pop(0)
list_of_lists.append(temp_list) # append temp_list as a list element
sort_anagrams(popped_list)
else:
print('you have reached the end and sorted all anagrams. here is the list of anagram lists: \n \n', list_of_lists)
sort_anagrams(list_of_strings)
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>I think a much simpler approach would be beneficial to you here, as well as if you were to utilize a dictionary to hold the results as you go along. The below code does not make use of recursion though, so if you were trying to learn about recursion in python then this would not help. But if you're just trying to learn what a simple and pythonic function to solve this problem would look like then I think this will help you. Notably it is much less code, easier to reason about, and does not make use of global variables.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def sort_anagrams2(list_of_strings):\n result = {}\n\n for string in list_of_strings:\n sorted_string = "".join(sorted(string))\n\n if sorted_string in result:\n result[sorted_string].append(string)\n else:\n result[sorted_string] = [string]\n\n return list(result.values())\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T16:02:49.253",
"Id": "484280",
"Score": "1",
"body": "If they were trying to learn about recursion, they picked the wrong problem :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T14:09:43.220",
"Id": "484387",
"Score": "1",
"body": "Yes I was hoping to get something along the more pythonic line, I had a feeling this wasn't the best approach :) thanks a lot for the feedback!!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T15:34:54.027",
"Id": "247441",
"ParentId": "247372",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-02T07:12:13.543",
"Id": "247372",
"Score": "2",
"Tags": [
"python",
"recursion"
],
"Title": "Python recursive function that receives list of strings, and returns a nested list of anagrams"
}
|
247372
|
<p>I need to run over all the IP addresses on the CIDR <code>10.96.0.0/12</code> network.<br />
There are <code>1,048,574</code> IP addresses.</p>
<p>I created a multi threaded program in Go to do it, but even when I use 100 threads it takes lots of time (didn't check exactly but it is more than 10 minutes).</p>
<p>Is there are way I can do it more efficient?<br />
By the way, on Windows it takes couple of minutes but I did also test on container in Linux and it took 40 seconds to scan 500K IP addresses. But let me know if you have faster way to check it.</p>
<p>My program:</p>
<pre><code>package main
import (
"fmt"
"log"
"net"
)
func getIPAddresses(cidr string) ([]string, error) {
ip, ipnet, err := net.ParseCIDR(cidr)
if err != nil {
return nil, err
}
var ips []string
for ip := ip.Mask(ipnet.Mask); ipnet.Contains(ip); inc(ip) {
ips = append(ips, ip.String())
}
// remove network address and broadcast address
lenIPs := len(ips)
var ipAddresses []string
switch {
case lenIPs < 2:
ipAddresses = ips
default:
// Shouldn't be panic here because we are checking the lenIPs before
ipAddresses = ips[1 : len(ips)-1]
}
return ipAddresses, nil
}
// http://play.golang.org/p/m8TNTtygK0
func inc(ip net.IP) {
for j := len(ip) - 1; j >= 0; j-- {
ip[j]++
if ip[j] > 0 {
break
}
}
}
func main() {
ipAddresses, err := getIPAddresses("10.96.0.0/12")
if err != nil {
log.Fatal(err)
}
fmt.Printf("[*] Scanning %d IP addresses\n", len(ipAddresses))
//var hostsMap map[string][]string
//l := sync.Mutex{}
threads := 100
sem := make(chan bool, threads)
count := 0
for _, ip := range(ipAddresses) {
sem <- true
go func(ip string) {
count += 1
if count % 1000 == 0 {
fmt.Printf("Scan: %d addresses\n", count)
}
_, err := net.LookupAddr(ip)
if err != nil {
//log.Fatal(err)
//fmt.Println("Error")
}
<- sem
}(ip)
}
for i := 0; i < cap(sem); i++ {
sem <- true
}
fmt.Println("DONE")
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-02T08:36:47.400",
"Id": "484130",
"Score": "0",
"body": "Why did you decide to multithread it ? Were you sure that the CPU is the bottleneck, not the IO?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-02T08:39:24.583",
"Id": "484131",
"Score": "2",
"body": "Because the function `net.LookupAddr()` need to send DNS request which means it is a network I/O and it takes time (not too much). When I comment the `net.LookupAddr()` function it finish to pass all the IPs in 2 seconds."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-02T08:45:04.550",
"Id": "484132",
"Score": "0",
"body": "Every run of `net.LookupAddr()` takes me 1 millisecond on average."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-02T15:44:43.953",
"Id": "484160",
"Score": "1",
"body": "Is this a network that you own/control ? I would guess that the answer is yes. Then you should be able to get a copy of the zone file and use it as a lookup source. The information that you want has to be available in some form, thus the mass lookup looks wasteful to me. PS: not familiar with the GO language but implementation on Windows differs than Linux - see the Name Resolution section [here](https://golang.org/pkg/net/)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T11:42:10.347",
"Id": "484369",
"Score": "0",
"body": "`Every run of net.LookupAddr() takes me 1 millisecond on average` How do you assert that ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T13:31:58.260",
"Id": "484380",
"Score": "0",
"body": "I created a loop that run 1000 times and every run it open a timer with `start := time.Now()`, run the `net.LookupAddr()` and when it finish I calculate the time with `elapsed := time.Since(start)` and print it. I saw that on average it was 990~ microsecond which are almost 1 millisecond."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-02T07:40:23.027",
"Id": "247373",
"Score": "4",
"Tags": [
"multithreading",
"go",
"ip-address"
],
"Title": "Running DNS lookup over million IP addresses"
}
|
247373
|
<h1>Context of the Problem</h1>
<p>I am running a discrete event simulation where at the end of each event I store the state of the system in a row of a dataframe. Each simulation run has a clock which determines which events are run and when, all the simulation have the same initial clock (0) and the same end clock (simulation end). but the number of rows for the dataframes may be different because the simulation has several stochastic components. The clock column is then converted to timestamp and use as index of the dataframe.</p>
<p>Whenever one does a simulation, it is good practice to run it many times and then average over all the replicates, doing so in this setup is a bit complicated because each simulation produced a dataframe which different indexes.</p>
<h1>Proposed Solution</h1>
<p>So far this is the solution I found:</p>
<pre><code># Auxiliary functions
def get_union_index(dfs):
index_union = dfs[0].index
for df in dfs[1:]:
index_union = index_union.union(df.index)
return pd.Series(index_union).drop_duplicates().reset_index(drop=True)
def interpolate(df, index, method='time'):
aux = df.astype(float)
aux = aux.reindex(index).interpolate(method=method).fillna(method='ffill').fillna(method='bfill')
return aux
# Simulation
dfs = []
replicates = 30
seeds = list(range(40, 40 + replicates))
dfs = [simulate(seed=seed, **parameters) for seed in seeds]
# Main Code
union_index = get_union_index(dfs)
dfs_interpolates = [interpolate(df, union_index) for df in dfs]
df_concat = pd.concat(dfs_interpolates)
by_row_index = df_concat.groupby(df_concat.index)
# Averaging
df_means = by_row_index.mean()
df_std = by_row_index.std()
</code></pre>
<h2>Explanation</h2>
<p>First, it is necessary to combine all the indexes, then this combined index is used to re-index all the dataframes and the <code>nan</code> values are filled using interpolation.</p>
<h2>Questions</h2>
<ol>
<li><p>Is there a native pandas function that could simplify this?</p>
</li>
<li><p>(If not 1) Is there an alternative way to combine the datasets directly, since the majority of the index are disjoint, <code>union_index</code> has a length of approximately <code>len(df) * len(dfs)</code> which is actually huge.</p>
</li>
<li><p>Which should be the best interpolation method to use in the <code>interpolate</code>? Since each row is an event and only a few variables are changed per event, from one row to the next only a few columns are modified, making it possible to have several consecutive rows with identical values in several columns (but not all).</p>
</li>
</ol>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-02T11:07:54.053",
"Id": "247376",
"Score": "1",
"Tags": [
"python",
"pandas"
],
"Title": "Interpolation across different dataframes with Pandas"
}
|
247376
|
<p>I have implemented some meta functions to create sequence for exponents of 2. I would love to know if there is any way to make the code more optimized.</p>
<p>Note: <code>int main()</code> should not be modified. From the requirements of my school:</p>
<blockquote>
<p>This program must implement three definitions: <code>sequence<Ts...></code>, <code>print()</code> and <code>printing_type()</code>.</p>
</blockquote>
<p>Hence, the name of functions should not be modified.</p>
<pre><code>#include<iostream>
template<size_t... Ts>
struct int_seq{};
template<size_t TCount, size_t...Ts>
struct sequence
{
using type = typename sequence<TCount - 1, 1, (2 * Ts)...>::type;
};
template<size_t...Ts>
struct sequence<0, Ts...>
{
using type = int_seq<Ts...>;
};
template<size_t TCount>
using create_int_seq = typename sequence<TCount + 1>::type;
template <typename T>
void print(T val)
{
std::cout << val << " ";
}
template <typename T, typename... Ts>
void print(T val, Ts... t)
{
std::cout << val << " ";
print(t...);
}
template <
template <size_t...> class T,
size_t... S
>
void printing_type(T<S...>)
{
print(S...);
}
int main()
{
constexpr size_t N = 63;
create_int_seq<N> dum{};
printing_type(dum);
}
</code></pre>
|
[] |
[
{
"body": "<p>Certainly your definitions of <code>printing_type</code> and <code>print</code> could be shortened. You're currently doing</p>\n<pre><code>print(t...) // print(a,b,c,d)\n</code></pre>\n<p>but what you actually want to happen is</p>\n<pre><code>print(t)... // print(a), print(b), print(c), print(d)\n</code></pre>\n<p>So then you have to do a bunch of extra work to transform the former into the latter. Instead of all that extra work, you could just write</p>\n<pre><code>void print(size_t val) {\n std::cout << val << " ";\n}\n\ntemplate<template<size_t...> class T, size_t... S>\nvoid printing_type(T<S...>) {\n (print(S) , ...);\n}\n</code></pre>\n<p>Notice that the single-argument <code>print</code> doesn't have to be a template, because <code>val</code> is always a <code>size_t</code>.</p>\n<p>In fact, we can inline <code>print</code> into <code>printing_type</code> if we want:</p>\n<pre><code>template<template<size_t...> class TT, size_t... Values>\nvoid printing_type(TT<Values...>) {\n ((std::cout << Values << " ") , ...);\n}\n</code></pre>\n<p>The <code>(ts , ...)</code> syntax is a C++17 fold-expression. If you aren't on C++17, then you can use an initializer list to accomplish the same thing:</p>\n<pre><code>template<template<size_t...> class TT, size_t... Values>\nvoid printing_type(TT<Values...>) {\n int dummy[] = {\n ((std::cout << Values << " "), 0) ...\n };\n}\n</code></pre>\n<hr />\n<p>Your definition for <code>sequence</code> is pretty confusing. Your code could benefit from some <em>unit tests</em>. Compile-time unit tests are easy:</p>\n<pre><code>static_assert(std::is_same<create_int_seq<0>, int_seq<1>>::value, "");\nstatic_assert(std::is_same<create_int_seq<1>, int_seq<1,2>>::value, "");\nstatic_assert(std::is_same<create_int_seq<2>, int_seq<1,2,4>>::value, "");\nstatic_assert(std::is_same<create_int_seq<3>, int_seq<1,2,4,8>>::value, "");\nstatic_assert(std::is_same<create_int_seq<4>, int_seq<1,2,4,8,16>>::value, "");\n</code></pre>\n<p>As a bonus, these five lines serve as excellent documentation about what this code does... to the extent that I no longer mind the lack of code comments explaining <em>how</em> it might work.</p>\n<p>FWIW, if I wanted to make these test cases pass, I'd implement <code>create_int_seq</code> like this:</p>\n<pre><code>template<class> struct powers_of_two;\ntemplate<size_t... Is>\nstruct powers_of_two<std::index_sequence<Is...>> {\n using type = int_seq<(size_t(1) << Is)...>;\n};\n\ntemplate<size_t N>\nusing create_int_seq =\n typename powers_of_two<std::make_index_sequence<N+1>>::type;\n</code></pre>\n<p>Relevant blog post of mine: <a href=\"https://quuxplusone.github.io/blog/2018/07/23/metafilter/\" rel=\"noreferrer\">"Template metaprogramming: Iteration is better than recursion"</a> (July 2018).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-02T16:45:25.137",
"Id": "484164",
"Score": "0",
"body": "Man, you blow me away with those changes! Thank you so so much. Still trying to take it in. And yes, I am using c++14 currently for this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-02T17:26:18.110",
"Id": "484169",
"Score": "0",
"body": "Hi @Quuxplusone, I need to retain both print() and printing_type meta functions, and since I am using c++14, is there another optimize way instead of using the initializer list method as you have mentioned for c++14, such that I am able to use both print() and printing_type functions at the same time. And, FYI, the compiler has issued a warning being treated as error that the \"dummy\" variable isn't used. Hope to hear more from you. Thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T01:50:10.623",
"Id": "484192",
"Score": "1",
"body": "Re unused variable `dummy`: Add `(void)dummy;` in the body of that function.\nRe needing to keep some function named `print`: Add `void print() {}` :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-02T16:36:06.847",
"Id": "247386",
"ParentId": "247379",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "247386",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-02T14:32:37.080",
"Id": "247379",
"Score": "5",
"Tags": [
"c++",
"c++14",
"template-meta-programming",
"variadic"
],
"Title": "Meta functions for sequences of exponents of 2"
}
|
247379
|
<p>I wanted to learn C and Win32 so I thought the best way to start would be to create a simple game to get familiar with the language, so I made Snake. The games works perfectly except for sometimes seeing the game window flash for a split second, don't know what causes it.</p>
<p>Code:</p>
<pre><code>#include <stdio.h>
#include <windows.h>
#define TIMER_MAIN 42069
HWND gameWindow;
HFONT gameFont;
int timeElapsed = 0;
int direction = 0;
int length = 0;
int width, height, bSize, snakeThinness;
POINT* playerHistory;
POINT playerLocation = { 0 };
POINT fruitLocation = { 0 };
void Die(int errorCode)
{
if (gameFont)
DeleteObject(gameFont);
char error[6][64] = { "Finished program execution",
"Could not register window class",
"Could not create window",
"Win32 Error",
"Player direction is outside 2D space",
"" };
LPVOID lpMsgBuf;
DWORD dw = GetLastError();
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, NULL);
printf("Halting: (0x%08x) %s\r\nWIN 0x%08x / %s", errorCode, error[errorCode], dw, (LPCSTR)lpMsgBuf);
exit(errorCode);
}
void GameInit(int w, int h, int bS)
{
printf("%s\n", "Initiating game variables...");
width = w;
height = h;
bSize = bS;
snakeThinness = bSize / 10;
timeElapsed = 0;
direction = 0;
length = 0;
playerLocation.x = 4;
playerLocation.y = 4;
while (1)
{
fruitLocation.x = rand() % width;
fruitLocation.y = rand() % height;
if (fruitLocation.x == playerLocation.x && fruitLocation.y == playerLocation.y)
continue;
else
break;
}
RECT rc, rcClient;
GetWindowRect(gameWindow, &rc);
GetClientRect(gameWindow, &rcClient);
int xExtra = rc.right - rc.left - rcClient.right - rcClient.left;
int yExtra = rc.bottom - rc.top - rcClient.bottom - rcClient.top;
SetWindowPos(gameWindow, NULL, NULL, NULL, (width * bSize) + xExtra, (height * bSize) + yExtra, SWP_NOMOVE | SWP_NOZORDER | SWP_NOCOPYBITS);
}
void GameLoop()
{
int lastX = playerLocation.x;
int lastY = playerLocation.y;
switch (direction)
{
//0 == right
//1 == bottom
//2 == left
//3 == top
case 0:
playerLocation.x++;
if (playerLocation.x > width)
playerLocation.x = 0;
break;
case 1:
playerLocation.y++;
if (playerLocation.y > height)
playerLocation.y = 0;
break;
case 2:
playerLocation.x--;
if (playerLocation.x < 0)
playerLocation.x = width;
break;
case 3:
playerLocation.y--;
if (playerLocation.y < 0)
playerLocation.y = height;
break;
default:
Die(4);
}
POINT p;
p.x = lastX;
p.y = lastY;
if (fruitLocation.x == playerLocation.x && fruitLocation.y == playerLocation.y)
{
length++;
if (playerHistory != 0)
{
POINT* playerHistory2 = (POINT*) malloc(length * sizeof(POINT));
//memcpy(playerHistory2 + sizeof(POINT), playerHistory, (length - 1) * sizeof(POINT));
for (int i = 0; i < length - 1; i++)
playerHistory2[i + 1] = playerHistory[i];
playerHistory2[0] = p;
free(playerHistory);
playerHistory = playerHistory2;
}
else
{
playerHistory = (POINT*) malloc(length * sizeof(POINT));
}
if (length == 1)
{
playerHistory[0] = p;
}
while (1)
{
fruitLocation.x = rand() % width;
fruitLocation.y = rand() % height;
if (fruitLocation.x == playerLocation.x && fruitLocation.y == playerLocation.y)
continue;
int t = 0;
for (int i = 0; i < length; i++)
if (fruitLocation.x == playerHistory[i].x && fruitLocation.y == playerHistory[i].y)
t = 1;
if (t == 0)
break;
}
}
else if (playerHistory != 0)
{
POINT* playerHistory2 = (POINT*) malloc(length * sizeof(POINT));
//memcpy(playerHistory2 + sizeof(POINT), playerHistory, (length - 1) * sizeof(POINT));
for (int i = 0; i < length - 1; i++)
playerHistory2[i + 1] = playerHistory[i];
playerHistory2[0] = p;
free(playerHistory);
playerHistory = playerHistory2;
}
int willDie = 0;
for (int i = 0; i < length; i++)
if (playerLocation.x == playerHistory[i].x && playerLocation.y == playerHistory[i].y)
willDie = 1;
if (willDie == 1)
GameInit(width, height, bSize);
}
LRESULT CALLBACK MainWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_CREATE:
MessageBox(hwnd, "Window succesfully created", "Succes", MB_OK);
ShowWindow(hwnd, SW_SHOW);
SetTimer(hwnd, TIMER_MAIN, 375, (TIMERPROC) NULL);
return 0;
case WM_TIMER:
switch (wParam)
{
case TIMER_MAIN:
timeElapsed++;
GameLoop();
RedrawWindow(hwnd, NULL, NULL, RDW_INVALIDATE);
return 0;
}
return 0;
case WM_PAINT:
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
RECT rect;
//Clear screen
rect.left = 0;
rect.right = width * bSize;
rect.top = 0;
rect.bottom = height * bSize;
FillRect(hdc, &rect, GetStockObject(BLACK_BRUSH));
//Draw fruit
rect.left = fruitLocation.x * bSize;
rect.right = (fruitLocation.x + 1) * bSize;
rect.top = fruitLocation.y * bSize;
rect.bottom = (fruitLocation.y + 1) * bSize;
FillRect(hdc, &rect, GetStockObject(GRAY_BRUSH));
//Draw player tail
int lastX = playerLocation.x;
int lastY = playerLocation.y;
for (int i = 0; i < length; i++)
{
int doNormal = 0;
int compare1, compare2;
if (lastY == playerHistory[i].y)
{
compare1 = playerHistory[i].x;
compare2 = lastX;
}
else
{
compare1 = playerHistory[i].y;
compare2 = lastY;
}
if (abs(compare1 - compare2) == 1)
{
if (compare1 < compare2)
{
rect.left = (playerHistory[i].x * bSize) + snakeThinness;
rect.right = ((lastX + 1) * bSize) - snakeThinness;
rect.top = (playerHistory[i].y * bSize) + snakeThinness;
rect.bottom = ((lastY + 1) * bSize) - snakeThinness;
}
else
{
rect.left = (lastX * bSize) + snakeThinness;
rect.right = ((playerHistory[i].x + 1) * bSize) - snakeThinness;
rect.top = (lastY * bSize) + snakeThinness;
rect.bottom = ((playerHistory[i].y + 1) * bSize) - snakeThinness;
}
}
else
doNormal = 1;
if (doNormal)
{
rect.left = (playerHistory[i].x * bSize) + snakeThinness;
rect.right = ((playerHistory[i].x + 1) * bSize) - snakeThinness;
rect.top = (playerHistory[i].y * bSize) + snakeThinness;
rect.bottom = ((playerHistory[i].y + 1) * bSize) - snakeThinness;
}
lastX = playerHistory[i].x;
lastY = playerHistory[i].y;
FillRect(hdc, &rect, CreateSolidBrush(RGB(0,255,0)));
}
//Draw player
rect.left = playerLocation.x * bSize;
rect.right = (playerLocation.x + 1) * bSize;
rect.top = playerLocation.y * bSize;
rect.bottom = (playerLocation.y + 1) * bSize;
FillRect(hdc, &rect, GetStockObject(WHITE_BRUSH));
rect.left = 0;
rect.right = width * bSize;
rect.top = 0;
rect.bottom = 30;
SelectObject(hdc, gameFont);
SetTextColor(hdc, RGB(128, 128, 128));
SetBkMode(hdc, TRANSPARENT);
int strLen = snprintf(NULL, 0, "%i", length);
char* str = malloc(sizeof(char) * (strLen + 1 + 7));
sprintf(str, "Score: %i", length);
DrawText(hdc, str, -1, &rect, DT_CENTER);
EndPaint(hwnd, &ps);
return 0;
case WM_SIZE:
return 0;
case WM_DESTROY:
Die(0);
return 0;
case WM_KEYDOWN:
if ((lParam & 0x40000000) == 0)
{
switch (wParam)
{
case VK_RIGHT:
if (direction != 2)
direction = 0;
return;
case VK_DOWN:
if (direction != 3)
direction = 1;
return;
case VK_LEFT:
if (direction != 0)
direction = 2;
return;
case VK_UP:
if (direction != 1)
direction = 3;
return;
}
}
return 0;
default:
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
return 0;
}
int main()
{
printf("%s\n", "Starting...");
HINSTANCE module = GetModuleHandle(NULL);
WNDCLASSEX wndClass = { 0 };
wndClass.cbSize = sizeof(WNDCLASSEX);
wndClass.style = NULL;
wndClass.lpfnWndProc = (WNDPROC) MainWndProc;
wndClass.cbClsExtra = NULL;
wndClass.cbWndExtra = NULL;
wndClass.hInstance = module;
wndClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wndClass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndClass.hbrBackground = GetStockObject(LTGRAY_BRUSH);
wndClass.lpszMenuName = "";
wndClass.lpszClassName = "MainWindowClass";
if (!RegisterClassEx(&wndClass))
Die(1);
gameWindow = CreateWindowEx(WS_EX_CLIENTEDGE, "MainWindowClass", "CSnake", WS_CAPTION | WS_SYSMENU, CW_USEDEFAULT, CW_USEDEFAULT, 460, 460, NULL, NULL, module, NULL);
if (gameWindow == NULL)
Die(2);
gameFont = CreateFont(28, 0, 0, 0, 400, FALSE, FALSE, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, OUT_DEFAULT_PRECIS, DEFAULT_PITCH, "Comic Sans MS");
GameInit(20, 20, 20);
MSG msg;
BOOL bRet;
while (1)
{
bRet = GetMessage(&msg, NULL, 0, 0);
if (bRet > 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else if (bRet < 0)
{
Die(3);
}
else
{
Die(0);
}
}
return msg.wParam;
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-02T14:56:16.780",
"Id": "247380",
"Score": "4",
"Tags": [
"c",
"windows",
"winapi"
],
"Title": "Basic snake game in C"
}
|
247380
|
<p>I'm rehashing some of the basics of c++ and I just want to find useful points along the way of things I can do to improve my coding.</p>
<p>This program has the user enter a number, then the computer try to guess it, with some higher/lower logic.</p>
<pre><code>#include <iostream>
#include <cstdlib>
#include <ctime>
int main()
{
srand(static_cast<unsigned int>(time(0))); //seed random number generator
int secretNumber = 0;
int tries = 0;
int guess;
int highRange = 100;
int lowRange = 0;
std::cout << "\tWelcome to Guess My Number\n\n";
std::cout << "\tPlease enter your number between 1 and 100:\n";
std::cin >> secretNumber;
do
{
do
guess = rand() % highRange + 1;
while (guess <= lowRange);
++tries;
if (guess > secretNumber)
{
std::cout << "Computer guess was too high! (" << guess << ")\n\n";
highRange = guess;
}
else if (guess < secretNumber)
{
std::cout << "Computer guess was too low! (" << guess << ")\n\n";
lowRange = guess;
}
else
{
std::cout << "\nI guessed it! (" << guess << ") in " << tries << " guesses!\n";
}
} while (guess != secretNumber);
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>You can simplify this:</p>\n<pre><code> do\n guess = rand() % highRange + 1;\n while (guess <= lowRange);\n</code></pre>\n<p>Why not get a value in the correct range then add lowRange.</p>\n<pre><code> // I did not check the maths there\n // may be an off by one error in this\n // Please verify the range is correct.\n guess = rand() % (highRange + 1 - lowRange);\n guess += lowRange;\n</code></pre>\n<p>I am not complain about you using <code>rand()</code> in this extremely simple example code. But you should note that:</p>\n<ul>\n<li><code>rand()</code> is not very random.</li>\n<li><code>rand() % x</code> not all values in the range [0-x) are equally probably.</li>\n</ul>\n<p>Please have a look at the C++ standard random number generator (you are using the C version).</p>\n<p><a href=\"http://www.cplusplus.com/reference/random/\" rel=\"nofollow noreferrer\">http://www.cplusplus.com/reference/random/</a></p>\n<hr />\n<p>You use the correct C++ header files:</p>\n<pre><code>#include <cstdlib>\n#include <ctime>\n</code></pre>\n<p>This puts all the functionality in the <code>std</code> namespace. Though it allows implementations to also add a definition in the global namespace (though this is optional). But this optional bit is what allows it to compile on your system (but you can't assume it would work everywhere).</p>\n<p>So the functions you use should be prefixed with <code>std::</code>.</p>\n<pre><code>std::srand(static_cast<unsigned int>(std::time(0)));\n^^^^^ ^^^^^\n\n....\nstd::rand() % highRange\n^^^^^\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T08:20:07.983",
"Id": "484213",
"Score": "0",
"body": "This is such a great answer! I'm going to fix this up tonight with your suggestions - how is best to submit improved versions here?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-02T17:33:41.587",
"Id": "247392",
"ParentId": "247383",
"Score": "6"
}
},
{
"body": "<pre><code> int highRange = 100;\n int lowRange = 0;\n</code></pre>\n<p>Mark them <code>const</code>. Then the reader doesn't need to check the whole code to see if these numbers are modified or not.</p>\n<blockquote>\n<p>Immutable objects are easier to reason about, so make objects non-const only when there is a need to change their value. Prevents accidental or hard-to-notice change of value.</p>\n</blockquote>\n<ul>\n<li><a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rconst-immutable\" rel=\"nofollow noreferrer\">https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rconst-immutable</a></li>\n</ul>\n<hr>\n<pre><code>std::cout << "\\tWelcome to Guess My Number\\n\\n";\n\nstd::cout << "\\tPlease enter your number between 1 and 100:\\n";\n\nstd::cin >> secretNumber;\n</code></pre>\n<p>Since you need the statements asking for input to appear in the console <em>definitely</em> before you start reading for input, use <code>std::endl</code>. That will force a buffer flush to the console.</p>\n<p>If you read that this affects performance, try to guess (<code>:)</code>) how much would the cost be compared to a human entering a number and hitting enter.</p>\n<hr>\n<pre><code>std::cin >> secretNumber;\n</code></pre>\n<p>Since secretNumber is going to remain a constant for the rest of the program, use a lambda to store it.</p>\n<pre><code>const int secretNumer = [](){\n int n;\n std::cin >> n;\n return n;\n}();\n</code></pre>\n<p>Sorry I don't know a better way to return a number read from stream.</p>\n<blockquote>\n<p>It nicely encapsulates local initialization, including cleaning up scratch variables needed only for the initialization, without needing to create a needless non-local yet non-reusable function. It also works for variables that should be const but only after some initialization work.</p>\n</blockquote>\n<ul>\n<li><a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Res-lambda-init\" rel=\"nofollow noreferrer\">https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Res-lambda-init</a></li>\n</ul>\n<hr>\n<p>Avoid <code>do</code> statements</p>\n<blockquote>\n<p>Readability, avoidance of errors. The termination condition is at the end (where it can be overlooked) and the condition is not checked the first time through.</p>\n</blockquote>\n<p>There is no benefit here of using the <code>do..while</code> but the harm is readability.</p>\n<ul>\n<li><a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Res-do\" rel=\"nofollow noreferrer\">https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Res-do</a></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T17:16:01.143",
"Id": "247447",
"ParentId": "247383",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-02T15:52:43.587",
"Id": "247383",
"Score": "4",
"Tags": [
"c++",
"beginner"
],
"Title": "Computer tries to guess your inputted number"
}
|
247383
|
<p>So i read about simple series for Pi named Leibniz Series for Pi. Here is its Link:-
<a href="https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80#:%7E:text=The%20Leibniz%20formula%20for%20%CF%804%20can%20be%20obtained%20by,of%20the%20Dirichlet%20beta%20function." rel="nofollow noreferrer">Series</a> . I made a program for it and soon realised that it converges very slows . So i did Euler accelerate for Alternating Series <a href="https://en.wikipedia.org/wiki/Series_acceleration#Euler%27s_transform" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Series_acceleration#Euler's_transform</a> and made this recursive program:-</p>
<pre><code>import functools
import decimal
def LebniezTerm(n):
return 1/(2*n + 1)
@functools.lru_cache(maxsize = 12800)
def ndiffrence(n,depth):
if depth == 0:
return LebniezTerm(n)
a = ndiffrence(n,depth-1)
b = ndiffrence(n+1,depth-1)
return (a - b)
def EulerAccelerate(n):
i = decimal.Decimal(1)
pi = decimal.Decimal(0)
while (i <= n):
pi = pi + decimal.Decimal(ndiffrence(0,i-1))/decimal.Decimal(2**i)
i+=1
return pi
4*EulerAccelerate(600)
</code></pre>
<p>Here i did and optimisation using Functools but it is still slow. So can it become more optimised ?</p>
<p>How can the accuracy get more increased ?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-02T17:24:38.943",
"Id": "484168",
"Score": "0",
"body": "Any details left ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-10T01:17:41.300",
"Id": "484977",
"Score": "0",
"body": "Why do you use Decimal?"
}
] |
[
{
"body": "<p>What I found out by simply taking the time the calculation takes, is that casting to <code>Decimal</code> is a very costly operation. Dropping that in certain places (see my code) brings down the overall runtime to ~ 30-40%.</p>\n<p>Besides, the Leibnitz terms can easily be precomputed (another Best Practice of optimization) as the list will be comparatively short. Surprisingly, this does not save much.</p>\n<p>Using a module method with a local name save some time as well (<code>import xxx from this_module as local_name</code> instead of using <code>this_module.xxx</code> multiple times).</p>\n<p>In <code>EulerAccelerate()</code>, the loop variable <code>i</code> does not need to be of type <code>Decimal</code> which saves a lot. Replacing <code>2**(i+1)</code> with a simple addition yields another (small) saving.</p>\n<p>Stepping back from the code analysis, I think changing the algorithm from recursive to iterative would speed up the calculation a lot, much more than those micro-optimizations.</p>\n<p>results on my notebook: <code>maxdepth=24</code>, accurate to 8 places: pi=3.1415926, runtime=10 s</p>\n<pre><code> import functools\n from decimal import Decimal\n import time\n\n ## @functools.lru_cache(maxsize = 12800)\n def ndifference(n, depth):\n if depth == 0:\n return LT[n] # = 1.0/(2*n + 1)\n a = ndifference(n, depth-1)\n b = ndifference(n+1, depth-1)\n return (a - b)\n\n def EulerAccelerate(n):\n pi = 0\n ith_power_of_2 = 2 # 2**(i+1)\n for i in range(n):\n pi += Decimal(ndifference(0, i)) / ith_power_of_2\n ith_power_of_2 += ith_power_of_2\n return pi\n\n\n # ---------------------------------\n maxdepth = 24\n # create Leibnitz terms beforehand; LT is global\n LT = [(1.0/(2.0*i+1.0)) for i in range(maxdepth+1)]\n\n t = time.time()\n print 4 * EulerAccelerate(maxdepth)\n print time.time()-t\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-09T16:40:33.023",
"Id": "484936",
"Score": "0",
"body": "ok have you any idea about fast converging series for pi"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-10T01:26:18.897",
"Id": "484978",
"Score": "0",
"body": "@DhavalBothra if you google for „fast converging series for pi“ you will find a lot."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-09T09:35:40.980",
"Id": "247669",
"ParentId": "247389",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "247669",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-02T17:15:10.320",
"Id": "247389",
"Score": "2",
"Tags": [
"python",
"performance",
"recursion",
"mathematics"
],
"Title": "Euler Transform on Leibniz Series of Pi"
}
|
247389
|
<p>I am solving <a href="https://leetcode.com/problems/design-hashset/" rel="nofollow noreferrer">a problem on Leetcode</a> that requires me to design a hash set. I intend to solve it using linked lists where each linked list would represent a bucket.</p>
<p>I am intending to implement this:
<a href="https://i.stack.imgur.com/enJhc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/enJhc.png" alt="enter image description here" /></a></p>
<p>However, I am failing in one large test case.</p>
<p>This is my solution that failed a test case mentioned below:</p>
<pre><code>class MyHashSet:
def __init__(self):
"""
Initialize your data structure here.
"""
self.key_range = 769
self.buckets = [Bucket() for _ in range(self.key_range)]
def add(self, key: int) -> None:
_hash_ = self._hash(key)
bucket = self.buckets[_hash_]
bucket.insert(key)
def _hash(self, key):
return key % self.key_range
def remove(self, key: int) -> None:
_hash_ = self._hash(key)
bucket = self.buckets[_hash_]
bucket.delete(key)
def contains(self, key: int) -> bool:
"""
Returns true if this set contains the specified element
"""
_hash_ = self._hash(key)
bucket = self.buckets[_hash_]
return bucket.check_val(key)
class Node:
def __init__(self, val):
self.val = val
self.next = None
class Bucket:
def __init__(self):
self.head = Node('*')
self.curr = self.head
def insert(self, val):
if not self.check_val(val):
self.curr.next = Node(val)
self.curr = self.curr.next
def delete(self, val):
curr = self.head.next
prev = self.head
# found = False
while curr is not None:
if curr.val == val:
prev.next = curr.next
return
prev = curr
curr = curr.next
def check_val(self, val):
curr = self.head.next
while curr:
if curr.val == val:
return True
curr = curr.next
return False
</code></pre>
<p>The failed test case is:</p>
<p>Input:</p>
<pre><code>["MyHashSet","contains","remove","add","add","add","add","contains","add","add","contains","contains","add","contains","add","add","add","contains","remove","add","add","contains","add","add","add","add","remove","add","add","add","add","contains","add","add","contains","contains","contains","remove","add","add","contains","remove","remove","add","add","add","add","add","contains","remove","contains","add","contains","add","contains","remove","add","add","remove","contains","add","add","add","add","add","add","add","contains","remove","add","add","remove","remove","add","remove","add","remove","add","add","add","add","add","add","add","remove","add","remove","remove","add","add","add","add","contains","add","add","remove","add","add","add","remove","add","add","add","add","contains","add","add","add","remove","contains","add","add","add","add","add","remove","add","contains","contains","add","add","add","add","contains","remove","add","contains","add","contains","contains","add","add","contains","add","add","add","add","add","add","add","contains","remove","add","contains","add","remove","add","remove","remove","add","add","contains","add","remove","contains","add","add","add","add","add","add","add","contains","remove","remove","contains","add","contains","remove","add","add","add","add","contains","add","remove","add","remove","add","remove","add","add","add","remove","contains","add","add","add","add","remove","add","add","contains","contains","contains","remove","contains","remove","add","contains","add","add","add","add","remove","add","add","add","remove","remove","add","add","add","add","remove","add","remove","contains","add","contains","add","contains","add","contains","add","add","add","remove","add","add","add","add","add","contains","add","add","add","add","add","add","remove","add","remove","add","add","add","contains","add","add","remove","remove","remove","contains","remove","add","add","remove","add","contains","add","add","remove","contains","add","add","add","contains","remove","add","add","remove","contains","remove","add","contains","remove","add","add","add","add","contains","add","contains","add","remove","contains","add","add","add","add","add","add","add","remove","contains","contains","add","remove","add","remove","contains","add","contains","add","remove","add","add","add","add","remove","add","add","add","add","add","remove","contains","add","add","remove","contains","add","add","contains","add","remove","add","remove","add","add","remove","contains","add","add","add","contains","add","add","add","remove","add","remove","contains","add","add","contains","add","contains","add","add","remove","add","contains","contains","remove","contains","add","contains","add","add","remove","remove","add","add","remove","add","contains","add","add","add","contains","add","add","add","add","add","contains","add","add","contains","add","add","add","remove","add","add","add","add","add","add","add","add","remove","add","add","contains","remove","add","remove","contains","add","add","add","remove","add","add","contains","contains","add","contains","add","add","remove","add","add","remove","remove","add","add","add","contains","add","add","remove","add","remove","add","add","add","contains","add","add","add","add","contains","add","remove","add","add","remove","add","add","contains","add","add","add","add","contains","add","contains","add","add","add","add","add","remove","remove","remove","remove","contains","add","add","add","contains","add","contains","remove","add","add","contains","add","add","contains","add","contains","add","remove","add","remove","add","add","contains","add","add","add","add","add","add","add","add","add","add","add","add","add","contains","add","add","remove","add","add","remove","add","remove","remove","remove","contains","remove","contains","remove","add","remove","add","add","remove","add","add","remove","add","add","remove","add","contains","remove","add","contains","contains","remove","add","contains","add","add","contains","contains","add","add","add","add","contains","add","contains","add","add","remove","add","remove","contains","add","remove","remove","add","add","contains","contains","contains","add","contains","add","add","remove","add","add","add","remove","add","add","add","add","contains","remove","remove","contains","add","add","add","add","add","add","remove","contains","remove","add","add","add","contains","add","remove","add","add","remove","add","add","add","add","remove","remove","remove","add","contains","add","add","add","add","add","add","add","remove","add","add","add","add","add","add","add","remove","add","add","add","add","remove","add","add","add","contains","add","remove","add","add","add","add","add","add","add","add","add","contains","remove","remove","contains","add","remove","add","contains","add","remove","add","contains","add","add","add","add","contains","add","add","contains","contains","contains","add","remove","contains","add","add","remove","add","add","add","add","remove","add","contains","add","add","remove","contains","contains","add","add","add","add","add","add","add","remove","contains","remove","add","add","add","remove","contains","remove","contains","add","add","remove","remove","remove","add","add","contains","add","add","add","add","remove","add","add","add","add","remove","add","add","contains","add","add","add","remove","contains","remove","contains","contains","add","add","add","add","contains","add","add","remove","add","add","add","contains","add","add","add","contains","add","remove","add","add","remove","add","add","add","add","add","contains","add","add","add","contains","add","contains","contains","remove","remove","add","add","remove","add","add","contains","add","add","contains","add","add","contains","add","add","add","contains","add","add","add","add","add","remove","add","remove","add","add","remove","add","add","remove","add","add","add","add","remove","add","add","add","add","add","add","add","add","add","remove","add","contains","add","add","add","contains","contains","remove","add","add","contains","remove","add","remove","contains","remove","add","add","add","contains","contains","add","contains","add","add","add","contains","add","add","add","contains","add","add","contains","contains","remove","add","contains","contains","remove","add","add","contains","remove","add","add","contains","remove","add","add","add","contains","add","add","remove","add","add","add","add","contains","remove","remove","contains","contains","remove","add","add","contains","add","remove","contains","add","add","contains","contains","remove","add","add","add","add","add","add","contains","remove","contains","add","remove","add","add","remove","contains","remove","remove","remove","remove","add","add","add","contains","contains","add","add","add","add","add","remove","remove","add","contains","contains","add","add","contains","add","add","add","add","add","add","add","add","add","add","remove","remove","add","add","add","contains","add","add","add","contains","add","add","remove","contains","add","remove","remove","add","add","add","add","add","add","contains","add","add","add","remove","add","contains","add","remove","add","add","add","contains","add","add","add","add","remove","add","contains","remove","contains","remove","add","contains","add","add","remove","add","add","remove","add","remove","add","remove","add","contains","contains","add","contains","remove","contains","remove","add","remove","add","remove","add","remove","add","contains","add","remove"]
[[],[624],[182],[74],[647],[724],[575],[802],[343],[320],[329],[343],[339],[618],[493],[592],[894],[724],[537],[404],[301],[727],[750],[437],[364],[243],[436],[262],[412],[246],[985],[592],[187],[644],[578],[320],[412],[31],[297],[887],[74],[601],[995],[498],[808],[821],[443],[139],[808],[90],[703],[275],[364],[839],[785],[151],[575],[937],[615],[571],[459],[978],[530],[649],[743],[672],[539],[644],[955],[509],[692],[320],[19],[726],[242],[426],[242],[359],[969],[208],[963],[205],[687],[527],[435],[969],[387],[723],[46],[124],[584],[754],[359],[981],[753],[275],[277],[99],[849],[237],[855],[398],[170],[977],[965],[832],[371],[284],[968],[978],[106],[815],[737],[503],[72],[203],[685],[647],[268],[315],[753],[602],[353],[626],[96],[637],[521],[292],[654],[686],[774],[148],[72],[146],[384],[760],[769],[51],[606],[993],[80],[349],[13],[731],[120],[525],[656],[18],[445],[448],[4],[126],[214],[569],[774],[594],[814],[57],[823],[240],[92],[424],[165],[879],[1],[555],[317],[969],[145],[530],[364],[402],[617],[398],[71],[213],[290],[488],[702],[522],[837],[361],[247],[352],[575],[623],[760],[139],[224],[547],[283],[985],[57],[590],[302],[816],[277],[690],[65],[80],[185],[780],[238],[484],[906],[445],[429],[59],[475],[562],[989],[524],[946],[599],[543],[573],[753],[150],[290],[588],[415],[173],[828],[57],[550],[180],[977],[474],[378],[64],[436],[377],[2],[837],[646],[947],[937],[234],[388],[988],[90],[221],[960],[592],[576],[247],[769],[134],[216],[973],[868],[262],[836],[629],[766],[998],[141],[992],[36],[317],[547],[765],[320],[976],[556],[784],[606],[289],[504],[112],[10],[402],[28],[175],[489],[459],[237],[711],[787],[913],[814],[162],[343],[265],[865],[750],[787],[986],[112],[417],[51],[40],[745],[433],[584],[212],[408],[644],[591],[59],[298],[16],[989],[986],[304],[506],[85],[131],[934],[257],[372],[690],[960],[151],[712],[976],[643],[900],[853],[33],[58],[220],[217],[498],[825],[116],[586],[69],[158],[121],[388],[112],[474],[750],[253],[77],[110],[987],[680],[227],[60],[495],[586],[989],[727],[649],[199],[985],[554],[848],[522],[943],[831],[121],[390],[106],[717],[220],[563],[15],[24],[840],[674],[936],[973],[111],[260],[586],[341],[422],[806],[966],[694],[99],[425],[860],[493],[157],[487],[509],[967],[370],[790],[460],[383],[777],[660],[144],[106],[728],[192],[953],[456],[936],[81],[69],[988],[732],[836],[301],[882],[906],[637],[438],[334],[456],[848],[38],[288],[563],[653],[30],[110],[230],[144],[561],[404],[216],[360],[639],[509],[764],[253],[385],[114],[552],[255],[549],[752],[441],[464],[862],[747],[870],[717],[296],[491],[155],[500],[513],[25],[894],[192],[199],[24],[737],[486],[4],[227],[895],[998],[387],[126],[68],[772],[594],[710],[243],[279],[191],[730],[160],[784],[378],[53],[260],[564],[974],[751],[913],[167],[303],[81],[552],[405],[348],[775],[222],[731],[594],[953],[255],[740],[110],[980],[175],[500],[921],[366],[805],[476],[738],[869],[114],[348],[916],[598],[815],[632],[24],[968],[78],[285],[182],[229],[247],[745],[574],[837],[908],[314],[990],[577],[22],[221],[525],[628],[228],[696],[145],[398],[652],[431],[380],[574],[253],[408],[137],[71],[120],[185],[156],[392],[395],[875],[957],[241],[938],[525],[902],[706],[416],[699],[265],[39],[810],[963],[288],[991],[483],[991],[520],[190],[772],[432],[695],[112],[321],[447],[234],[55],[239],[993],[937],[624],[689],[787],[921],[292],[611],[888],[151],[463],[745],[367],[694],[567],[352],[439],[377],[616],[499],[995],[454],[578],[743],[771],[758],[279],[349],[721],[831],[394],[412],[454],[344],[920],[832],[151],[312],[830],[217],[815],[254],[497],[882],[997],[380],[734],[399],[720],[568],[860],[689],[814],[194],[503],[169],[459],[99],[99],[142],[301],[784],[472],[812],[204],[618],[675],[267],[725],[572],[77],[786],[634],[980],[829],[930],[754],[481],[484],[423],[377],[425],[521],[53],[552],[698],[664],[412],[666],[255],[308],[822],[931],[99],[123],[667],[931],[724],[515],[99],[270],[240],[808],[129],[6],[266],[806],[314],[235],[668],[236],[966],[173],[639],[306],[782],[135],[918],[285],[185],[880],[686],[58],[598],[290],[623],[71],[726],[436],[55],[305],[410],[313],[777],[554],[177],[456],[85],[436],[921],[523],[623],[736],[917],[860],[572],[183],[630],[676],[866],[754],[723],[400],[533],[606],[583],[524],[624],[407],[697],[823],[917],[192],[514],[535],[131],[966],[100],[639],[383],[35],[251],[838],[614],[118],[654],[927],[111],[674],[431],[816],[679],[352],[734],[887],[129],[185],[257],[332],[187],[727],[434],[750],[949],[335],[427],[259],[365],[642],[422],[121],[212],[857],[208],[148],[175],[945],[522],[197],[619],[862],[768],[835],[595],[841],[528],[113],[560],[449],[795],[421],[40],[314],[417],[219],[655],[859],[293],[10],[844],[263],[98],[682],[120],[809],[810],[235],[587],[681],[121],[410],[661],[806],[976],[3],[938],[806],[648],[227],[351],[192],[266],[694],[736],[428],[123],[933],[147],[407],[612],[619],[488],[608],[897],[87],[214],[275],[567],[259],[78],[288],[614],[338],[313],[498],[519],[421],[968],[742],[8],[170],[421],[977],[293],[941],[702],[841],[953],[210],[176],[487],[849],[846],[484],[339],[397],[249],[645],[285],[974],[975],[844],[670],[560],[951],[2],[661],[57],[580],[56],[693],[254],[751],[366],[97],[423],[625],[452],[34],[140],[285],[235],[873],[366],[81],[590],[229],[722],[669],[753],[797],[55],[400],[838],[34],[635],[97],[657],[910],[201],[223],[841],[248],[657],[545],[240],[622],[180],[201],[795],[571],[864],[632],[492],[857],[73],[849],[826],[513],[468],[114],[122],[643],[553],[907],[276],[874],[99],[1],[172],[239],[520],[148],[761],[100],[227],[592],[442],[652],[7],[105],[624],[780],[247],[772],[862],[57],[676],[191],[762],[116],[327],[859],[198],[596],[565],[119],[112],[219],[296],[982],[502],[623],[57],[513],[260],[368],[118],[118],[69],[795],[766],[481],[499],[433],[66],[374],[44],[981],[294],[418],[552],[384],[999],[196],[400],[925],[222],[678],[657],[684],[308],[423],[282],[487],[229],[598],[149],[247]]
</code></pre>
<p>Output:</p>
<pre><code>[null,false,null,null,null,null,null,false,null,null,false,true,null,false,null,null,null,true,null,null,null,false,null,null,null,null,null,null,null,null,null,true,null,null,false,true,true,null,null,null,true,null,null,null,null,null,null,null,true,null,false,null,true,null,false,null,null,null,null,false,null,null,null,null,null,null,null,true,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,true,null,null,null,null,null,null,null,null,null,null,null,false,null,null,null,null,true,null,null,null,null,null,null,null,true,false,null,null,null,null,false,null,null,false,null,false,false,null,null,true,null,null,null,null,null,null,null,false,null,null,false,null,null,null,null,null,null,null,false,null,null,true,null,null,null,null,null,null,null,false,null,null,false,null,true,null,null,null,null,null,true,null,null,null,null,null,null,null,null,null,null,true,null,null,null,null,null,null,null,true,false,false,null,true,null,null,false,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,false,null,false,null,false,null,true,null,null,null,null,null,null,null,null,null,true,null,null,null,null,null,null,null,null,null,null,null,null,true,null,null,null,null,null,false,null,null,null,null,null,false,null,null,null,false,null,null,null,true,null,null,null,null,true,null,null,false,null,null,null,null,null,true,null,true,null,null,true,null,null,null,null,null,null,null,null,true,false,null,null,null,null,false,null,true,null,null,null,null,null,null,null,null,null,null,null,null,null,false,null,null,null,false,null,null,true,null,null,null,null,null,null,null,true,null,null,null,false,null,null,null,null,null,null,true,null,null,true,null,true,null,null,null,null,false,true,null,true,null,true,null,null,null,null,null,null,null,null,false,null,null,null,false,null,null,null,null,null,true,null,null,true,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,false,null,null,null,true,null,null,null,null,null,null,true,false,null,true,null,null,null,null,null,null,null,null,null,null,true,null,null,null,null,null,null,null,null,false,null,null,null,null,true,null,null,null,null,null,null,null,true,null,null,null,null,true,null,false,null,null,null,null,null,null,null,null,null,false,null,null,null,true,null,false,null,null,null,true,null,null,true,null,false,null,null,null,null,null,null,true,null,null,null,null,null,null,null,null,null,null,null,null,null,false,null,null,null,null,null,null,null,null,null,null,true,null,true,null,null,null,null,null,null,null,null,null,null,null,null,null,false,null,null,true,true,null,null,true,null,null,false,false,null,null,null,null,true,null,false,null,null,null,null,null,true,null,null,null,null,null,false,true,false,null,true,null,null,null,null,null,null,null,null,null,null,null,true,null,null,true,null,null,null,null,null,null,null,true,null,null,null,null,false,null,null,null,null,null,null,null,null,null,null,null,null,null,true,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,true,null,null,null,null,null,null,null,null,null,null,null,true,null,null,true,null,null,null,true,null,null,null,true,null,null,null,null,true,null,null,false,false,false,null,null,true,null,null,null,null,null,null,null,null,null,true,null,null,null,true,false,null,null,null,null,null,null,null,null,false,null,null,null,null,null,true,null,true,null,null,null,null,null,null,null,true,null,null,null,null,null,null,null,null,null,null,null,null,true,null,null,null,null,false,null,true,false,null,null,null,null,false,null,null,null,null,null,null,false,null,null,null,false,null,null,null,null,null,null,null,null,null,null,true,null,null,null,true,null,false,true,null,null,null,null,null,null,null,true,null,null,true,null,null,false,null,null,null,true,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,false,null,null,null,true,true,null,null,null,true,null,null,null,false,null,null,null,null,false,true,null,false,null,null,null,false,null,null,null,true,null,null,false,true,null,null,true,false,null,null,null,true,null,null,null,true,null,null,null,null,true,null,null,null,null,null,null,null,true,null,null,false,true,null,null,null,true,null,null,false,null,null,true,false,null,null,null,null,null,null,null,false,null,true,null,null,null,null,null,false,null,null,null,null,null,null,null,false,false,null,null,null,null,null,null,null,null,false,true,null,null,false,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,false,null,null,null,true,null,null,null,true,null,null,null,null,null,null,null,null,null,true,null,null,null,null,null,true,null,null,null,null,null,false,null,null,null,null,null,null,false,null,false,null,null,true,null,null,null,null,null,null,null,null,null,null,null,true,false,null,false,null,true,null,null,null,null,null,null,null,null,true,null,null]
</code></pre>
<p>Expected Output:</p>
<pre><code>[null,false,null,null,null,null,null,false,null,null,false,true,null,false,null,null,null,true,null,null,null,false,null,null,null,null,null,null,null,null,null,true,null,null,false,true,true,null,null,null,true,null,null,null,null,null,null,null,true,null,false,null,true,null,false,null,null,null,null,false,null,null,null,null,null,null,null,true,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,true,null,null,null,null,null,null,null,null,null,null,null,false,null,null,null,null,true,null,null,null,null,null,null,null,true,false,null,null,null,null,false,null,null,false,null,false,false,null,null,true,null,null,null,null,null,null,null,false,null,null,false,null,null,null,null,null,null,null,false,null,null,true,null,null,null,null,null,null,null,false,null,null,false,null,true,null,null,null,null,null,true,null,null,null,null,null,null,null,null,null,null,true,null,null,null,null,null,null,null,true,false,false,null,true,null,null,false,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,false,null,false,null,false,null,true,null,null,null,null,null,null,null,null,null,true,null,null,null,null,null,null,null,null,null,null,null,null,true,null,null,null,null,null,false,null,null,null,null,null,false,null,null,null,false,null,null,null,true,null,null,null,null,true,null,null,false,null,null,null,null,null,true,null,true,null,null,true,null,null,null,null,null,null,null,null,true,false,null,null,null,null,false,null,true,null,null,null,null,null,null,null,null,null,null,null,null,null,false,null,null,null,false,null,null,true,null,null,null,null,null,null,null,true,null,null,null,false,null,null,null,null,null,null,true,null,null,true,null,true,null,null,null,null,false,true,null,true,null,true,null,null,null,null,null,null,null,null,false,null,null,null,false,null,null,null,null,null,true,null,null,true,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,false,null,null,null,true,null,null,null,null,null,null,true,false,null,true,null,null,null,null,null,null,null,null,null,null,true,null,null,null,null,null,null,null,null,false,null,null,null,null,true,null,null,null,null,null,null,null,true,null,null,null,null,true,null,false,null,null,null,null,null,null,null,null,null,false,null,null,null,true,null,false,null,null,null,true,null,null,true,null,false,null,null,null,null,null,null,true,null,null,null,null,null,null,null,null,null,null,null,null,null,false,null,null,null,null,null,null,null,null,null,null,true,null,true,null,null,null,null,null,null,null,null,null,null,null,null,null,false,null,null,true,true,null,null,true,null,null,false,false,null,null,null,null,true,null,false,null,null,null,null,null,true,null,null,null,null,null,false,true,false,null,true,null,null,null,null,null,null,null,null,null,null,null,true,null,null,true,null,null,null,null,null,null,null,true,null,null,null,null,false,null,null,null,null,null,null,null,null,null,null,null,null,null,true,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,true,null,null,null,null,null,null,null,null,null,null,null,true,null,null,true,null,null,null,true,null,null,null,true,null,null,null,null,true,null,null,false,true,false,null,null,true,null,null,null,null,null,null,null,null,null,true,null,null,null,true,false,null,null,null,null,null,null,null,null,false,null,null,null,null,null,true,null,true,null,null,null,null,null,null,null,true,null,null,null,null,null,null,null,null,null,null,null,null,true,null,null,null,null,false,null,true,false,null,null,null,null,false,null,null,null,null,null,null,false,null,null,null,false,null,null,null,null,null,null,null,null,null,null,true,null,null,null,true,null,false,true,null,null,null,null,null,null,null,true,null,null,true,null,null,false,null,null,null,true,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,false,null,null,null,true,true,null,null,null,true,null,null,null,false,null,null,null,null,false,true,null,false,null,null,null,false,null,null,null,true,null,null,false,true,null,null,true,false,null,null,null,true,null,null,null,true,null,null,null,null,true,null,null,null,null,null,null,null,true,null,null,false,true,null,null,null,true,null,null,false,null,null,true,false,null,null,null,null,null,null,null,false,null,true,null,null,null,null,null,false,null,null,null,null,null,null,null,false,false,null,null,null,null,null,null,null,null,false,true,null,null,false,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,false,null,null,null,true,null,null,null,true,null,null,null,null,null,null,null,null,null,true,null,null,null,null,null,true,null,null,null,null,null,false,null,null,null,null,null,null,false,null,false,null,null,true,null,null,null,null,null,null,null,null,null,null,null,true,false,null,false,null,true,null,null,null,null,null,null,null,null,true,null,null]
</code></pre>
<p>I then took a look at the solution and figured out that it intends to add a new node at the head, whereas I append the new node to the tail. Here, the node represents a unique value in the bucket. In my opinion, both the ways should work and so <a href="https://leetcode.com/articles/design-hashset/" rel="nofollow noreferrer">says the author</a>:</p>
<blockquote>
<p>For a value that was never seen before, we insert it to the head of the bucket, though we could also append it to the tail. It is a choice that we made, which could fit better the scenario where redundant values are operated in nearby time windows, since it is more likely that we spot the value at the head of the bucket rather than walking through the entire bucket.</p>
</blockquote>
<p>The solution that worked:</p>
<pre><code>class MyHashSet:
def __init__(self):
"""
Initialize your data structure here.
"""
self.key_range = 769
self.buckets = [Bucket() for _ in range(self.key_range)]
def _hash(self, key):
return key % self.key_range
def add(self, key: int) -> None:
bucket_index = self._hash(key)
self.buckets[bucket_index].insert(key)
def remove(self, key: int) -> None:
bucket_index = self._hash(key)
self.buckets[bucket_index].delete(key)
def contains(self, key: int) -> bool:
"""
Returns true if this set contains the specified element
"""
bucket_index = self._hash(key)
return self.buckets[bucket_index].check_val(key)
class Node:
def __init__(self, val, next_node=None):
self.val = val
self.next = next_node
class Bucket:
def __init__(self):
self.head = Node('*')
def insert(self, val):
if not self.check_val(val):
self.head.next = Node(val, self.head.next)
def delete(self, val):
curr = self.head.next
prev = self.head
# found = False
while curr is not None:
if curr.val == val:
prev.next = curr.next
return
prev = curr
curr = curr.next
def check_val(self, val):
curr = self.head.next
while curr:
if curr.val == val:
return True
curr = curr.next
return False
</code></pre>
<p>I failed to see what is wrong with appending values at the end.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-02T21:13:57.757",
"Id": "484187",
"Score": "0",
"body": "https://codereview.stackexchange.com/help/dont-ask"
}
] |
[
{
"body": "<p>I found the bug. It was in the <code>delete</code> function.</p>\n<p>I was wrongly marking the self.curr pointer.</p>\n<p>The correction is:</p>\n<pre><code>def delete(self, val):\n curr = self.head\n prev = self.head\n while curr is not None:\n if curr.val == val:\n prev.next = curr.next\n break\n prev = curr\n curr = curr.next\n if not curr or not curr.next: # we reached the last node\n # so that curr points to last valid node, whether the prev last was deleted, or this would be a redundant.\n self.curr = prev\n</code></pre>\n<p>My self.curr still points to the deleted node.</p>\n<p>The cases that I missed: correctly marking the self.curr in the cases of last node deletion.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-02T19:58:59.473",
"Id": "247398",
"ParentId": "247390",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-02T17:27:59.930",
"Id": "247390",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"hash-map"
],
"Title": "Designing a hashset with LinkedLists as buckets"
}
|
247390
|
<p>When asked to increment / decrement a particular value I usually create specific functions to handle this functionality. Like this:</p>
<pre><code> const increaseQuantity = index => {
const currentItems = [...stock];
currentItems[index].quantity += 1;
setStock(currentItems);
};
const decreaseQuantity = index => {
const currentItems = [...stock];
if (currentItems[index].quantity > 1) {
currentItems[index].quantity -= 1;
setStock(currentItems);
}
};
</code></pre>
<p>I like this approach because it clearly separates each action. Also, it only takes one single argument which keeps things simple.</p>
<p>But I can also create a single function, that does both things (increment or decrement), but it uses an additional parameter <code>action</code> as well as logic to perform the update:</p>
<pre><code> const manageQuantity = (index, action) => {
const currentItems = [...stock];
if (action === "increase") {
currentItems[index].quantity += 1;
setStock(currentItems);
}
if (currentItems[index].quantity > 1 && action === "decrease") {
currentItems[index].quantity -= 1;
setStock(currentItems);
}
};
</code></pre>
<p>I feel that the second pattern (single function) is more prone to error. Mainly because the the second argument is a (string).</p>
<p>Which is considered best practice and also follows some established (or well known) design pattern? Also, is one pattern more performant than the other?</p>
<p>Full functioning example below:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const availableItems = [
{
name: "iPod Nano",
capacity: "4GB",
quantity: 3
},
{
name: "iPod Classic",
capacity: "30GB",
quantity: 2
},
{
name: "iPod Mini",
capacity: "4GB",
quantity: 5
}
];
function FirstApp() {
const [stock, setStock] = React.useState(availableItems);
const increaseQuantity = index => {
const currentItems = [...stock];
currentItems[index].quantity += 1;
setStock(currentItems);
};
const decreaseQuantity = index => {
const currentItems = [...stock];
if (currentItems[index].quantity > 1) {
currentItems[index].quantity -= 1;
setStock(currentItems);
}
};
return (
<div className="app">
<h2>FirstApp</h2>
{JSON.stringify(stock)}
<hr />
{stock.map((item, i) => (
<div key={item.name}>
{item.name} | <button onClick={() => increaseQuantity(i)}>+</button>
<button onClick={() => decreaseQuantity(i)}>-</button>
</div>
))}
</div>
);
}
function SecondApp () {
const [stock, setStock] = React.useState(availableItems);
const increaseQuantity = index => {
const currentItems = [...stock];
currentItems[index].quantity += 1;
setStock(currentItems);
};
const decreaseQuantity = index => {
const currentItems = [...stock];
if (currentItems[index].quantity > 1) {
currentItems[index].quantity -= 1;
setStock(currentItems);
}
};
const manageQuantity = (index, action) => {
const currentItems = [...stock];
if (action === "increase") {
currentItems[index].quantity += 1;
setStock(currentItems);
}
if (currentItems[index].quantity > 1 && action === "decrease") {
currentItems[index].quantity -= 1;
setStock(currentItems);
}
};
return (
<div className="app">
<h2>SecondApp</h2>
{JSON.stringify(stock)}
<hr />
{stock.map((item, i) => (
<div key={item.name}>
{item.name} |{" "}
<button onClick={() => manageQuantity(i, "increase")}>+</button>
<button onClick={() => manageQuantity(i, "decrease")}>-</button>
</div>
))}
</div>
);
}
function App() {
return (
<React.Fragment>
<FirstApp />
<SecondApp />
</React.Fragment>
)
}
ReactDOM.render(<App/>, document.getElementById('root'));</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.app {
border: 2px solid grey;
padding: 10px;
margin: 10px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div></code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-02T20:06:23.173",
"Id": "484172",
"Score": "2",
"body": "Welcome to Code Review, where we review working code and provide suggestions on how that code can be improved. This question without the functioning snippet is off-topic.Rather than hiding the snippet I would leave it fully open all the time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-02T20:17:35.537",
"Id": "484173",
"Score": "0",
"body": "The functioning snippet is under \"Show code snippet\" @pacmaninbw"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-02T20:47:39.270",
"Id": "484175",
"Score": "2",
"body": "Please see our [guidelines](https://codereview.stackexchange.com/help/how-to-ask) for future reference. Especially any part about context."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T06:39:39.723",
"Id": "484198",
"Score": "0",
"body": "`currentItems[index].quantity += 1` mutates the state. `const currentItems = [...stock]` only creates a shallow copy of the array."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T12:16:24.043",
"Id": "484247",
"Score": "0",
"body": "I'm not mutating the state @adiga, I'm making a copy of the state using [spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator). I then make the change and update the state. See [here](https://reactjs.org/docs/optimizing-performance.html#the-power-of-not-mutating-data) for details."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T12:17:19.747",
"Id": "484248",
"Score": "3",
"body": "@JuanMarco spread syntax creates a copy of the array. The objects inside it are still the same in the copy and the original array."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T02:01:40.747",
"Id": "484338",
"Score": "2",
"body": "@JuanMarco spread only makes a *shallow* copy. Only works if the array is composed entirely of primitives like strings, numbers or booleans. You have an array of objects, so it won't do a deep copy."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T07:07:31.007",
"Id": "484725",
"Score": "0",
"body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
}
] |
[
{
"body": "<h1>Implementation 1</h1>\n<pre><code>const increaseQuantity = index => {\n const currentItems = [...stock];\n\n currentItems[index].quantity += 1;\n setStock(currentItems);\n};\n\nconst decreaseQuantity = index => {\n const currentItems = [...stock];\n\n if (currentItems[index].quantity > 1) {\n currentItems[index].quantity -= 1;\n setStock(currentItems);\n }\n};\n</code></pre>\n<h2>Issues</h2>\n<ul>\n<li><code>currentItems[index].quantity += 1;</code> and <code>currentItems[index].quantity -= 1;</code> are state mutations.</li>\n<li>Any computed state updates should use functional state updates and compute the next state from the current state. If for any reason more than a single <code>increaseQuantity</code> or <code>decreaseQuantity</code> is queued within a single render cycle only one gets applied. Similarly, if both a <code>increaseQuantity</code> <em>and</em> <code>decreaseQuantity</code> are enqueued, one would expect the net gain to be zero, but the last one enqueued is the one applied, so the net gain won't be zero.</li>\n</ul>\n<h2>Solution</h2>\n<ul>\n<li>Use a functional update</li>\n<li>Correctly compute next state</li>\n</ul>\n<p>Suggestions</p>\n<pre><code>const increaseQuantity = index => {\n setStock(stock =>\n stock.map((el, i) =>\n i === index\n ? {\n ...el,\n quantity: el.quantity + 1\n }\n : el\n )\n );\n};\n\nconst decreaseQuantity = index => {\n setStock(stock =>\n stock.map((el, i) =>\n i === index\n ? {\n ...el,\n quantity: el.quantity - el.quantity > 1 ? 1 : 0,\n // or\n // quantity: Math.max(0, el.quantity - 1),\n }\n : el\n )\n );\n};\n</code></pre>\n<h1>Implementation 2</h1>\n<pre><code>const manageQuantity = (index, action) => {\n const currentItems = [...stock];\n\n if (action === "increase") {\n currentItems[index].quantity += 1;\n setStock(currentItems);\n }\n\n if (currentItems[index].quantity > 1 && action === "decrease") {\n currentItems[index].quantity -= 1;\n setStock(currentItems);\n }\n};\n</code></pre>\n<h2>Issues</h2>\n<ul>\n<li>Suffers the same state mutation issue previously mentioned.</li>\n<li>More of a design pattern issue, but you've effectively encoded most of a reducer function.</li>\n</ul>\n<h2>Solution 1</h2>\n<ul>\n<li>Apply same fixes as implementation 1</li>\n<li>Reduce code duplication in function</li>\n</ul>\n<p>Suggestions</p>\n<pre><code>const manageQuantity = (index, action) => {\n setStock(stock =>\n stock.map((el, i) =>\n i === index\n ? {\n ...el,\n quantity:\n el.quantity + action === "increment"\n ? 1\n : el.quantity > 1\n ? -1\n : 0\n // or\n // quantity: Math.max(0, el.quantity + action === "increment" ? 1 : -1)\n }\n : el\n )\n );\n};\n</code></pre>\n<h2>Solution 2</h2>\n<ul>\n<li>Apply same fixes as implementation 1</li>\n<li>Concert to <a href=\"https://reactjs.org/docs/hooks-reference.html#usereducer\" rel=\"nofollow noreferrer\"><code>useReducer</code></a> react hook</li>\n</ul>\n<p>Suggestions</p>\n<p>Create action types & creator, and a reducer function.</p>\n<pre><code>const ACTIONS_TYPE = {\n INCREMENT: 'INCREMENT',\n DECREMENT: 'DECREMENT',\n};\n\nconst reducer = (state, action) => {\n switch(action.type) {\n case ACTIONS_TYPE.INCREMENT:\n return state.map((el, i) => i === action.index ? {\n ...el,\n quantity: el.quantity + 1,\n } : el);\n\n case ACTIONS_TYPE.DECREMENT:\n return state.map((el, i) => i === action.index ? {\n ...el,\n quantity: Math.max(0, el.quantity - 1),\n } : el);\n\n default:\n return state;\n };\n};\n\nconst increment = index => ({\n type: ACTIONS_TYPE.INCREMENT,\n index,\n});\n\nconst decrement = index => ({\n type: ACTIONS_TYPE.DECREMENT,\n index,\n});\n</code></pre>\n<p>Use in component</p>\n<pre><code>const [state, dispatch] = useReducer(reducer, initialState);\n\nconst incrementQuantity = () => index => dispatch(increment(index));\nconst decrementQuantity = () => index => dispatch(decrement(index));\n\n...\n\n...onClick={incrementQuantity(index)}...\n</code></pre>\n<p><em><strong>Notice</strong></em>:</p>\n<ul>\n<li>Action types are defined as an ENUM so when used in code the likelihood of typos is reduced since the string text isn't used directly.</li>\n<li>Like its redux big brother, it is a bit boiler-plately, but abstracts and isolates the state computation into a reducer pure function. IMO this improves the readability of the code using it.</li>\n<li>It still applies the pattern of using the current state and some input to compute the next state, still always a returning a new state object.</li>\n</ul>\n<h1>TL;DR</h1>\n<p>Complexity is similar in both approaches so it really comes down to familiarity. The former is close to the normal component state pattern while the latter resembles a portion of the redux pattern. One isn't necessarily better than the other, though I'd say for simple state the <code>useState</code> and update functions may be easier to grok for juniors joining your team than the <code>useReducer</code> which works well for more complex state shapes.</p>\n<p>Lessons Learned</p>\n<ol>\n<li>Don't mutate state, use shallow copies of state (and sub-state) and update when necessary.</li>\n<li>Use functional state updates to ensure multiple state updates enqueued within the same render cycle correctly compute next state from previous state.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T18:51:11.997",
"Id": "484669",
"Score": "0",
"body": "When you said \"If for any reason more than a single `increaseQuantity` or `increaseQuantity`\"\nDidn't you mean `increaseQuantity` and `decreaseQuantity`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T19:30:24.987",
"Id": "484680",
"Score": "1",
"body": "@JuanMarco Yes, I certainly did mean that, thanks. (*copy/paste error*) I've updated answer. Sorry if that caused any confusion."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T02:12:23.623",
"Id": "247500",
"ParentId": "247394",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "247500",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-02T18:23:43.890",
"Id": "247394",
"Score": "5",
"Tags": [
"javascript",
"performance",
"ecmascript-6",
"react.js"
],
"Title": "Pattern usage for increment / decrement React (Hooks)"
}
|
247394
|
<p>I coded a registration form and was wondering if anyone could give me feedback on whether I'm lacking any major security mechanisms. I've done loads of reading around the topic and feel it should be secure but expert feedback would be great.</p>
<p><strong>Registration script</strong></p>
<pre><code><?php
// User/pass only used locally
$host = 'localhost';
$db = 'new_db';
$user = 'root';
$pass = '';
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$dsn = "mysql:host=$host;dbname=$db";
try {
$pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
$errors = [];
if ( $_POST )
{
// Get form field values
$fname = filter_input(INPUT_POST, 'fname', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$pwd = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
$pwd_confirm = filter_input(INPUT_POST, 'confirm-password', FILTER_SANITIZE_STRING);
// Generate activation key
$activation_key = md5(uniqid(mt_rand(), true));
$activation_link = 'https://www.example.com/activate?id='.$activation_key.'&name='.$fname;
// Check if passwords match
if ($pwd !== $pwd_confirm) {
$errors[] = "Passwords don't match";
}
// Check if password is secure
if (strlen($pwd) < 8) {
$errors[] = "Password not long enough! Must be at least 8 characters long";
}
// Check if username equals password
if ($fname === $pwd) {
$errors[] = "Your name cannot be your password!";
}
// Check if email address exists in database
$email_query = $pdo->prepare("SELECT * FROM users WHERE email = :email");
$email_query->bindParam(':email', $email);
$email_query->execute();
$email_found = $email_query->fetchColumn();
if ($email_found) {
$errors[] = "Your email address is associated with another account.";
}
// If no errors, continue with user account creation
if (!$errors)
{
// Hash password
$hashed_password = password_hash($pwd, PASSWORD_DEFAULT);
// Create database entry
$create_account = $pdo->prepare("INSERT INTO users (first_name,email,password, activation_key) VALUES (:fname, :email, :password, :activation_key)");
$create_account->bindParam(':fname', $fname);
$create_account->bindParam(':email', $email);
$create_account->bindParam(':password', $hashed_password);
$create_account->bindParam(':activation_key', $activation_key);
$create_account->execute();
// Send out activation email
$to=$email;
$subject="Activate your account";
$from = 'no-reply@example.com';
$body='Thank you for creating your account, '.$fname.'. Please click on the following link to activate your account: <a href="'.$activation_link.'">'.$activation_link.'</a>';
$headers = "From:".$from;
mail($to,$subject,$body,$headers);
// Redirect user to the dashboard
header("Location: /dashboard.php");
exit;
}
}
?>
</code></pre>
<p>I do want to use it on a live site at one point, so the end result should not just be a registration form that's somewhat secure but could actually be used in production.</p>
<p><strong>EDIT</strong></p>
<p>I did some more thinking and I guess before redirecting the newly registered user, I have to start a session to detect on the dashboard page whether the user is logged in. Is the following sufficient and secure to to add after I sent out the activation email?</p>
<pre><code>session_start();
$_SESSION["loggedin"] = true;
$_SESSION["email"] = $email;
// Redirect user to the dashboard
header("Location: /dashboard.php");
exit;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-02T19:57:29.077",
"Id": "484171",
"Score": "3",
"body": "Anyone who down votes or uses VTC please leave a comment as to why you down voted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-02T20:46:37.507",
"Id": "484174",
"Score": "0",
"body": "I don't really see anything unsecure to point out in your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T09:47:21.617",
"Id": "484224",
"Score": "0",
"body": "```$activation_key = md5(uniqid(mt_rand(), true));``` - stop, just do `bin2hex(random_bytes(15));` or something like that, it's much safer than uniqid()"
}
] |
[
{
"body": "<ul>\n<li><p>It will be better practice to url encoding the query string of your <code>$activation_link</code> in case the <code>$fname</code> is not url-compliant. I recommend <code>http_build_query()</code> -- <a href=\"https://joomla.stackexchange.com/q/26632/12352\">here's a post about the delimiting ampersands</a>. I will also recommend that you not generate this string until you determine that it is actually needed down script.</p>\n</li>\n<li><p>It is good that you are properly implementing prepared statements, but your unique email query is fetching more data than you intend to use. Instead of <code>SELECT *</code> use <code>COUNT(1)</code> or <code>COUNT(*)</code>, and <a href=\"https://phpdelusions.net/pdo#:%7E:text=$count,fetchColumn();\" rel=\"noreferrer\">fetch that one particular column of the single-row result set</a>.</p>\n<pre><code>if ($email_query->fetchColumn()) {\n $errors[] = "Your email address is associated with another account.";\n}\n</code></pre>\n</li>\n<li><p>There is no benefit to re-declaring the email value to the new variable <code>$to</code>, just keep using <code>$email</code> when passing arguments to your <code>mail()</code> function.</p>\n</li>\n<li><p>I generally advise against declaring "single-use variables". It can be a good idea when the variable name helps to describe the data, but then if your script needs this kind of meta-detail, then perhaps just use a comment. In my own project, I'd probably not declare the single-use variables like <code>$hashed_password</code>, <code>$to</code>, <code>$from</code>, <code>$subject</code>, and <code>$body</code>.</p>\n</li>\n<li><p>You are not <a href=\"https://stackoverflow.com/q/3186725/2943403\">checking for a <code>true</code> response from <code>mail()</code></a>, you may like to check this instead of assuming. Then again, in all of my projects, I rely upon PHPMailer to do all my mailing functionality -- it is just a better / more robust class to work with. In the meantime, you might rewrite your <code>mail()</code> call like this:</p>\n<pre><code>if (\n !mail(\n $email,\n "Activate your account",\n sprintf(\n 'Thank you for creating your account, %1$s.'\n . ' Please click on the following link to activate your account: <a href="%2$s">%2$s</a>',\n $fname,\n 'https://www.example.com/activate?' . http_build_query(['name' => $fname, 'id' => $activation_key], '', '&amp;')\n ),\n "From:no-reply@example.com"\n )\n) {\n $errors[] = "Failed to mail activation email";\n} else {\n session_start(); // I advise that this line be unconditionally written at the start of page -- ideally in a config file which is called first by every page\n\n $_SESSION["loggedin"] = true; // I don't think I'd bother with this element\n $_SESSION["email"] = $email; \n header("Location: /dashboard.php");\n exit;\n}\n</code></pre>\n<p>If you find this to be "uglier", then there won't be any harm in declaring the extra variables.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-02T22:16:44.817",
"Id": "247404",
"ParentId": "247395",
"Score": "6"
}
},
{
"body": "<p>You properly protect against SQL injection, that's good.</p>\n<p>I worry about the filtering on the password. If I choose <code><script>' OR 1=1 ">>></code> as my password, the filtering should not reduce this to just <code>' OR 1=1 "</code>, just because some part of it looks like HTML tags. A password is not supposed to be displayed anywhere, it is not supposed to be stored in plain text anywhere, the only valid use is to feed it to <code>password_validate</code> and <code>password_hash</code>, and these can cope with arbitrary input (well, except that they stop processing at the first byte that is 0, that is, the byte value 0, not the digit <code>'0'</code>). When I enter a password, I expect this password to be used exactly, unmodified, unnormalized, just as I entered it.</p>\n<p>I dimly remember that <code>uniqid</code> is not very unique at all. You should double-check the documentation whether that function provides enough randomness to protect against guessing attacks.</p>\n<p>Your code is sending out a mail containing <code><a href="..."></code>, but nowhere in the code do I see a <code>Content-type: text/html; charset=UTF-8</code> header.</p>\n<p>Your code is sending out malformed HTML. The URL contains a plain <code>&</code>, which in HTML must be escaped as <code>&amp;</code>. To do this, call <code>htmlspecialchars($url)</code>. Most browsers accept this malformed HTML, but it's better do know how to correctly convert between plain text and HTML. Just to avoid cross-site scripting from the beginning.</p>\n<p>What if the <code>$fname</code> contains an ampersand? Some companies have that in their name. I don't know of actual people with these names, but who knows? An ampersand would make the generated <code>$activation_link</code> invalid.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T01:59:01.550",
"Id": "484194",
"Score": "0",
"body": "I definitely agree with not sanitizing the password string. I don't know that `uniqid()`'s \"uniqueness\" is a concern worth stressing over. There are two factors in the activate requirements, so an attacker would need to know a new user's fname and blow through a lot of attempts to activate the account ...and to what end? They activate your account for you? I will hope/assume that the activation receiving script will force the user to login with their password, otherwise there could be a vulnerability there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T10:00:16.473",
"Id": "484230",
"Score": "1",
"body": "```and these can cope with arbitrary input``` i wish that was true. but it's not true, see: https://3v4l.org/SaRef - they will choke on any strings containing null bytes. they think that these 2 strings are equivalent: `X\\x00Roland` and `X\\x00ASUFHUWEGFHSEJUHFW` - do those look the same to you? no? well, they look the same to password_hash() and password_verify() <.<"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T10:21:07.633",
"Id": "484234",
"Score": "0",
"body": "@hanshenrik That may be a bug, as it assumes `\"X\"` as equal as well. But the function doesn't say that it is binary-safe. But on the other hand, `strlen` isn't binary-safe either but `var_dump(strlen(\"X\\x00ASUFHUWEGFHSEJUHFW\"));` returns 20."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T18:16:28.923",
"Id": "484305",
"Score": "1",
"body": "@IsmaelMiguel actually PHP's strlen() is binary-safe (horrifyingly, it's possible to configure strlen to be non-binary-safe, but that's deprecated as of 7.2: https://www.php.net/manual/en/mbstring.overload.php )"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T20:11:21.143",
"Id": "484311",
"Score": "0",
"body": "@hanshenrik Then the documentation is wrong, as [`str_replace()`'s notes](https://www.php.net/manual/en/function.str-replace.php#refsect1-function.str-replace-notes) say it is binary-safe, but `strlen()` doesn't."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T22:07:57.930",
"Id": "484324",
"Score": "0",
"body": "@IsmaelMiguel well str_replace() is always binary safe, even if mb overloading is enabled.. strlen() is only binary safe when mb overloading is disabled (and it should *always* be disabled)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T23:23:42.143",
"Id": "484330",
"Score": "0",
"body": "@hanshenrik I think my point failed to get across. Other string functions say if/when they are binary-safe, but `strlen()` doesn't, making the documentation incomplete."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T23:24:59.920",
"Id": "484331",
"Score": "1",
"body": "@IsmaelMiguel oh like that, yeah you're right, it's a shame the strlen() docs doesn't mention the binary safety properties of strlen()"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T23:30:39.130",
"Id": "484332",
"Score": "0",
"body": "@hanshenrik Exactly. Which is why I assumed that it wasn't binary safe. But still, regarding your point about `password_hash()`, it appears it was commented 4 years ago: https://www.php.net/manual/en/function.password-hash.php#118603 but so far, nothing has been done. I guess it may be intended behaviour or just not reported before?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T23:33:51.903",
"Id": "484333",
"Score": "0",
"body": "@IsmaelMiguel i'm guessing it's \"kindof\" intended: they intend to be compatible with [POSIX's crypt()](https://www.man7.org/linux/man-pages/man3/crypt.3.html), and POSIX crypt() *also* isn't binary safe <.< (in a way, they kindof inherited the non-binary-safety from POSIX)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T23:35:53.597",
"Id": "484334",
"Score": "0",
"body": "@hanshenrik Well, I guess it is just a salad there with surprising results. But well, this answer still should be updated to reflect this information."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T14:33:41.773",
"Id": "484751",
"Score": "0",
"body": "\"well, except that they stop processing at the first byte that is 0, that is, the byte value 0, not the digit '0'\" <-- this is called a `null` byte, usually represented as a `\\0` or `\\x00`."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T00:31:07.187",
"Id": "247408",
"ParentId": "247395",
"Score": "9"
}
},
{
"body": "<p>A small addition to what others have said...</p>\n<p><a href=\"https://www.php.net/manual/en/function.password-hash.php\" rel=\"nofollow noreferrer\"><code>password_hash()</code></a> when used with <code>PASSWORD_DEFAULT</code> will change the algorithm in future versions of php, which means that it might stop passing in one update.</p>\n<p>I would use <code>PASSWORD_BCRYPT</code> and set an appropriate number of rounds, when increasing the rounds you can update passwords on the fly after they log in.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T09:46:35.070",
"Id": "484222",
"Score": "1",
"body": "I'm torn between downvoting and not downvoting this answer. Reading the documentation, you can see that the intended use is to use `PASSWORD_DEFAULT` for easiness, and then more advanced algorithms if supported. Then, you use [`password_needs_rehash()`](https://www.php.net/manual/en/function.password-needs-rehash.php) to see if you need to update the hash on login. Also, `PASSWORD_BCRYPT` cuts the password to 72 characters. That's TERRIBLE! Also, \"[...] which means that it will stop passing in one update.\" is just wrong as the default will change, the hash verifies anyway and then updated. ..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T10:00:53.143",
"Id": "484231",
"Score": "0",
"body": "... However, increasing the rounds is a good mitigation and a good way to slowdown brute-force. But other methods could be added, for login, but it's outside the scope of the review. But then, you say you would store those rounds with the password. Which makes me believe that you have a wrong understanding of how these functions work. All the information (algorithm, rounds, salt and hash) is stored in the result of `password_hash()`. All you ned to do is to check the result with [`password_verify()`](https://www.php.net/manual/en/function.password-verify.php). ..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T10:03:53.103",
"Id": "484232",
"Score": "0",
"body": "... You should check how these work on here: http://sandbox.onlinephpfunctions.com/code/5a4fa92c5a6b221157373003c98a0b9dba37e941. You can try to change the algorithm, the password, the options. Just see what happens. The password hash was taken from the 1st example. You can see that you don't need to store anything else to see if the password matches or not. Just set whatever you want and it works fine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T14:08:51.417",
"Id": "485951",
"Score": "0",
"body": "(In short, the algo is stored in the hash. It won't stop passing if the default algo changes.)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T08:05:51.233",
"Id": "247422",
"ParentId": "247395",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "247408",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-02T18:35:08.737",
"Id": "247395",
"Score": "8",
"Tags": [
"php",
"mysql",
"pdo"
],
"Title": "How secure is my PHP registration script?"
}
|
247395
|
<p>I wrote code to filter for duplicate elements in an array. I'd like to know your opinion, whether it's efficient at all, or if there's too many objects created, use of both array and list. That's in preparation for an interview. I'm not interested in lambdas (distinct) or helper methods, I'd like to see where I can improve and understand what's efficient or not in what I wrote, also without using Set, HashSet.</p>
<pre class="lang-java prettyprint-override"><code>public class Duplicate {
public static void main (String [] args){
// filter duplicate elements
int [] arr = {5,4,3,5,4,6,7,8,6};
Arrays.sort(arr);
int length = arr.length;
List<Integer> list = new ArrayList<>();
list.add(arr[0]);
for(int i =0; i <length-1;i++){
if(arr[i] != arr[i+1]){
list.add(arr[i+1]);
}
}
System.out.println(Arrays.toString(list.toArray()));
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-28T23:49:58.720",
"Id": "484177",
"Score": "0",
"body": "You can add the items to a `Set` instead of a `List` to avoid duplicates."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-29T08:59:35.713",
"Id": "484178",
"Score": "0",
"body": "Sorry I forgot to mention, without using a set."
}
] |
[
{
"body": "<p>You can add the items to a <code>Set</code> instead of a <code>List</code> to avoid duplicates. That way you delegate to <code>Set</code> for uniqueness:</p>\n<pre><code>int [] arr = {5, 4, 3, 5, 4, 6, 7, 8, 6};\n\nSet<Integer> set = new HashSet<>();\n\nint length = arr.length;\n\nfor(int i = 0; i < length; i++){\n set.add(arr[i]);\n}\n\nSystem.out.println(Arrays.toString(set.toArray()));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-29T01:22:01.537",
"Id": "484179",
"Score": "0",
"body": "Have you tested this on an array with only one element?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-29T03:29:08.363",
"Id": "484180",
"Score": "0",
"body": "I copy the loop from the question. Now is fixed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-29T08:58:11.757",
"Id": "484181",
"Score": "0",
"body": "Sorry I forgot to mention, without using a Set."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-29T09:02:50.887",
"Id": "484182",
"Score": "0",
"body": "dnault - Yes, let's take into consideration there's an if statement to filter for that, this is to focus more on the working logic"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-29T00:01:51.307",
"Id": "247401",
"ParentId": "247400",
"Score": "0"
}
},
{
"body": "<p>It may be important to the interviewer that you can find a solution without sorting (I don't know the full context of the interview question), for example if the original order is important or if the elements can not be compared in a sortable way. A solution that would take O(n^2) time but preserve order, and take O(1) space is to go element by element, search the rest of the data structure for a repetition of the current element and removing it. It would take O(n^2) if you used a structure with O(1) removals, such as a linked list.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-29T09:01:58.140",
"Id": "484183",
"Score": "0",
"body": "No, I don't get a null pointer exception, as it stops one before the length of the array, i + 1 still works."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-29T14:32:21.790",
"Id": "484184",
"Score": "0",
"body": "@Patrick Oh right, sorry, that was lazy on my part. I’ll edit it so it doesn’t confuse anyone"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-29T00:09:50.030",
"Id": "247402",
"ParentId": "247400",
"Score": "0"
}
},
{
"body": "<p>This problem is very simple in only a few lines of code, as long as we know what the constraints on the input are:</p>\n<pre><code>int [] arr = {5,4,3,5,4,6,7,8,6};\nint maxPossibleInputValue = 9;\n...\nList<Integer> list = new ArrayList<>();\nbyte[] tracker = new byte[maxPossibleInputValue + 1];\nfor (int i = 0; i < arr.length; i++)\n{\n if (tracker[arr[i]]++ == 0)\n {\n list.add(arr[i]);\n }\n}\n</code></pre>\n<p>Only works when we know the range of input possible due to memory consumption, but it will be fast - O(n) with only a single heap allocation.</p>\n<p>If the value range will exceed memory constraints (i.e. the entire 32 bit int range instead of "all digits under 1000" or such), then we may have to implement our own simple hashset...</p>\n<p>i.e.</p>\n<pre><code>List<Integer> mainRoutine(int[] arr)\n{\n List<Integer> list = new ArrayList<>();\n MyNode[] tracker = new MyNode[65536];\n for (int i = 0; i < arr.length; i++)\n {\n int segment = arr[i] % tracker.length;\n if (tracker[segment] == null) || !tracker[segment].has(arr[i]))\n {\n list.add(arr[i]);\n }\n MyNode newNode = new MyNode(arr[i], tracker[segment]);\n tracker[segment] = newNode;\n }\n return list;\n}\n\n...\n...\n\nprivate static class MyNode\n{\n private final int val;\n private MyNode child;\n\n private MyNode(int val, MyNode child)\n {\n this.val = val;\n this.child = child;\n }\n\n boolean has(int val)\n {\n return (this.val == val) || (child != null && child.has(val);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-02T19:00:41.963",
"Id": "247403",
"ParentId": "247400",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-28T23:37:32.113",
"Id": "247400",
"Score": "1",
"Tags": [
"java",
"performance"
],
"Title": "Filter for duplicate elements"
}
|
247400
|
<p>I started learning programing with C++. It runs perfectly, but I wonder what things I can improve following the principles of class inheritance, access, overwriting, virtual functions and destructors, and why.</p>
<pre><code>#include <iostream> // allows program to output data to the screen
using namespace std;
struct Base {
virtual void do_something() {};
virtual ~Base(){};
};
struct Derived1 : public Base {
Derived1():Base(){}
virtual void do_something() {
std::cout << "Derived1!!!" << std::endl;
}
virtual~Derived1(){};
};
struct Derived2 : public Base {
Derived2():Base(){}
virtual void do_something() {
std::cout << "Derived2!!!" << std::endl;
}
virtual ~Derived2(){};
};
// function main begins program execution
int main(int argc, const char *argv[]) {
std::cout << "Welcome" << std::endl;
Derived1 derived1;
derived1.do_something();
Derived2 derived2;
derived2.do_something();
return 0;
} // end function main
</code></pre>
|
[] |
[
{
"body": "<p>Don't add meaningless comments.</p>\n<pre><code>#include <iostream> // allows program to output data to the screen\n</code></pre>\n<p>There is a real issue with code and comment rot. So your comments should always be meaningful as you have to maintain them with the code. It is best to reserve comments to "WHY" you are doing something. The code will explain "HOW".</p>\n<hr />\n<p>Don't do this:</p>\n<pre><code>using namespace std;\n</code></pre>\n<p>There are definitely issues with pulling the whole standard namespace into the global namespace.</p>\n<p>See: <a href=\"https://stackoverflow.com/q/1452721/14065\">Why is “using namespace std;” considered bad practice?</a>\nIn my opinion the best answer is the second one: <a href=\"https://stackoverflow.com/a/1453605/14065\">sbi</a> though the first one is good.</p>\n<hr />\n<p>If <code>Base</code> does no real work you can make the virtual functions abstract:</p>\n<pre><code>struct Base {\n virtual void do_something() {};\n virtual ~Base(){};\n};\n\n// If the user should not be able to instantiate a `Base` then do this:\n\nstruct Base {\n virtual void do_something() = 0;\n virtual ~Base() {}\n};\n</code></pre>\n<hr />\n<p>If your functions do <strong>not</strong> alter the standard behavior then don't include them:</p>\n<pre><code>struct Derived1 : public Base {\n Derived1():Base(){}\n virtual void do_something() {\n std::cout << "Derived1!!!" << std::endl;\n }\n virtual~Derived1(){};\n};\n</code></pre>\n<p>Here the constructor and destructor are useless. Do not bother to specify them</p>\n<pre><code>struct Derived1 : public Base {\n virtual void do_something() {\n std::cout << "Derived1!!!" << std::endl;\n }\n};\n</code></pre>\n<hr />\n<p>Don't use <code>std::endl</code>.</p>\n<pre><code> std::cout << "Derived2!!!" << std::endl;\n</code></pre>\n<p>This is the major cause of C++ code running slowly. The problem is that <code>std::endl</code> forces the stream to flush. The stream will automatically flush when it is need and any extra flushes are likely to be inefficient (humans are bad at working out when to flush the stream).</p>\n<p>It is better simply to use <code>"\\n"</code></p>\n<pre><code> std::cout << "Derived2!!!" << "\\n";\n</code></pre>\n<hr />\n<p>From C++11 we introduced the <code>override</code> specifier.<br />\nIn the derived class you should mark any overridden methods with it.</p>\n<pre><code>struct Derived1 : public Base {\n virtual void do_something() override;\n};\n\nstruct Derived2 : public Base {\n virtual void do_something() override;\n};\n</code></pre>\n<p>The advantage here is that if in the future somebody changes the <code>Base</code> class and renames or alters the virtual functions in the base the compiler will not warn you that these functions no longer align with the base class version.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T16:25:39.617",
"Id": "484288",
"Score": "0",
"body": "The `Base` destructor needs to be defined anyway, so there's no reason to make that pure virtual."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T17:23:52.227",
"Id": "484295",
"Score": "0",
"body": "@MooingDuck Thanks Fixed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T20:12:56.340",
"Id": "484312",
"Score": "0",
"body": "`std::endl` is useful for debugging when code may prematurely crash or exit or when running code in multiple threads. For small log messages like this, `std::endl` is fine. For larger pieces of data, not so much."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T21:47:45.217",
"Id": "484321",
"Score": "0",
"body": "@yyny For this type of debugging tasks you should be using `std::cerr` which is not buffered."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-05T00:58:19.827",
"Id": "527869",
"Score": "0",
"body": "Is it possible to do this: Base b = Derived1(); b.do_something(); ? For me it's not executing the do_something method of Derived, rather its running the base's method. Is there a way I can achieve b to execute Derived1's do_something method?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-05T23:48:03.803",
"Id": "527915",
"Score": "0",
"body": "@programmer: Not that will not work. The `Derived1()` object will be copied into a `Base` object b. This cuts off all the bits that are from `Derived1` (you just copy the `Base` portion of the object. Change to make `b` a reference. `Base& b = Derived1(); b.do_something();` This is known as [slicing](https://www.geeksforgeeks.org/object-slicing-in-c/)."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T00:05:11.443",
"Id": "247407",
"ParentId": "247405",
"Score": "13"
}
},
{
"body": "<p>While Martin explained problems with code there is, I'm gonna note about one that isn't. This is done out of suspicion about you not knowing and I hope you'll forgive me if I'm wrong.</p>\n<h2>Currently you don't use virtuality of your virtual functions.</h2>\n<p>In the main function you create objects of derived type and call <em>functions of derived type</em>. You never use the API of base class</p>\n<p>The use mostly arrives when</p>\n<h3>a) There's a container with base class pointers</h3>\n<pre class=\"lang-cpp prettyprint-override\"><code>std::vector<unique_ptr<Base>> vec;\nvec.push_back(make_unique<Derived1>());\nvec[0].do_something() //Derived1!!!\n</code></pre>\n<p>or</p>\n<h3>b) There's a function taking base class pointer/reference</h3>\n<pre><code>void foo(Base& b)\n{\n b.do_something();\n}\n\nint main()\n{\n Derived1 d;\n foo(d); //Derived1!!!\n}\n</code></pre>\n<p>Sometimes both:</p>\n<pre><code>void foo(Base& b)\n{\n b.do_something();\n}\n\nint main()\n{\n std::vector<unique_ptr<Base>> vec;\n vec.push_back(make_unique<Derived2>());\n foo(vec[0]); //Derived2!!!\n} \n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T15:02:09.117",
"Id": "484273",
"Score": "2",
"body": "This might just be a problem with the [simplified example](https://codereview.meta.stackexchange.com/q/1709/1581) in the question."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T10:57:39.680",
"Id": "247432",
"ParentId": "247405",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "247407",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-02T23:09:15.990",
"Id": "247405",
"Score": "6",
"Tags": [
"c++",
"beginner"
],
"Title": "Struct inheritance in C++"
}
|
247405
|
<p>Back with another Reddit bot. This one provides games of Hangman to an arbitrary number of players simultaneously. Users interface with the bot by mentioning it for a new game. Once that game is started, the user guesses continuously and the bot replies until win, loss, or forfeit. A user is limited to playing only their own game and there is no branching..</p>
<p>To achieve this, I keep track of active games with a dict of <user,game>, active_games, which is saved to a file in json format every time it changes. The program can be restarted such that it loads the active games from file. This persistence requires that I convert between Hangman instances and dicts, and I'm not sure I've done it the best way. Additionally, whenever a game ends it is removed from active_games and written to another file storing all past games.</p>
<p>Please feel free to comment on anything.</p>
<pre><code>import json
import os
import random
import praw
import requests
FORFEIT = 'forfeit'
WIN = 'You win! Big-brained, you are.'
LOSS = 'You lose. Try again.'
MIN_LEN = 4
INIT_LIVES = 5
class Hangman:
"""represents the state of a game of Hangman"""
def __init__(self):
self.secret = random_word()
self.lives = INIT_LIVES
self.word_state = ['_'] * len(self.secret)
self.mistakes = []
@classmethod
def fromdict(cls, dictionary):
"""dictionary to Hangman copy/convert constructor"""
instance = cls()
for key in dictionary:
setattr(instance, key, dictionary[key])
return instance
def process_guess(self, guess_body):
"""requires that guess_body is single character: modifies word_state to fill in guess matches"""
for i in range(0, len(self.secret)):
if self.secret[i] == guess_body:
self.word_state[i] = guess_body
def word_correct(self, guess):
return guess == self.secret
def record_mistake(self, mistake_body):
self.mistakes.append(mistake_body)
self.lives -= 1
def display_contents(self):
"""return a formatted markdown string containing a report on hangman attributes"""
reply = ''
reply += '\n\nlives: ' + str(self.lives) + '\n\n#'
for char in self.word_state:
reply += char + ' '
reply += '\n\nmistakes: '
reply += ', '.join(self.mistakes)
return reply
def random_word():
"""request one random word from API. If len of word at least MIN_LEN letters, return it (str). Otherwise, request another."""
while True:
r = requests.get('https://random-word-api.herokuapp.com/word', {'number' : 1})
r.raise_for_status()
word = r.json()[0]
if len(word) >= MIN_LEN:
return word
def authenticate():
r = praw.Reddit('hangman', user_agent = "hangmanbot")
return r
def run_bot(reddit, active_games):
# concern: maybe update_active_games_file should be done in same fn as archiving
unread_items = []
for item in reddit.inbox.unread(limit=None):
if bot_mentioned(item):
start_new_game(item, active_games)
update_active_games_file(item, active_games)
else:
try:
continue_game(item, active_games)
update_active_games_file(item, active_games)
except Exception as e: print(e)
unread_items.append(item)
reddit.inbox.mark_read(unread_items)
def bot_mentioned(item):
return 'u/hangman_bot' in item.body
def start_new_game(item, active_games):
"""reply to item with a comment containing a new Hangman game and remember it."""
if item.author.name not in active_games:
new_game = Hangman()
active_games[item.author.name] = new_game
item.reply(new_game.display_contents())
def continue_game(guess, active_games):
"""continue a game by replying to guess with the updated hangman state."""
game = active_games[guess.author.name]
guess_content = guess.body.replace(' ','').replace('\n','').lower()
if game.word_correct(guess_content):
remove_and_archive_game(guess, active_games)
guess.reply(WIN)
elif guess_content in game.secret: # possibly make this work for substrings len > 1
game.process_guess(guess_content)
if game.secret == ''.join(game.word_state):
remove_and_archive_game(guess, active_games)
guess.reply(WIN)
else:
guess.reply('Correct!' + game.display_contents())
elif game.lives == 1 or FORFEIT in guess_content:
remove_and_archive_game(guess, active_games)
guess.reply(LOSS + '\n\nWord: ' + game.secret)
else:
game.record_mistake(guess_content)
guess.reply('Incorrect!' + game.display_contents())
def remove_and_archive_game(guess, active_games):
"""remove guess author's game from active, place entry in archive file"""
finished_game = active_games.pop(guess.author.name)
if not os.path.isfile('hangmanbot/archived_games.txt'):
with open('hangmanbot/archived_games.txt', 'w') as f:
json.dump({guess.author.name : [finished_game.__dict__]}, f)
else:
with open('hangmanbot/archived_games.txt', 'r+') as f:
archived_games = json.load(f)
if guess.author.name not in archived_games:
archived_games[guess.author.name] = [finished_game.__dict__]
else:
archived_games[guess.author.name].append(finished_game.__dict__)
# seek(0), dump, truncate completely overwrites the file contents.
f.seek(0)
json.dump(archived_games, f)
f.truncate()
def update_active_games_file(item, active_games):
"""update the save file by writing a new active game or modifying an existing game."""
copied = dict()
for key in active_games:
copied[key] = active_games[key].__dict__
with open('hangmanbot/active_games.txt', 'w') as f:
json.dump(copied, f)
def get_active_games():
"""return a dict of <username, Hangman> corresponding to active games."""
if not os.path.isfile("hangmanbot/active_games.txt"):
return dict()
else:
with open("hangmanbot/active_games.txt") as f:
dict_with_dicts = json.load(f)
dict_with_objects = dict()
for key in dict_with_dicts:
dict_with_objects[key] = Hangman.fromdict(dict_with_dicts[key])
return dict_with_objects
def main():
reddit = authenticate()
active_games = get_active_games()
while True:
run_bot(reddit, active_games)
## end definitions
## begin executions
if __name__ == '__main__':
main()
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T16:17:50.367",
"Id": "484637",
"Score": "0",
"body": "Do you really need an API for a random word? The API provider has provided a means to host it yourself, along with the source code. They have also provided a call that gives you all the words at once, which means you can put them in a file and generate random words yourself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T18:35:15.273",
"Id": "484666",
"Score": "0",
"body": "@spyr03 yes, I suppose the request isn't really necessary and I could download all the words. Do you have any other comments?"
}
] |
[
{
"body": "<p>First of all, this is all pretty good. If it was short, it would be fine. Because it's long, it could use neater organization.</p>\n<p>My biggest feedback is if you separate</p>\n<ol>\n<li>Interacting with the reddit API</li>\n<li>Local persistence to and from files (you may want to have separate persistence for ongoing and archived games)</li>\n<li>Messages to and from players (make them an explicit concept not linked to the reddit API)</li>\n<li>The core hangman game</li>\n</ol>\n<p>then the code will be easy to understand. It will also be easy to reuse, so you can make it cooler (switch out games, add a discord bot to play the same games, change persistence).</p>\n<p>Other than that, this looks fine. Mostly, it's lacking robustness and dealing with errors, which ends up being pretty important for web software and human input. You could add robustness, and learn about that, which will help if you want to be a professional programmer. Or you could decide it's no fun and ignore it. But do keep in mind if you planning to run this in a loop forever, that there are currently likely ways you'll end up spamming people thousands of messages, which will suck for them and you.</p>\n<ul>\n<li>Learn about all the things that can go wrong if you control-C your program halfway though, or if you encounter an exception halfway through. Will your database be corrupt and everyone will lose their game? Will you send people two messages? Will you be unable to get new messages and send them a new message every time your script runs?</li>\n<li>What happens if reddit returns an error? Do you send people multiple messages? One common goal is to make "partial progress"--if you can read messages from 98 people, you should process those 98 turns and mark them as read, not fail for everyone. The errors might be from reddit, or they might be from you.</li>\n</ul>\n<p>You've chosen to store JSON. This is fine, especially if you want to manually debug. There are also built-in serialization methods in Python (pickle, shelve, and marshall). You may encounter some problems if you get more players, runtime errors, or run for a long time.</p>\n<ul>\n<li>If you start having a large number of updates, you'll find that writing and reading the whole file every time becomes a problem. This is a whole area to learn about, I can't really give any concise advice. It's definitely a problem you will run into many times, so it's worth learning the options and common solutions.</li>\n</ul>\n<p>I didn't see any defensive programming in particular, so you might want to think about that or security. I also don't see any specific problems, just mentioning that it's generally good to think about. Keep in mind that a user typing in really weird guesses (doesn't have to be malicious, think just some weird unicode smileys) could crash your game or corrupt the database.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T03:54:18.090",
"Id": "251579",
"ParentId": "247406",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "251579",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T00:01:56.947",
"Id": "247406",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"json",
"api",
"reddit"
],
"Title": "Reddit Hangman Bot Python3"
}
|
247406
|
<p>I wrote this little hook so I could fetch some remote resources:</p>
<pre><code>import {DependencyList, useEffect, useRef, useState} from "react";
export default function useAsyncValue<T>(cb: () => Promise<T>, deps?: DependencyList): T | undefined {
const [value, setValue] = useState<T | undefined>(undefined)
const nonce = useRef(Symbol())
useEffect(() => {
const current = nonce.current = Symbol()
Promise.resolve(cb()).then(result => {
if (nonce.current === current) {
setValue(result)
}
})
return () => {
nonce.current = Symbol()
}
}, deps)
return value
}
</code></pre>
<p>Use is like:</p>
<pre><code>const value = useAsyncValue(() => fetch("..."))
</code></pre>
<p>I added a nonce and some deps too so if you do:</p>
<pre><code>const value = useAsyncValue(() => fetch(`/get?foo=${foo}`), [foo])
</code></pre>
<p>Then you <code>value</code> will always be the latest result, and you won't have any results out-of-order bugs from older fetch returning after a later fetch.</p>
<p>Are there any problems with this? I don't need to pass the <code>counter</code> into the <code>useEffects</code> deps list do I?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T02:19:00.440",
"Id": "247410",
"Score": "3",
"Tags": [
"react.js",
"typescript"
],
"Title": "React hook: useAsyncValue"
}
|
247410
|
<p>I would like to transform the input</p>
<pre class="lang-rb prettyprint-override"><code>elems = [a, b, c]
terms = [t1, t2]
@spec contains?(term, elem) :: boolean
def contains?(term, elem), do: #implementation
</code></pre>
<p>to either of</p>
<pre class="lang-rb prettyprint-override"><code>%{t1 => [a, b], t2 => [c]}
</code></pre>
<p>or</p>
<pre class="lang-rb prettyprint-override"><code>%{t1 => [a], t2 => [b, c]}
</code></pre>
<p>where</p>
<pre class="lang-rb prettyprint-override"><code>t1 |> contains?(a) #=> true
t1 |> contains?(b) #=> true
t1 |> contains?(c) #=> false
t2 |> contains?(a) #=> false
t2 |> contains?(b) #=> true
t2 |> contains?(c) #=> true
</code></pre>
<hr />
<p>My current solution is as follows</p>
<pre class="lang-rb prettyprint-override"><code>defmodule Test do
def contains?(term, elem) do
elem in term
end
def test do
elems = [1,2,3]
terms = [[1,2], [2,3]]
elems
|> Enum.into(%{}, fn elem ->
{elem,
terms |> Enum.find(&contains?(&1, elem))}
end)
|> reverse_map()
end
defp reverse_map(map, reversed \\ %{})
defp reverse_map(map, reversed) when map_size(map) == 0, do: reversed
defp reverse_map(map, reversed) do
[key | _] = Map.keys(map)
{value, map} = Map.pop!(map, key)
reversed = Map.update(reversed, value, [key], &[key | &1])
reverse_map(map, reversed)
end
end
</code></pre>
<p>With this solution I'm generating the map</p>
<pre class="lang-rb prettyprint-override"><code>%{a => t1, b => t1, c => t2}
</code></pre>
<p>then reversing it and collecting collisions in a list.</p>
<p>But I feel this intermediate map is unnecessary and a solution could exist without it.</p>
<p>In addition I'm not sure my implementation of <code>reverse_map</code> is as elegant as it could be.</p>
|
[] |
[
{
"body": "<pre class=\"lang-rb prettyprint-override\"><code>defmodule Test do\n def contains?(term, elem) do\n elem in term\n end\n\n def test do\n elems = [1,2,3]\n terms = [[1,2], [2,3]]\n \n for e <- elems, reduce: %{} do\n acc ->\n key = Enum.find(terms, &contains?(&1, e))\n Map.update(acc, key, [e], &[e|&1])\n end \n #=> %{[1, 2] => [2, 1], [2, 3] => [3]}\n end\nend\n</code></pre>\n<p>Found a simple and elegant solution using a reduce comprehension.<br />\nHere, we iterate over each <code>elem</code> in <code>elems</code>, find the first <code>term</code> which contains it, then update our map with either <code>term => [elem]</code> or <code>term => [elem|previous_elems]</code> depending on if that key exists in the map yet.</p>\n<hr />\n<p>Side note:<br />\nIf I needed the elems in the same as order they were originally I could use <code>& &1 ++ [e]</code> instead of <code>&[e|&1]</code>, but as I don't have that requirement it is more efficient to prepend the list.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T08:17:13.243",
"Id": "247511",
"ParentId": "247411",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "247511",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T02:45:33.690",
"Id": "247411",
"Score": "4",
"Tags": [
"elixir"
],
"Title": "Elixir generate inverted / reversed map"
}
|
247411
|
<p>I have implemented a customized memory allocation class template for an assignment. Codes are commented; Hopefully it's clear. I would love to know if there is any way to make the code more optimized.</p>
<p>Note: <code>int main()</code> should not be modified. From the requirements of my school (Must be adhered to):</p>
<blockquote>
<p>Implement an alloc class template for the purpose of memory management inside of vector objects;</p>
</blockquote>
<blockquote>
<p>It is necessary that I use std::forward_list as an allocator to store the allocated memory;</p>
</blockquote>
<blockquote>
<p>No other headers allowed</p>
</blockquote>
<blockquote>
<p>It is necessary that I use bitwise operations for this assignment (Which I have); Note: use of std::bitset not allowed.</p>
</blockquote>
<blockquote>
<p>It is necessary that I use std::forward_list::remove_if() (Which I did), to check if there are anymore elements in the block, otherwise, remove it; Implementation for this could change if it can be more optimized, but have to make sure to stick with the use of std::forward_list::remove_if()</p>
</blockquote>
<blockquote>
<p>Struct vector and union _vertex should remain the way they are, since it was given as part of the assignment</p>
</blockquote>
<blockquote>
<p>Code must be implemented using c++17. Implementation that is compatible with g++ is only required.</p>
</blockquote>
<blockquote>
<p>Output for the code should not change.</p>
</blockquote>
<pre><code>#include<iostream>
#include<forward_list>
namespace Ns
{
// Elements of Data_type_T, bit mask of type Flags_T
template <typename Data_type_T, typename Flags_T>
class N_allocator
{
static const size_t poolSize_ = sizeof(Flags_T) * 8;
//To generate a bitflag according to the no. of bits required
Flags_T Bits_needed(size_t sz)
{
uint32_t mask = 0xFFFFFFFF >> (32 - sz);
return (Flags_T)(mask);
}
struct Pool
{
//buffer for pool
Data_type_T Pool_data_[poolSize_];
Flags_T bitsInPool;
};
std::forward_list<Pool> linkedList;
//For the allocation of a new memory block & adds to the list of blocks
Data_type_T* create_pool(size_t size)
{
std::cout << " Allocating new pool." << std::endl;
Pool pool;
pool.bitsInPool = Bits_needed(size);
linkedList.push_front(pool);
std::cout << " The pool found for " << size
<< " elements @ index 0." << std::endl;
return linkedList.front().Pool_data_;
}
public:
using N_pointer = Data_type_T*;
//To find a continuous memory of N size & returns a pointer to 1st
//element, then allocates a new block if a suitable slot is not found
N_pointer alloc(size_t size_avail)
{
std::cout << std::endl
<< " Allocator alloc " << size_avail
<< " elements. " << std::endl;
if (size_avail > poolSize_)
{
throw std::bad_alloc();
}
if (!linkedList.empty())
{
//for shifting bitsinpool by 'countOfE' no.of times
size_t countOfE = poolSize_ - size_avail;
for (Pool& pool : linkedList)
{
Flags_T flag_chk = Bits_needed(size_avail);
//for running a check against the bit flag of current to see if a suitable slot
//is found
for (size_t i=0; i < countOfE; i++)
{
Flags_T condition = static_cast<Flags_T>
((flag_chk & (~pool.bitsInPool)));
//check if element at i was allocated previously,
//otherwise, don't set
if (condition == flag_chk)
{
std::cout << " The pool found for "
<< size_avail << " elements @ index "
<< i << "." << std::endl;
//only do set if element at the index i in the
//pool is allocated
pool.bitsInPool |= flag_chk;
//return the address of the element corresponding
//to the index of the first bit found
return (&pool.Pool_data_[i]);
}
//shift flag for nxt round of bit checking
flag_chk = static_cast<Flags_T>(flag_chk << 1);
}
std::cout << " Can't find space in pool."
<< std::endl
<< " Searching for next avail pool..."
<< std::endl;
}
//if slots have run out, alloc a new pool
return create_pool(size_avail);
}
else
{ //If no pool exist, alloc new pool
return create_pool(size_avail);
}
}
//To find the matching block that the pointer belongs to, marks N bits
//after the pointer's index as unused. Removes block from list if all
//elements are unused
void dealloc(N_pointer pv, size_t sz)
{
std::cout << " Deallocate "
<< sz << " elements. " << std::endl;
for (Pool& pool : linkedList)
{
//size_t offset = addr - root;
size_t offset = (size_t)(pv - pool.Pool_data_);
//if memory offset less than pool size
if (offset < poolSize_)
{
Flags_T flag = Bits_needed(sz);
flag = static_cast<Flags_T>(flag << offset);
//Mark deallocation of element by flipping
//then Or-ing bit then flip result again
Flags_T n_flag = static_cast<Flags_T>
((flag | (~pool.bitsInPool)));
pool.bitsInPool = static_cast<Flags_T>(~n_flag);
std::cout << " Have found " << sz
<< " elements in a pool." << std::endl;
break;
}//iterate to next block
std::cout << " Searching next existing pool..."
<< std::endl;
}
//if there are no elements used in a memory block
//after deallocation, the pool should be removed
linkedList.remove_if([&](Pool& pool)
{
bool checkRemoval = (pool.bitsInPool == 0) ? true : false;
if (checkRemoval)
std::cout << " Remove empty pool." << std::endl;
return checkRemoval;
});
}
};
struct vector
{
//A default ctor for a vector type
float x;float y;float z;float w;
vector() : x{ 0 },y{ 0 },z{ 0 },w{ 0 }{}
//A non Default ctor for vector type
vector(float ax1, float ay, float az, float aw) :
x{ ax1 },y{ ay },z{ az },w{ aw }{}
};
union _vertex
{
vector vertex_coord;
float axisCoordinates[sizeof(vector) / sizeof(float)];
//A default ctor for vertex type
_vertex() :
vertex_coord{}{}
//A non-default ctor for vertex type
_vertex(float ax1, float ay, float az, float aw) :
vertex_coord{ ax1, ay, az, aw }{}
};
}
void test4()
{
std::cout << "Allocator_:\n-----" << std::endl;
Ns::N_allocator<Ns::_vertex, short> N_allocator;
using N_pointer = decltype(N_allocator)::N_pointer;
N_pointer p1 = N_allocator.alloc(10);
N_pointer p2 = N_allocator.alloc(4);
N_allocator.dealloc(p1, 10);
N_pointer p3 = N_allocator.alloc(16);
N_pointer p4 = N_allocator.alloc(8);
N_allocator.dealloc(p4, 8);
N_allocator.dealloc(p3, 16);
N_allocator.dealloc(p2, 4);
N_pointer pv5 = N_allocator.alloc(32);
N_allocator.dealloc(pv5, 32);
std::cout << std::endl;
}
int main()
{
using test_ = void (*)();
test_ tests[] =
{
test4
};
int i = 0;
for (const test_& test : tests)
{
try
{
std::cout << (++i) << ". ";
test();
std::cout << std::endl;
}
catch (std::exception& e)
{
std::cout << "\nError: " << e.what() << std::endl;
}
catch (...)
{
std::cout << "\nUnknown error occurred." << std::endl;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T07:16:53.490",
"Id": "484205",
"Score": "0",
"body": "Note: No other headers allowed as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-10T07:33:46.320",
"Id": "485002",
"Score": "0",
"body": "Please do not update the code in your question after receiving answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-10T07:36:52.467",
"Id": "485004",
"Score": "1",
"body": "Oh. My apologies for that. I didn't know. Thanks for the heads up!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-10T07:38:32.203",
"Id": "485005",
"Score": "0",
"body": "No problem, there's no penalty and most new users are not aware of it."
}
] |
[
{
"body": "<h1>Try to be more consistent with naming</h1>\n<p>I'm seeing <a href=\"https://en.wikipedia.org/wiki/Camel_case\" rel=\"nofollow noreferrer\">camelCase</a>, <a href=\"https://en.wikipedia.org/wiki/Pascal_case\" rel=\"nofollow noreferrer\">PascalCase</a> and <a href=\"https://en.wikipedia.org/wiki/Snake_case\" rel=\"nofollow noreferrer\">snake_case</a> all mixed together. Pick one style and stick with it. Furthermore, I see redundant things in names like <code>Data_type_T</code>, inconsistent use of the underscore suffix for private member variables, sometimes even using an underscore prefix which <a href=\"https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier\">you should avoid</a>.</p>\n<p>I would suggest that you stick with the style used in the standard library, so that you can use one style throughout programs that use both your custom allocator and functions and classes from the standard library. So:</p>\n<ul>\n<li><code>Data_type_T</code> -> <code>data_type</code></li>\n<li><code>Flags_T</code> -> <code>flags_type</code></li>\n<li><code>poolSize_</code> -> <code>pool_size</code></li>\n<li><code>Bits_needed</code> -> <code>bits_needed</code></li>\n<li><code>_vertex</code> -> <code>vertex</code></li>\n<li>...</li>\n</ul>\n<p>Also avoid unnecessary abbreviations. For example, instead of <code>flag_chk</code>, just write <code>flag_check</code>, or even better <code>flags_to_check</code>.</p>\n<h1>Naming things</h1>\n<p>Names should clearly express what something is about. When I look at some of the names in your code, I have some questions:</p>\n<ul>\n<li><code>namespace Ns</code>: what does "Ns" mean? Is it an abbreviation for "namespace"? That would be very redundant. Is it even necessary to put things into a namespace here?</li>\n<li><code>Flags_T</code>: this is not really a set of flags, but rather the type of the bit mask to use to keep track of allocated elements, as you already say in the comments. So perhaps name it <code>bit_mask_type</code>.</li>\n<li><code>N_allocator</code>: what does the "N" mean? I think <code>pool_allocator</code> might be a better name for this class.</li>\n<li><code>linkedList</code>: yes, this variable's <em>type</em> is a linked list, but wat does it actually do? It's there to keep track of the pools you have, so I would instead just name it <code>pools</code>.</li>\n<li><code>N_pointer</code>: again, the "N" doesn't mean anything to me. I would not create an alias here at all, if you want something that is a pointer to a data element, then <code>data_type *</code> is perfectly clear.</li>\n<li><code>bitsInPool</code>: this is a bit mask that keeps track of which elements in this pool are allocated. Since the type of the variable is already <code>bit_mask_type</code>, you shouldn't repeat that in the name. So perhaps <code>allocated_elements</code>, or in this case I think you can shorten it to <code>allocated</code>, as this is clear enough from the context.</li>\n<li><code>size_avail</code>: this is not the size of how much is available, it is rather a count of the number of elements the caller wants to allocate. Since the fact that it's about allocation is already clear from the context, I would name this <code>count</code>.</li>\n<li><code>countOfE</code>: what's an "E"? This variable holds the number of times you have to shift to find a free range in a pool. Maybe <code>number_of_shifts</code>, or more shortly <code>n_shifts</code> would be appropriate.</li>\n<li><code>flag_chk</code>: that should be something like <code>mask_to_check</code>, or <code>candidate_mask</code>, as it is the bit mask that you want to check whether it would fit into the pool.</li>\n<li><code>condition</code>: this variable is probably not necessary, see below.</li>\n</ul>\n<h1>Avoid using <code>std::endl</code></h1>\n<p>Use <code>"\\n"</code> instead of <code>std::endl</code>, the latter forces the output to be flushed, which can be inefficient. See <a href=\"https://stackoverflow.com/questions/213907/c-stdendl-vs-n\">this question</a> for more details.</p>\n<h1>Remove debug statements</h1>\n<p>I see a lot of messages being printed to <code>std::cout</code> that are just debug statements. They should not end up in production code, so remove them.</p>\n<h1>Remove redundant comments</h1>\n<p>Comments should only be added if the code itself is unclear. Comments that merely repeat exactly what the code does are unhelpful. For example:</p>\n<pre><code>for (Pool& pool : linkedList)\n{\n ...\n //iterator to next block\n}\n</code></pre>\n<p>The comment there is redundant, of course you will iterate to the next element at the end of the body of a <code>for</code>-loop. Similarly:</p>\n<pre><code>//A default ctor for vertex type\n_vertex() :\n vertex_coord{}{}\n//A non-default ctor for vertex type\n_vertex(float ax1, float ay, float az, float aw) :\n vertex_coord{ ax1, ay, az, aw }{}\n</code></pre>\n<p>It is obvious from the code that you are declaring constructors here, the type is already in the name of the constructor function, and whether it's a default constructor is obvious from the fact that the first one doesn't take parameters while the second does.</p>\n<p>And here you just repeat literally what the code does:</p>\n<pre><code>//size_t offset = addr - root; \nsize_t offset = (size_t)(pv - pool.Pool_data_);\n</code></pre>\n<h1>Simplify the check for free space in a pool</h1>\n<p>Instead of inverting the <code>bitsInPool</code>, and checking if the result of that ANDed with the candidate bit mask is still the same as the bit mask, you can just write this:</p>\n<pre><code>if ((flag_chk & pool.bitsInPool) == 0) {\n // it fits, add it to this pool\n}\n</code></pre>\n<p>Since if there is no overlap between the bits set in <code>flag_chk</code> and the bits set in <code>bitsInPool</code>, the result of the AND operation will be zero.</p>\n<h1>Improve <code>Bits_needed()</code></h1>\n<p>The problem with your version of <code>Bits_needed()</code> is that it expects the type of bit mask to be 32 bits or less. But what if I use an <code>uint64_t</code> as the bit mask type, and want to allocate more that 32 bits? It will fail. The function can be rewritten like this:</p>\n<pre><code>Flags_T Bits_needed(size_t sz)\n{\n return ~Flags_T{} >> (poolSize_ - sz)\n}\n</code></pre>\n<p>First, it creates a zero of the right type, inverts all the bits, and then shifts it right by the right amount.</p>\n<h1>Remove redundant <code>static_cast</code>s</h1>\n<p>I see a lot of <code>static_cast<Flags_T></code> that look completely redundant. For example:</p>\n<pre><code>flag_chk = static_cast<Flags_T>(flag_chk << 1);\n</code></pre>\n<p>Why? The type doesn't change here, and even if it did, assigning the value back to <code>flag_chk</code> would implicitly cast it for you. And in this case, you can even write this to:</p>\n<pre><code>flag_chk <<= 1;\n</code></pre>\n<h1>Use more <code>auto</code></h1>\n<p>There are a lot of places where you can use <code>auto</code> to reduce the number of times you have to repeat type names. For example:</p>\n<ul>\n<li><code>for (Pool& pool : linkedList)</code> -> <code>for (auto& pool : linkedList)</code></li>\n<li><code>Flags_T flags = Bits_needed(sz)</code> -> <code>auto flags = Bits_needed(sz)</code></li>\n</ul>\n<h1>Redundant use of <code>? true : false</code></h1>\n<p>It is almost always redundant to write <code>some_condition ? true : false</code>, since the condition itself will be a boolean, or it can be cast implicitly to a boolean, otherwise the ternary operator wouldn't work. So:</p>\n<pre><code>bool checkRemoval = (pool.bitsInPool == 0) ? true : false;\n</code></pre>\n<p>Can just be written as:</p>\n<pre><code>bool checkRemoval = pool.bitsInPool == 0;\n</code></pre>\n<p>But then the whole call to <code>remove_if</code> can be simplified to:</p>\n<pre><code>linkedList.remove_if([](Pool& pool){ return pool.bitsInPool == 0; });\n</code></pre>\n<p>Note that you don't needed to capture anything in the lambda here, so use <code>[]</code> instead of <code>[&]</code>.</p>\n<h1>Invalid assumptions about pointer ordering in <code>dealloc()</code></h1>\n<p>Your <code>dealloc()</code> function contains the following code:</p>\n<pre><code>size_t offset = (size_t)(pv - pool.Pool_data_);\n//if memory offset less than pool size\nif (offset < poolSize_)\n{\n ...\n</code></pre>\n<p>Here you assume that the first pool's <code>Pool_data_</code> will always have the lowest address. But there is absolutely no guarantee that newly allocated pools will always have an address that is higher than the previously allocated pool. But it gets even worse, it is actually undefined behaviour in C++ to do <a href=\"https://en.cppreference.com/w/c/language/operator_comparison\" rel=\"nofollow noreferrer\">pointer comparison</a> between two pointers that point to different arrays. But, if you are willing to assume that pointer comparisons do actually work as expected on your platform, then you should write:</p>\n<pre><code>if (pv >= pool.Pool_data_ && pv < pool.Pool_data_ + poolSize_)\n{\n // pv is inside this pool\n</code></pre>\n<h1>Simplify clearing bits in <code>dealloc()</code></h1>\n<p>You have four lines of code to just unset a few bits in one variable, making it more complicated than necessary. You can simplify it to:</p>\n<pre><code>pool.bitsInPool &= ~(Bits_needed(sz) << (pv - pool.Pool_data_));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T11:59:10.433",
"Id": "484244",
"Score": "1",
"body": "Hey @G.Sliepen! Thank you very much for the much needed advice and recommendations! Really appreciate your help."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T04:51:28.100",
"Id": "484343",
"Score": "4",
"body": "Just a short comment on your comments to naming, it's actually `camelCase`, `PascalCase` and `snake_case`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T08:01:52.773",
"Id": "484356",
"Score": "2",
"body": "@MindSwipe Thanks, I updated the answer!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T11:53:53.240",
"Id": "247433",
"ParentId": "247412",
"Score": "19"
}
}
] |
{
"AcceptedAnswerId": "247433",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T03:32:40.800",
"Id": "247412",
"Score": "11",
"Tags": [
"c++",
"memory-management",
"homework",
"c++17"
],
"Title": "Customization of memory class C++"
}
|
247412
|
<p>I made a helper function for drawing the <code>map(OpenLayers)</code>.<br />
Then I made another helper function for <code>fetch(axios.get)</code> the map URL.</p>
<p>So my question is should I switch from</p>
<ul>
<li>from <code>.then()</code> (<code>loadMap_before()</code>)</li>
<li>to <code>async/await </code> (<code>loadMap()</code>) ?</li>
</ul>
<p>Which way is better?</p>
<p>Or option3 is the best where <code>loadMapUrl()</code> helper is totally unnecessary?</p>
<p>Is there any other place where I can improve my code?</p>
<h3>Option #1 with <code>promise.then</code></h3>
<pre><code>export const loadMapUrl_before = (storeMapUrl, storeMapExtent) => {
let result = {}
if (!storeMapUrl) {
getNaviMap().then(res => {
result.mapExtent = [res.data.origin_x, res.data.origin_y,
res.data.width * res.data.resolution + res.data.origin_x,
res.data.height * res.data.resolution + res.data.origin_y];
result.mapUrl = res.data.image_url})
.catch(...)
} else {
result.mapExtent = storeMapExtent
result.mapUrl = storeMapUrl
}
return result
}
</code></pre>
<h3>Option #2 with <code>async/await</code></h3>
<pre><code>//load map url from store or get it through axios request
export const loadMapUrl = async (storeMapUrl, storeMapExtent) => {
let result = {}
if (!storeMapUrl) {
let res = await getNaviMap()
result.mapExtent = [res.data.origin_x, res.data.origin_y,
res.data.width * res.data.resolution + res.data.origin_x,
res.data.height * res.data.resolution + res.data.origin_y];
result.mapUrl = res.data.image_url
} else {
result.mapExtent = storeMapExtent
result.mapUrl = storeMapUrl
}
return result
}
</code></pre>
<h3>Usage</h3>
<pre><code>// where I call loadMapUrl()
export const loadMap = async (storeMapUrl, storeMapExtent, map, mapLayer) => {
let mapUrl = '', mapExtent = []
await loadMapUrl(storeMapUrl, storeMapExtent).then(result => {
mapUrl = result.mapUrl
mapExtent = result.mapExtent
})
const projection = new Projection({
code: 'EPSG:4326',
units: 'degrees',
extent: mapExtent
});
map.setView(new View({
center: getCenter(mapExtent),
projection: projection,
zoom: map.getView().getZoom(),
minZoom: 0.1,
maxZoom: 7
}));
const source = new Static({
attributions: 'xxx',
url: mapUrl,
projection: projection,
imageExtent: mapExtent
});
mapLayer.setSource(source);
};
</code></pre>
<h3>Option #3 the helper for axios request might be redundant</h3>
<pre><code>export const loadMap = async (storeMapUrl, storeMapExtent, map, mapLayer) => {
let mapUrl = '', mapExtent = []
if (!storeMapUrl) {
let res = await getNaviMap()
mapExtent = [res.data.origin_x, res.data.origin_y,
res.data.width * res.data.resolution + res.data.origin_x,
res.data.height * res.data.resolution + res.data.origin_y];
mapUrl = res.data.image_url
} else {
mapExtent = storeMapExtent
mapUrl = storeMapUrl
}
...
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T09:56:19.490",
"Id": "484228",
"Score": "0",
"body": "Your `loadMapUrl_before` doesn't seem to be completely working when you don't have a `storeMapUrl` (at least you are returning result which would be only filled by the promise and not before)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T11:43:52.937",
"Id": "484242",
"Score": "0",
"body": "@Icepickle Hi, thanks for the replay, legit concern but you might not be noticed that I used await with loadMapUrl_before, so I think should be fine to return a pending promise"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T12:57:18.793",
"Id": "484253",
"Score": "0",
"body": "But, you are not returning a pending promise, you are returning `result` for option1"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T01:00:23.780",
"Id": "484439",
"Score": "0",
"body": "@Icepickle loadMap() can be a regular function without async/await"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T12:41:41.907",
"Id": "484499",
"Score": "0",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T05:51:35.420",
"Id": "484584",
"Score": "0",
"body": "@Mast Thanks a lot for the editing"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T06:04:01.193",
"Id": "484585",
"Score": "0",
"body": "No problem. Will you manage to change the title yourself?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T03:37:04.770",
"Id": "247414",
"Score": "2",
"Tags": [
"javascript",
"ecmascript-6",
"async-await",
"axios"
],
"Title": "Which one should I choose for simple task: async/await or promise.then?"
}
|
247414
|
<p>FEN strings are compact representations of chess board positions which allows you to derive the necessary information to start playing a chess game from that position. This includes things like the pieces on the board, castle statuses, etc. More information here: <a href="https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation</a></p>
<p>I have written a simple function in go to decode a FEN string into separate variables with suitable types for each of the desired pieces of information that FEN strings represent, and I would like to see if I am parsing the FEN string in a reasonable manner.</p>
<pre class="lang-golang prettyprint-override"><code>import (
"strings"
)
type pair struct {
x, y int8
}
func decodeFen(fen string) ([8][8]int8, int8, [4]bool, pair, int8, int) {
split := strings.Split(fen, " ")
var board [8][8]int8
board_split := strings.Split(split[0], "/")
for r, row := range board_split {
var col_ind int8
for _, char := range row {
if char >= 49 && char <= 57 {
for i := int8(0); i < int8(char) - 48; i++ {
board[r][col_ind] = '-'
col_ind++
}
} else {
board[r][col_ind] = int8(char)
col_ind++
}
}
}
var color int8
if split[1] == "w" {
color = 1
} else {color = 2}
var castle_status [4]bool
var status_map = map[rune]int8 {
'K' : 0, 'Q' : 1, 'k' : 2, 'q' : 3}
if split[2] != "-" {
for _, char := range split[2] {
castle_status[status_map[char]] = true
}
}
var ep_pos pair = pair{-1, -1}
if split[3] != "-" {
x_label := split[3][0]
y_label := split[3][1]
y_label -= 48
ep_pos = pair{int8(x_label - 97), int8(y_label - ((y_label - 1) - (8 - y_label)) - 1)}
}
var halfmove_clock int8 = int8(split[4][0]) - 48
var fullmove_number int = int(split[5][0]) - 48
return board, color, castle_status, ep_pos, halfmove_clock, fullmove_number
}
</code></pre>
<p>This is really just a parsing problem, and to split the strings I decided to use the Split() function from the <code>strings</code> go library, rather than writing my own. Any improvements and feedback for this code would be great, and I apologize if I am not correctly asking this question as this is my first post in this community.</p>
|
[] |
[
{
"body": "<p>Code should be correct, maintainable, robust, reasonably efficient, and, most importantly, readable.</p>\n<hr />\n<p>To be certain that the code is correct, carefully read the specification and related documents.</p>\n<p><a href=\"https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation\" rel=\"nofollow noreferrer\">Forsyth–Edwards Notation</a></p>\n<p><a href=\"https://www.chessclub.com/help/PGN-spec\" rel=\"nofollow noreferrer\">PGN-SPEC</a></p>\n<p><a href=\"https://en.wikipedia.org/wiki/Portable_Game_Notation\" rel=\"nofollow noreferrer\">Portable Game Notation</a></p>\n<p><a href=\"https://en.wikipedia.org/wiki/Algebraic_notation_(chess)\" rel=\"nofollow noreferrer\">Algebraic notation (chess)</a></p>\n<p><a href=\"https://en.wikipedia.org/wiki/Chess\" rel=\"nofollow noreferrer\">Chess</a></p>\n<p>For a code review, compare the specification and the code implementing it side-by-side.</p>\n<hr />\n<p>In chess, there are pieces placed on squares which are organized into ranks and files to form a board. There doesn't appear to be any references to these basic concepts, apart from board, in <code>decodeFen</code>. Therefore, comparison of code to specification is difficult.</p>\n<p>"PGN is "Portable Game Notation", a standard designed for the representation of chess game data using ASCII text files. PGN data is represented using a subset of the eight bit ISO 8859/1 (Latin 1) character set." Therefore,</p>\n<pre><code>var board [8][8]int8\n</code></pre>\n<p>is incorrect. Characters are not type <code>int8</code> (8-bit signed integers). Characters are type <code>byte</code> (8 bits).</p>\n<pre><code>var board [8][8]byte\n</code></pre>\n<p>The code</p>\n<pre><code>for _, char := range row { ... }\n</code></pre>\n<p>expects a UTF-8 encoded string. UTF-8 encoding is not the same as ISO 8859/1 encoding.</p>\n<p>Go is a safe, statically typed language. The code</p>\n<pre><code>board[r][col_ind] = int8(char)\n</code></pre>\n<p>is a failed attempt to correct errors when ISO 8859/1 encoding is decoded as UTF-8 encoding.</p>\n<p>The <code>decodeFen</code> code is a "stream-of-conciousness" code that is hard to read and prove correct. The code is missing fundamental concepts like functions to encapsulate complexity and implementation details. For example, organize <code>decodeFen</code> as a series of calls to parse functions for each FEN field.</p>\n<hr />\n<p>As an example, consider the FEN piece placement field. Here's a first draft:</p>\n<p><code>pieces.go</code>:</p>\n<pre><code>package main\n\nimport (\n "errors"\n "fmt"\n "strings"\n)\n\ntype Board [8][8]byte\n\nconst (\n whitePieceLetters = "PNBRQK"\n blackPieceLetters = "pnbrqk"\n pieceLetters = whitePieceLetters + blackPieceLetters\n)\n\nfunc isPiece(p byte) bool {\n for i := 0; i < len(pieceLetters); i++ {\n if p == pieceLetters[i] {\n return true\n }\n }\n return false\n}\n\nvar (\n ErrRankOutOfRange = errors.New("rank out of range")\n ErrFileOutOfRange = errors.New("file out of range")\n ErrPieceInvalid = errors.New("piece invalid")\n)\n\nfunc parseFENPieces(board *Board, pieces string) error {\n ranks := strings.Split(pieces, "/")\n if len(ranks) != len(board) {\n return ErrRankOutOfRange\n }\n for r, rank := range ranks {\n f := 0\n for i := 0; i < len(rank); i++ {\n piece := rank[i]\n if piece >= '0' && piece <= '9' {\n for j := byte(0); j < piece-'0'; j++ {\n if f >= len(board[0]) {\n return ErrFileOutOfRange\n }\n board[r][f] = '-'\n f++\n }\n } else {\n if f >= len(board[0]) {\n return ErrFileOutOfRange\n }\n if !isPiece(piece) {\n return ErrPieceInvalid\n }\n board[r][f] = piece\n f++\n }\n }\n if f != len(board[0]) {\n return ErrFileOutOfRange\n }\n }\n return nil\n}\n\nfunc main() {\n fens := []string{\n // https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation\n "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",\n "rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1",\n "rnbqkbnr/pp1ppppp/8/2p5/4P3/8/PPPP1PPP/RNBQKBNR w KQkq c6 0 2",\n "rnbqkbnr/pp1ppppp/8/2p5/4P3/5N2/PPPP1PPP/RNBQKB1R b KQkq - 1 2",\n }\n var board Board\n for _, fen := range fens {\n fields := strings.Split(fen, " ")\n if len(fields) > 0 {\n pieces := strings.Split(fen, " ")[0]\n fmt.Println(pieces)\n err := parseFENPieces(&board, pieces)\n fmt.Println(err)\n for i := range board {\n fmt.Printf("%c\\n", board[i])\n }\n }\n }\n}\n</code></pre>\n<p>Playground: <a href=\"https://play.golang.org/p/-pPnCs2GMao\" rel=\"nofollow noreferrer\">https://play.golang.org/p/-pPnCs2GMao</a></p>\n<p>Output:</p>\n<pre><code>rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR\n<nil>\n[r n b q k b n r]\n[p p p p p p p p]\n[- - - - - - - -]\n[- - - - - - - -]\n[- - - - - - - -]\n[- - - - - - - -]\n[P P P P P P P P]\n[R N B Q K B N R]\n</code></pre>\n<p>Use chess terminology to match the specification.</p>\n<p>The chess board data structure is ubiquitous. Give it a type:</p>\n<pre><code>type Board [8][8]byte\n</code></pre>\n<p>In Go, arguments are passed by value. For an array, the value is the entire array. Therefore, for efficiency, we use a pointer (8 bytes or 4 bytes) rather than an array (64 bytes).</p>\n<p>Input must be valid. Make no assumptions about external input. Report errors.</p>\n<p>Don't use magic values: 49 is '0', 57 is '9'.</p>\n<p>And so forth.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T21:55:23.550",
"Id": "247458",
"ParentId": "247415",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "247458",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T03:48:14.567",
"Id": "247415",
"Score": "4",
"Tags": [
"go",
"chess"
],
"Title": "Decode FEN string into separate variables for the 6 categories"
}
|
247415
|
<p>I have a class as follows, where I want the user of the class to know that <strong>setting</strong> the Slug property <strong>to null is supported</strong>, and its <strong>getter will still return a valid value</strong>:</p>
<pre><code>public class Post
{
public string Title { get; }
public Post(string title)
{
Title = title;
}
private string? slug;
public string Slug
{
get
{
if(slug is null)
{
slug = Title.Slugify();
}
return slug;
}
set => slug = value;
}
}
</code></pre>
<p>There are two possible cases here:</p>
<p><strong>CASE 1:</strong> No slug is set on/after initialization OR the slug is initialized with a non-null string.</p>
<pre><code>var post = new Post("foo bar");
var slug = post.Slug; // foo-bar
var post2 = new Post("foo bar 2") { Slug = "foo-bar-2" };
var slug2 = post.Slug; // foo-bar-2
</code></pre>
<p><strong>CASE 2:</strong> The slug set on is initialization with a nullable string.</p>
<pre><code>string? maybeNull = viewModel.Slug; // may or may not be null
var post = new Post("foo bar") { Slug = maybeNull! };
var slug = post.Slug; // returns an expected value
</code></pre>
<p>Is there a better way to do this, than using the null forgiving operator? The above code looks worse if I had to set it to null:</p>
<pre><code>var post = new Post("foo bar") { Slug = null! };
var slug = post.Slug; // returns an expected value
</code></pre>
<p>The reason I dont want to use the null forgiving operator is because it requires the user of the <code>Post</code> class to know that a null value can be safely passed into its <code>Slug</code> property -- something I wish to avoid.</p>
<p>If it's not possible to have different nullability for getters and setters (appears to me like it's not), what is the best way to communicate my intent (users can safely set <code>Slug</code> to <code>null</code> + users will always get a valid slug, irrespective of what was set).</p>
<p>For some more context:</p>
<ul>
<li>the <code>Post</code> class is instantiated with a nullable value only while creating a Post. Every other time, it's going to be pulled from a database, and so will always be instantiated with a valid slug.</li>
<li>the <code>Post</code> class is not a ORM model.</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T06:25:51.870",
"Id": "484197",
"Score": "2",
"body": "Did you think about adding a method \"useTitleAsSlug\", while leaving the setter to not accepts null? That way it may be more explicit. Anyway maybe the setter should check the null and getter should not modify the internals..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T06:50:37.427",
"Id": "484199",
"Score": "0",
"body": "@gldraphael. In case of null if you can specify a fallback value then all need to do is to modify the setter of `Slug` like this: `set => slug = !string.IsNullOrEmpty(value)? value : fallbackValue;`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T07:09:19.053",
"Id": "484201",
"Score": "0",
"body": "@slepic I did consider adding a method, but was hoping to avoid that. (My goal is to communicate that **set**ting a valid slug is optional, the user of the class will still **get** a valid slug.) If the setter checks the value, there's the getter might return null if the setter wasn't used. Lazy initializing a property in the getter is a common pattern in C#. Peter, that will still require me to use the null forgiving operator."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T07:12:00.960",
"Id": "484203",
"Score": "0",
"body": "What prompted you to write this? Your examples look very hypothetical and your question is attracting close-votes [for lack of review context](https://codereview.meta.stackexchange.com/a/3652/52915)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T07:15:51.627",
"Id": "484204",
"Score": "0",
"body": "@Mast thank you for your comment. Not sure what makes the example look hypthetical, is there something else you suggest I add to the question? Here's where my example is from: https://github.com/gldraphael/evlog/blob/bb400215f93ef67936d27f35502860b2180a7f50/src/Evlog.Core/Entities/EventAggregate/EventPost.cs#L12-L22 (I wanted to avoid adding an external link to the question)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T07:21:21.237",
"Id": "484206",
"Score": "1",
"body": "That file is different from what you posted, is your code supposed to replace it? As I suggested, please add what prompted you to write this to the question. It's part of an EventAggregate it seems, that's valuable information."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T07:25:50.287",
"Id": "484207",
"Score": "0",
"body": "@Mast honestly at this point if non-C# community members want to close it I'm cool with that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T07:26:13.117",
"Id": "484208",
"Score": "0",
"body": "I still believe the question is valid, and not hypothetical."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T07:29:29.767",
"Id": "484209",
"Score": "0",
"body": "Do you or do you not want to turn this into a great question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T07:32:06.517",
"Id": "484210",
"Score": "0",
"body": "@Mast I want to, but don't see what I'm missing. Can we hop on chat please? The code works fine, but the null forgiving operator in this instance doesn't communicate the right thing to the user of the class. I'm looking for alternatives to \"communicate\" the original intention. (Aggregates are just a way of grouping things. The constructor in this question needs to be added to that file, I work on that project in weekends.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T09:30:40.823",
"Id": "484220",
"Score": "0",
"body": "As far as I can see, your answer is in https://www.meziantou.net/csharp-8-nullable-reference-types.htm under 'Preconditions attributes: AllowNull / DisallowNull'"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T09:39:30.923",
"Id": "484221",
"Score": "1",
"body": "Unless I misunderstood, you are contradicting yourself: **(1)** _\"I want the user of the class to know that setting the Slug property to null is supported\"_ **(2)** _\"it requires the user of the Post class to know that a null value can be safely passed into its Slug property -- something I wish to avoid\"_"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T09:47:21.400",
"Id": "484223",
"Score": "0",
"body": "@dumetrulo The `[AllowNull]` was exactly what I was looking for. Din't know that existed. Thanks a ton."
}
] |
[
{
"body": "<p>I'm thinking you should probably change your <code>Post</code> class as follows:</p>\n<pre><code>public class Post\n{\n public string Title { get; }\n public string Slug { get; set; }\n public Post(string title)\n {\n Title = title;\n Slug = title.Slugify();\n }\n}\n</code></pre>\n<p>Now you have a slugified title by default. However, if a user of the <code>Post</code> class wants to provide an alternative slug, they can still do that:</p>\n<pre><code>var post = new Post("foo bar") { Slug = altSlug };\n</code></pre>\n<p>The explanation for the user should be that they can either provide a slug explicitly, or have one auto-created by omitting it from the initializer. The only thing you cannot do with this code is set <code>Slug</code> to <code>null</code> explicitly. But I think it would not be good design to allow that.</p>\n<p>On a side note, you might even want to make the <code>Slug</code> property getter-only, creating an immutable class, and providing a second constructor that takes the alternative slug. This makes reasoning easier:</p>\n<pre><code>public class Post\n{\n public string Title { get; }\n public string Slug { get; }\n public Post(string title) : Post(title, title.Slugify()) {}\n public Post(string title, string slug)\n {\n Title = title;\n Slug = slug;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T09:50:39.353",
"Id": "484225",
"Score": "0",
"body": "Thanks for the answer, can you please add the `[AllowNull]` to it? I considered making an immutable (`PostMetadata`) class too, perhaps with C# 9's record types that will feel more natural as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T09:52:40.160",
"Id": "484226",
"Score": "1",
"body": "The thing is, if you take the design as suggested in this answer, you don't need the ``[AllowNull]`` attribute anymore."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T09:54:26.283",
"Id": "484227",
"Score": "0",
"body": "I agree, and on second thought what you suggest feels more clear too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T09:56:47.217",
"Id": "484229",
"Score": "0",
"body": "And if you find that you need settable properties for serialization or something, using ``get; private set;`` is probably the answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T19:36:51.050",
"Id": "484308",
"Score": "0",
"body": "How about a constructor forcing a non-null `slug` value, and no public setter for it. Besides an exception for passing `null` , a default value or perhaps the [null object pattern](https://en.wikipedia.org/wiki/Null_object_pattern) could be a possibility. In any case the allow null but can't be null contradiction must be resolved."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T21:50:22.840",
"Id": "484322",
"Score": "0",
"body": "@radarbob When using non-nullable references in C# (which is what the OP's question is about), the code presented here already forces ``slug`` to be non-null."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T01:00:20.807",
"Id": "484336",
"Score": "0",
"body": "@dumetrulo, yeah, but I was thinking about Flater's answer: \"... your question revolves around intent and communication ...\""
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T09:44:56.173",
"Id": "247427",
"ParentId": "247416",
"Score": "4"
}
},
{
"body": "<p>This answer is more philosophical than it is technical, as your question revolves around intent and communication, not technical implementation or syntax (directly). You have some expectations, but aren't quite taking them to their logical conclusion.</p>\n<p>If you're just interested in the code, read the last section. The rest is explanation and justification as to why this is a better approach.</p>\n<hr />\n<h2>Your intentions are unclear</h2>\n<blockquote>\n<p>I want the user of the class to know that setting the Slug property to null is supported</p>\n</blockquote>\n<blockquote>\n<p>... it requires the user of the Post class to know that a null value can be safely passed into its Slug property -- something I wish to avoid"</p>\n</blockquote>\n<p>That's a contradiction.</p>\n<p>The reason I'm bringing this up is because this question revolves around communication between developer and consumer, not technical implementation (directly). But if you want your developer and consumer to be on the same page, you need to first know what that page is supposed to be, and that contradiction isn't helping you.</p>\n<hr />\n<h2>The typical property</h2>\n<p>Generally, you expect a gettable and settable property to retain the state you set.</p>\n<pre><code>var myClass = new MyClass();\nmyClass.MyProperty = "hello";\n\nAssert.AreEqual(myClass.MyProperty, "hello"); // Should pass!\n</code></pre>\n<p>That is the default expectation on how a property behaves. Is that behavior set in stone? No. Clearly, the language/compiler allows you to implement your properties completely differently.</p>\n<p>But doing so means you go against the consumer's natural intuition on how a property behaves.</p>\n<p>The conclusion I'm trying to get to here is that <strong>you need a valid reason to deviate from the default property behavior</strong>, if you want to justify the cognitive cost to your consumer, who now has to know about this atypical behavior in your implementation.</p>\n<p>Sometimes, this can already be contextually understood, e.g. if your setter cleans up an understandable-but-abnormal value (e.g. a file path with consecutive separators). Sometimes, this requires documentation to explain to the consumer.</p>\n<p>I have no idea what a <code>Slug</code> is, so I can't judge this part. Based on the root your question, it would seem that this needs to be explicitly communicated to the consumer.</p>\n<hr />\n<h2>The <code>null</code> crutch</h2>\n<p>Historically, <code>null</code> is a controversial topic. Some developers hate it, some use it religiously. I'm not making any definitive statements here. Let's avoid a holy war and try to find middle ground: <code>null</code> can have its purposes, but <code>null</code> can also be abused.</p>\n<p>One clear abuse of <code>null</code> is when developers use it as an additional value which they don't bother to further define. The clearest example here is turning a <code>bool</code> into a <code>bool?</code> when a third state needs to be added. It should've been an enum with 3 members, but <code>null</code> is being introduced as the third value instead, as a shortcut.</p>\n<p>What you're doing here is similar. Your <code>Slug</code> doesn't have "the chosen value or <code>null</code>", your <code>Slug</code> has "the chosen value <strong>or a default value</strong>". You've just <em>chosen</em> to represent that <em>choice</em> of setting the default value using <code>null</code> (and then subsequently translate a <code>null</code> into the actual default value you want), which in my book counts as the same <code>null</code> abuse I just described.</p>\n<hr />\n<h2>Solution: the named default</h2>\n<p>We've addressed several issues:</p>\n<ul>\n<li>The way you're suggesting to use your property is atypical and would require the consumer to learn the specifics of your implementation</li>\n<li>The way you're suggesting <code>null</code> should be used to set a (non-null) default value is atypical and would require the consumer to learn the specifics of your implementation.</li>\n</ul>\n<p>This can't live in the same world as:</p>\n<ul>\n<li>You want the code to be self-documenting towards the consumer.</li>\n</ul>\n<p><strong>If you stray from the beaten path, then people won't find their way on their own.</strong></p>\n<p>To solve the above issues, we should make the "default" value an explicit part of the contract of your <code>Post</code> class. This way, your consumer can figure out that there is a default value, and how to set it, without needing to read additional documentation.</p>\n<p>The simplest solution here is to stick with a non-null property, and add a secondary route to set that property value.</p>\n<pre><code>public class Post\n{\n public string Title { get; }\n public string Slug { get; set; }\n\n public Post(string title)\n {\n Title = title;\n SetDefaultSlug();\n }\n\n public void SetDefaultSlug()\n {\n Slug = title.Slugify();\n }\n}\n</code></pre>\n<p>The main difference between this answer and the already given answer by dumetrulo is that <strong>this version can revert back to the default</strong>, whereas the other answer's default, once removed, cannot be retrieved (since your consumer doesn't know how you calculate the default value.</p>\n<hr />\n<p>Additionally, you can argue that you should still use the default value when the custom value doesn't pass a certain validation (e.g. no empty strings).<br />\nI can see arguments pro and con, depending on whether you consider this a valid responsibility of your class. That's a contextual consideration which I cannot conclusively judge. Should you judge it to be relevant, you can change your <code>Slug</code> property to:</p>\n<pre><code>private string _slug;\npublic string Slug\n{\n get\n {\n return ValidateSlug()\n ? _slug\n : title.Slugify();\n }\n set { _slug = value; }\n\n}\n\nprivate bool ValidateSlug()\n{\n return !String.IsNullOrWhitespace(_slug);\n}\n</code></pre>\n<p><em>A null or empty check is just a basic example. This could be based on length, profanity filter, ... Your business validation is your own decision.</em></p>\n<p>However, do keep in mind that we're getting into atypical property behavior again. If your <code>Post</code>'s responsibility includes sanitizing the slug (which would be the basis for adding the above code), then that's a valid justification for changing the property's default behavior.</p>\n<p>But that depends on the notion that the consumer inherently understands that the <code>Post</code> class will sanitize the slug as it sees fit.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T10:54:15.663",
"Id": "484236",
"Score": "0",
"body": "Thank you for your well thought out answer. A slug is a url segment. There's no contraction: the first statement is what I want, the second statement is what I have (but dont want). I agree with the typical property section -- that is what made me feel like I was asking for the wrong thing in the first place. The other answer suggested to make the class immutable, i.e. don't change but replace."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T11:01:49.420",
"Id": "484237",
"Score": "0",
"body": "@gldraphael: I'm aware I may be misreading, but the second statement explicitly expresses \"what you want to avoid\", i.e. you want to avoid the user being required to know of the null feature; which is the opposite of the first statement. Either I'm misreading or you misspoke?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T11:03:15.473",
"Id": "484238",
"Score": "2",
"body": "@gldraphael: Immutability does make things easier as your object's state isn't in flux. But not every class can be made immutable without consequences - and I cannot judge that context. If immutability works for you, it is definitely worth considering as it simplifies your problem scenario."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T11:29:44.113",
"Id": "484240",
"Score": "0",
"body": "aah now i see what you mean about the contradiction, my bad ♂️. I'll leave it unedited."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T10:27:23.320",
"Id": "247430",
"ParentId": "247416",
"Score": "4"
}
},
{
"body": "<p><code>[AllowNull]</code> does seem to be exactly what you need. If slug was declared as:</p>\n<pre><code> private string? slug;\n [AllowNull]\n public string Slug \n { \n get\n {\n if(slug is null)\n {\n slug = Title.Slugify();\n }\n return slug;\n }\n set => slug = value;\n }\n</code></pre>\n<p>One of the answers suggest that allowing a property to have a non-nullable getter, but nullable setter is "atypical" and straying off the beaten path. But it's not quite true. Let's look at the UX, when using the <code>[AllowNull]</code>:</p>\n<pre><code>// Creating a Post without setting a slug\nPost post1 = new Post(title: "Foo bar");\nstring slug1 = post1.Slug; // slug = "foo-bar"\n\n// Creating a Post by setting an explicit slug\nPost post2 = new Post(title: "Foo bar 2) { Slug = "hello-world" };\nstring slug2 = post2.Slug; // slug = "hello-world"\n\n// Creating a Post by setting an explicit nullable slug\nstring? slug = vm.Slug; // maybe null\nPost post3 = new Post(title: "Foo bar 3") { Slug = slug }; // note that we dont need the ! operator\nstring slug3 = post3.Slug; // slug3 = slug\n</code></pre>\n<p>No compiler warnings, no null forgiving operators. The user can set the property if they want to, or set it to a nullable value. But when they get the value, since the value will not be null (implementation detail), so the compiler won't ask to check for null (what the API user sees).</p>\n<p>From the <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/nullable-migration-strategies\" rel=\"nofollow noreferrer\">documentation</a>:</p>\n<blockquote>\n<p>you can apply a number of attributes: <code>AllowNull</code>, <code>DisallowNull</code>, <code>MaybeNull</code>, <code>NotNull</code>, <code>NotNullWhen</code>, <code>MaybeNullWhen</code>, and <code>NotNullIfNotNull</code> to completely describe the null states of argument and return values. That provides a great experience as you write code. You get warnings if a non-nullable variable might be set to null. You get warnings if a nullable variable isn't null-checked before you dereference it.</p>\n</blockquote>\n<p>The other answers are spot-on about using a fully immutable type, and IMO is the best approach. Perhaps (if Post is an Entity) this could also be an opportunity to extract properties into a ValueObject.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-08T09:46:56.840",
"Id": "247652",
"ParentId": "247416",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "247427",
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T04:41:16.493",
"Id": "247416",
"Score": "4",
"Tags": [
"c#",
"ddd"
],
"Title": "Representing a property with a non-nullable getter & a nullable setter"
}
|
247416
|
<p>I'm trying to write a script that would (a) fetch StackOverflow questions and (b) update a markdown table with new entries.
With github actions I automated this script to run daily.</p>
<p>Idea borrowed from <a href="https://github.com/simonw/simonw" rel="nofollow noreferrer">simonw</a></p>
<p>Code:</p>
<pre><code>import re
import requests
from pathlib import Path
from datetime import datetime
URL = "https://api.stackexchange.com/2.2/questions"
DATE = datetime.utcnow().date()
ROOT = Path(__file__).parent.resolve()
def get_epochs(date):
""" Get epoch dates for the start and end of the (current) day. """
start = datetime(
year=date.year, month=date.month, day=date.day,
hour=0, minute=0, second=0
)
end = datetime(
year=date.year, month=date.month, day=date.day,
hour=23, minute=59, second=59
)
return int(start.timestamp()), int(end.timestamp())
def fetch_questions(start, end, tag, site="stackoverflow"):
""" Fetch questions from stackoverflowAPI. """
_params = {
"fromdate": start,
"todate": end,
"order": "desc",
"sort": "votes",
"tagged": tag,
"site": site,
}
return requests.get(URL, params=_params).json()
def build_table(*args, **kwargs):
""" Build a markdown table from a list of entries. """
columns = [
"\n".join(
"* [{title}]({url}) - {score} votes".format(
# to prevent code from breaking if special characters are present
title=re.sub(r'[^\w\s]', '', item["title"]),
url=item["link"],
score=item["score"]
)
for item in chunk["items"][:8]
)
for chunk in args
]
return columns
def replace_chunk(content, marker, chunk, inline=False):
""" Replace chunks of README.md """
r = re.compile(
r"<!\-\- {} starts \-\->.*<!\-\- {} ends \-\->".format(marker, marker),
re.DOTALL,
)
if not inline:
chunk = "\n{}\n".format(chunk)
chunk = "<!-- {} starts -->{}<!-- {} ends -->".format(marker, chunk, marker)
return r.sub(chunk, content)
if __name__ == "__main__":
readme = ROOT / "README.md"
start, end = get_epochs(DATE)
pandas, beautifulsoup, code_review = build_table(
fetch_questions(start, end, tag="pandas"),
fetch_questions(start, end, tag="beautifulsoup"),
fetch_questions(start, end, tag="python", site="codereview")
)
readme_contents = readme.open().read()
rewritten = replace_chunk(readme_contents, "date", DATE.strftime("%Y-%m-%d"), inline=True)
rewritten = replace_chunk(rewritten, "pandas", pandas)
rewritten = replace_chunk(rewritten, "bs", beautifulsoup)
rewritten = replace_chunk(rewritten, "code_review", code_review)
with open(readme, "w") as output:
output.write(rewritten)
</code></pre>
<p>Markdown file:</p>
<pre><code># Stackoverflow daily top questions: <!-- date starts --> date <!-- date ends -->
<table><tr><td valign="top" width="33%">
### Pandas
<!-- pandas starts -->
pandas content
<!-- pandas ends -->
</td><td valign="top" width="34%">
### BeautifulSoup
<!-- bs starts -->
bs4 content
<!-- bs ends -->
</td><td valign="top" width="34%">
### Python code review submissions
<!-- code_review starts -->
code review content
<!-- code_review ends -->
</td><td valign="top" width="34%">
</code></pre>
<hr />
<p>Sample output:</p>
<p><a href="https://i.stack.imgur.com/QJjVr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QJjVr.png" alt="enter image description here" /></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T08:22:38.543",
"Id": "484214",
"Score": "0",
"body": "oh, and how it all works with a github workflows is [here](https://github.com/hp0404/hp0404)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T08:22:49.510",
"Id": "484464",
"Score": "1",
"body": "If this is python 3+, you can tag as [tag:python-3.x]"
}
] |
[
{
"body": "<p>Things look good and well organised at first glance. However, there are a few things you can make use of.</p>\n<ol>\n<li>Use f-string over using str.format. The former <a href=\"https://stackoverflow.com/a/43123579/1190388\">is more performant</a>.</li>\n<li>You can group the columns and iterate over them, instead of having multiple lines for each section. This way, you can add/remove to this iterable without having to change much of the code itself.</li>\n<li>When using raw strings, you do not need to escape the <code>-</code> character, unless they are being used inside a character set (for regex).</li>\n<li>The <code>build_table</code> can be split to another separate function.</li>\n<li>Use <a href=\"https://devdocs.io/python%7E3.8/library/typing\" rel=\"nofollow noreferrer\">type hinting</a>.</li>\n<li>If you're not using <code>kwargs</code>, no need to declare them.</li>\n</ol>\n<hr />\n<p>Rewritten snippets (you might need to fit them in your code accordingly):</p>\n<pre><code>sections = (\n {'tag': "pandas", "marker": "pandas"},\n {'tag': "beautifulsoup", "marker": "bs"},\n {'tag': "python", "site": "codereview", "marker": "code_review"},\n)\nfor section in sections:\n questions_list = fetch_questions(start, end, **section)\n # Using `**section` might throw an error for the unknown kwarg: `marker`.\n # But it is trivial to handle that.\n .\n ...\n</code></pre>\n<hr />\n<pre><code>def replace_chunk(content: str, marker: str, chunk: str, inline: bool = False):\n """ Replace chunks of README.md """\n r = re.compile(\n rf"<!-- {marker} starts -->.*<!-- {marker} ends -->",\n re.DOTALL,\n )\n if not inline:\n chunk = "\\n{}\\n".format(chunk)\n chunk = f"<!-- {marker} starts -->{chunk}<!-- {marker} ends -->"\n return r.sub(chunk, content)\n</code></pre>\n<hr />\n<pre><code>def get_item_string(item):\n # to prevent code from breaking if special characters are present\n title = re.sub(r'[^\\w\\s]', '', item["title"])\n return f"* [{title}]({item['link']}) - {item['score']} votes"\n\ndef build_table(*args):\n """ Build a markdown table from a list of entries. """\n columns = [\n "\\n".join(\n map(get_item_string, chunk["items"][:8])\n )\n for chunk in args\n ]\n return columns\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T13:08:18.083",
"Id": "484509",
"Score": "0",
"body": "This is great, thank you very much!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T10:34:06.810",
"Id": "247518",
"ParentId": "247417",
"Score": "2"
}
},
{
"body": "<p>The code looks really good, so I'll ask some questions on the design decisions that have been made.</p>\n<pre><code>Path(__file__).parent.resolve()\n</code></pre>\n<p>I haven't used this before, so I may be wrong, but this looks a little fragile.</p>\n<p>The Python docs for <a href=\"https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.parent\" rel=\"nofollow noreferrer\">pathlib</a> include a very useful note under parent</p>\n<p><a href=\"https://i.stack.imgur.com/NHPh9.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/NHPh9.png\" alt=\"enter image description here\" /></a></p>\n<p>Namely, it may do something unexpected if the path is not an absolute path. From this <a href=\"https://stackoverflow.com/a/7116925/3503611\">stack overflow answer</a>, the result returned from <code>__file__</code> may be relative, if the directory is in sys.path. In conclusion, you probably want to resolve before getting the parent, to avoid some unexpected paths.</p>\n<pre><code>ROOT = Path(__file__).resolve().parent\n</code></pre>\n<p>Also, why set the root based on the file location, rather than <code>__main__</code> or a fixed location? Another consideration is <code>__file__</code> is not always set, do you care about the use-case of running the code in an interpreter?</p>\n<hr />\n<pre><code>def get_epochs(date):\n """ Get epoch dates for the start and end of the (current) day. """\n ...\n</code></pre>\n<p>This code all looks good. I would maybe include a note specifying that the API is inclusive of the end time, and is quantised in seconds. A change to either of these assumptions (which is unlikely) would warrant changing the code here.</p>\n<hr />\n<pre><code>def fetch_questions(start, end, tag, site="stackoverflow"):\n """ Fetch questions from stackoverflowAPI. """\n\n _params = {\n ...\n }\n requests.get(URL, params=_params).json()\n</code></pre>\n<p>Some very minor points</p>\n<ul>\n<li>The API is for stack exchange, not stack overflow.</li>\n<li>You don't need the underscore in front of params. It is a local name to the function, so it doesn't need to be marked private. Keyword args can share their name with the parameter name. <code>params=params</code> works.</li>\n<li>I would split up the request, and extracting result as a certain file format. If this function starts returning bad results, it will be easier to debug if the fetch and parsing of results are separated.</li>\n<li>I would change the parameter <code>tag</code> to <code>tags</code> since you can pass more than one tag by delimiting with ';'. A note on how to use tag would be a good addition to the docstring.</li>\n</ul>\n<hr />\n<pre><code>if __name__ == "__main__":\n \n readme = ROOT / "README.md"\n start, end = get_epochs(DATE)\n\n pandas, beautifulsoup, code_review = build_table(\n fetch_questions(start, end, tag="pandas"),\n fetch_questions(start, end, tag="beautifulsoup"),\n fetch_questions(start, end, tag="python", site="codereview")\n )\n \n readme_contents = readme.open().read()\n rewritten = replace_chunk(readme_contents, "date", DATE.strftime("%Y-%m-%d"), inline=True)\n rewritten = replace_chunk(rewritten, "pandas", pandas)\n rewritten = replace_chunk(rewritten, "bs", beautifulsoup)\n rewritten = replace_chunk(rewritten, "code_review", code_review)\n \n with open(readme, "w") as output:\n output.write(rewritten)\n</code></pre>\n<p>I would move this code to a function, since it will be a little easier to test (and therefore update if needed). What happens if you make a typo in a tag between <code>fetch_questions</code> and <code>replace_chunk</code>?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T06:31:22.057",
"Id": "484589",
"Score": "0",
"body": "Thank you for such a detailed answer! Those are very relevant questions. I'll reconsider everything once I have more free time."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T14:23:34.443",
"Id": "247524",
"ParentId": "247417",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "247518",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T07:08:17.270",
"Id": "247417",
"Score": "7",
"Tags": [
"python",
"python-3.x",
"api",
"markdown"
],
"Title": "Fetch StackOverflow questions and save them to a markdown table"
}
|
247417
|
<p>Folding, done by <code>fold</code>-functions. A folding function can <code>fold-right</code> or <code>fold-left</code>.</p>
<p>Also see the <a href="http://community.schemewiki.org/?fold" rel="nofollow noreferrer">SchemeWiki entry on folding</a>.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T07:08:28.230",
"Id": "247418",
"Score": "0",
"Tags": null,
"Title": null
}
|
247418
|
Reducing a sequence of terms to a single term.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T07:08:28.230",
"Id": "247419",
"Score": "0",
"Tags": null,
"Title": null
}
|
247419
|
<p>DAX is a formula language for calculations in Power PivotTables in Power BI Desktop. Similar to Excel formulas, focussed on data analysis.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T07:28:56.493",
"Id": "247420",
"Score": "0",
"Tags": null,
"Title": null
}
|
247420
|
A formula language for calculations in Power PivotTables in Power BI Desktop.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T07:28:56.493",
"Id": "247421",
"Score": "0",
"Tags": null,
"Title": null
}
|
247421
|
<p>I'm implementing a kind of 'heartbeat pattern' with websocket in JS.</p>
<p>The idea is: the server keeps a dictionary holding a <a href="https://www.npmjs.com/package/ws" rel="nofollow noreferrer">Websocket</a> object for each uuid (an uuid is a client).</p>
<pre><code>const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
const DELAY_TO_DECLARE_DEATH_CLIENT = 15000
let websocketsDictionary = {}
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(data) {
data = JSON.parse(data)
if(data.type == "REGISTER"){
console.log("Client has registered to path " + data.path)
}
else if(data.type == "PUT"){
console.log("Client says hello to " + data.path)
}
else if(data.type == "HEARTBEAT"){
if(!websocketsDictionary[data.uuid]){
console.log("Remembering " + data.uuid)
websocketsDictionary[data.uuid] = {
ws: ws,
lastSeen: new Date().getTime()
}
}
else{
console.log("Already know " + data.uuid)
websocketsDictionary[data.uuid].lastSeen = new Date().getTime()
}
}
})
})
</code></pre>
<p>On the side, I'd like to purge each client that hasn't sent a heartbeat in a certain threshold.</p>
<pre><code>function purgeDeadClients(){
let now = new Date().getTime
websocketsDictionary = websocketsDictionary.filter(c => c.lastSeen - now < DELAY_TO_DECLARE_DEATH_CLIENT)
}
</code></pre>
<p>What I don't like is that <code>webosocketDictionary</code> is global, and both the callbacks from <code>ws.on</code> and <code>purgeDeadClients</code> are reading/writing in it.</p>
<p>Is there some pattern I could use so that the content of <code>websocketDictionary</code> is shared by both callbacks, without being simply declared as global ?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T09:06:12.957",
"Id": "484475",
"Score": "0",
"body": "Hey, when handling in memory stuff like this. I usually just run a redis which works like a charm. Plus you can set a TTL which solves your purge issue."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T08:10:24.513",
"Id": "247424",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Heartbeat pattern with Websocket in JS - annoyed by global dictionary"
}
|
247424
|
<p>I have a class that opens a text file and reads out its content.
This class has a member function that will extract a substring between two given delimiters.
My application needs to extract between 6000 and 7000 substrings of this text file content on start up. Even though speed is not the most important concern, the whole process should still not take more than 1s.
My problem is, that the way I wrote the class, the process takes more than 10 seconds!
What I am doing is, I am using the string.find() method to find the first delimiter, than I am looking for the second delimiter in the same way. In the last step, I just use the string.substr() method to cut out the piece I want.</p>
<p>There must be much quicker ways to do this right? I found <a href="https://codereview.stackexchange.com/questions/88509/getting-a-substring-of-a-delimited-string">this answer</a> that uses a split approach. I do not think I can use this kind of approach, as my start-delimiter varies from entry to entry.
My data looks like this (this might look like JSON, but it is not guaranteed that the data will be in a clean JSON format. All that I know is that I have the relevant substring between "xN" and ","):</p>
<pre><code>"x1" : "SUBSTRING_1",
...
"x6500" : "SUBSTRING_6500",
</code></pre>
<p>This is the complete code of the class:</p>
<pre><code>class fileAccess{
public:
fileAccess(const char *path);
fileAccess(const std::string path);
bool overwrite(const std::string content); //will delete old file
bool overwriteBinary(std::vector<uint16_t> &a); //will delete old file
std::string read();
std::vector<uint16_t> readBinary();
std::string getSubStringWithinFile(std::string fromHere, std::string toHere);
private:
std::string m_filepath;
};
////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
//////// ------------------- IMPLEMENTATION -------------------- ////////
////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
fileAccess::fileAccess(const char *path)
{
m_filepath = path;
}
fileAccess::fileAccess(const std::string path)
{
m_filepath = path;
}
bool fileAccess::overwrite(const std::string content)
{
std::ofstream file;
file.open(m_filepath, std::ios::out);
file << content;
file.close();
return true;
}
bool fileAccess::overwriteBinary(std::vector<uint16_t> &a)
{
std::ofstream f(m_filepath, std::ios::binary);
if (!f.is_open()) {
std::cout << "[CmpCameraSetup] File could not be opened!\n";
return false;
}
uint16_t *ptr = a.data();
char *b = (char*) ptr;
size_t size = a.size() * sizeof(uint16_t);
f.write(b, size);
f.close();
if (f.bad()){
std::cout << "[CmpCameraSetup] Error when writing!" << std::endl;
return false;
}
return true;
}
std::string fileAccess::read()
{
//see https://stackoverflow.com/questions/2602013/read-whole-ascii-file-into-c-stdstring
std::ifstream t(m_filepath);
std::string str;
t.seekg(0, std::ios::end);
str.reserve(t.tellg());
t.seekg(0, std::ios::beg);
str.assign((std::istreambuf_iterator<char>(t)),
std::istreambuf_iterator<char>());
return str;
}
std::vector<uint16_t> fileAccess::readBinary()
{
std::ifstream file(m_filepath, std::ios::binary);
std::vector<unsigned char> buffer(std::istreambuf_iterator<char>(file), {});
uint16_t *ptr = (uint16_t*) buffer.data();
std::vector<uint16_t> ret;
for (unsigned long int i = 0; i < buffer.size()/2; i++){
ret.push_back(ptr[i]);
}
file.close();
return ret;
}
std::string fileAccess::getSubStringWithinFile(std::string fromHere, std::string toHere)
{
std::string err = "ERROR! STRING NOT FOUND!! CHECK FILE";
std::string content = this->read();
size_t foundStart = content.find(fromHere);
if(foundStart == std::string::npos)
return err;
size_t foundEnd = content.find(toHere, foundStart);
if(foundEnd == std::string::npos)
return err;
return content.substr(foundStart + fromHere.length(), foundEnd - (foundStart + fromHere.length()));
}
</code></pre>
<p>On startup I am calling the <code>getSubStringWithinFile()</code> method from within a for loop that goes from 1 to 6500 and passes the correct starting delimiter <code>"x1"</code>, <code>"x2"</code>...</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T12:11:44.757",
"Id": "484246",
"Score": "3",
"body": "Welcome to Code Review. We really need to see the entire `myClass` class to be able to help with performance issues. Seeing the entire class gives us the context of what the function is doing. Code review is different from stackoverflow, we don't want the briefest question. Please see our [guidelines on how to ask a good question](https://codereview.stackexchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T12:32:58.863",
"Id": "484250",
"Score": "2",
"body": "Is this performance issue occurring when the code is compiled -O3?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T12:49:09.947",
"Id": "484252",
"Score": "2",
"body": "It seems like the file is read from disk every time `getSubStringWithinFile` is called. You could try reading it once and passing a reference to it instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T13:48:21.550",
"Id": "484259",
"Score": "0",
"body": "@pacmaninbw thank you for the comment. Sorry for not reading the guidelines first, you were right in assuming that I wrote the question in the stackoverflow way :-). I did not try compiling it with the optimization flags yet. I will try and then report back, but would it really cut down the process time by so much that it would matter? What do you think?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T13:50:56.757",
"Id": "484260",
"Score": "0",
"body": "@Johnbot you are right, this is reading it every time from disk which I really should not do. I will try to save the content of the file in a member string-variable and perform the substring routine on that variable instead. Thanks for the hint"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T14:09:27.483",
"Id": "484262",
"Score": "1",
"body": "Compiling -O3 can make a lot of difference. I'll look through the code now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T14:38:40.853",
"Id": "484268",
"Score": "2",
"body": "I think @Johnbot found you performance issue, but I can't be sure without seeing how this class is used. If I write a review there will be very little about performance for this reason, I can only review what is posted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T15:00:18.380",
"Id": "484271",
"Score": "0",
"body": "@Johnbot Reading from disk every time was the issue. Now that I am buffering the file content between calls the performance is fine. Thank you very much!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T15:02:05.310",
"Id": "484272",
"Score": "0",
"body": "@pacmaninbw Thank you for your comments! Running the optimized code still was very slow, but buffering the content helped. After I have reworked the class I will post also how I use the class, every comment on my code will be highly appreciated! As you see, I am still learning :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T15:45:27.203",
"Id": "484276",
"Score": "2",
"body": "You need to test the read and write binary functions before posting for review, the current Old C style casts can mutilate the data. Make sure the code is fully working before you post. You might want to delete this question now because I am unwilling to change my vote to close at this time. You might also want to rename the `read()` function since the reason the `this` pointer is necessary is because you are using the name of a standard C library function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T06:37:45.683",
"Id": "484349",
"Score": "0",
"body": "Hi. I have been using this read function for a while now, it has been working. It always reads out the data I expect it to - but maybe I do simply not know how to test it thoroughly enough."
}
] |
[
{
"body": "<pre><code>fileAccess::fileAccess(const char *path)\n{\n m_filepath = path;\n}\n\nfileAccess::fileAccess(const std::string path)\n{\n m_filepath = path;\n}\n</code></pre>\n<p>I prefer an initializer list constructor for such cases. No need to write it in a separate location.</p>\n<ul>\n<li><a href=\"https://docs.microsoft.com/en-us/cpp/cpp/constructors-cpp?view=vs-2019#init_list_constructors\" rel=\"nofollow noreferrer\">https://docs.microsoft.com/en-us/cpp/cpp/constructors-cpp?view=vs-2019#init_list_constructors</a></li>\n</ul>\n<hr>\n<p>You may use <code>std::string_view</code> instead of <code>const std::string</code> to indicate that we're only reading it. Also, that avoids the need for <code>const char *path</code> overloading since <code>string_view</code> accepts that too in its constructor.</p>\n<p>The performance benefit of <code>std::string_view</code> is negligible in the path since that is used just once in the program. Use it later in the code in place of string allocations. As long as <em>something</em> owns the string(that includes compile time constants), you don't need to create a new <code>std::string</code> or a <code>const std::string &</code>.</p>\n<ul>\n<li><a href=\"https://en.cppreference.com/w/cpp/string/basic_string_view/basic_string_view\" rel=\"nofollow noreferrer\">https://en.cppreference.com/w/cpp/string/basic_string_view/basic_string_view</a></li>\n</ul>\n<hr>\n<pre><code>//will delete old file\n</code></pre>\n<p>Make such comments near the implementation for easy discovery. IDEs can also pick up documentation formatted comments like:</p>\n<pre><code>/**\n * Deletes the old file.\n */\n</code></pre>\n<hr>\n<pre><code>str.assign((std::istreambuf_iterator<char>(t)),\n std::istreambuf_iterator<char>());\n</code></pre>\n<p>The answer that you've taken this code from got a downvote from me due to the sheer performance penalty it incurs. Please see the answer by Jerry Coffin</p>\n<pre><code>std::ifstream t("file.txt");\nstd::stringstream buffer;\nbuffer << t.rdbuf();\n</code></pre>\n<hr>\n<p>If the file is huge, this approach is costly in terms of memory usage as well as time taken in memory allocations.</p>\n<p>Read the file line by line or use asynchronous threads for reading and processing.</p>\n<hr>\n<p>I won't duplicate what I've already written here:</p>\n<ul>\n<li><a href=\"https://codereview.stackexchange.com/questions/246219/parser-written-in-php-is-5-6x-faster-than-the-same-c-program-in-a-similar-test/246232#246232\">Parser written in PHP is 5.6x faster than the same C++ program in a similar test (g++ 4.8.5)</a></li>\n</ul>\n<p>I suggest you to give those answers a read.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T06:39:05.407",
"Id": "484350",
"Score": "1",
"body": "Thank you very much for your effort! `std::string_view` was completely new to me, thank you for teaching me about it!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T16:59:09.603",
"Id": "247446",
"ParentId": "247426",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T09:38:03.237",
"Id": "247426",
"Score": "1",
"Tags": [
"c++",
"performance",
"strings",
"linux"
],
"Title": "Getting 6000+ substrings from large a large string"
}
|
247426
|
<p>I have implemented a zigzag array which will sort smaller greater smaller and goes on...</p>
<p>For example :</p>
<p>3 7 4 8 2 6 1 is a valid ordering.</p>
<p>The relationship between numbers is</p>
<p>3 < 7 > 4 < 8 > 2 < 6 > 1</p>
<pre><code>3 smaller than 7
7 greater than 4
4 smaller than 8
8 greater than and so on
</code></pre>
<p>the ordering always has to be "smaller than" then "greater than" then "smaller than"...</p>
<p>Are there any other suggestions for improving the solution?</p>
<p>Thanks.</p>
<pre><code>package main.algorithms;
public class ZigZag {
public static void main(String[] args) {
int[] array = {4,3,7,8,6,2,1};
zigZag(array);
for (int i: array){
System.out.println(i);
}
}
// Time O(n)
// Space O(1)
private static int[] zigZag(int[] array) {
int status = 0;
int counter = 0;
while(counter < array.length-1){
if(status ==0) {
if (array[counter] > array[counter + 1]) {
int temp = array[counter + 1];
array[counter + 1] = array[counter];
array[counter] = temp;
}
status = 1;
} else {
if (array[counter] < array[counter + 1]) {
int temp = array[counter + 1];
array[counter + 1] = array[counter];
array[counter] = temp;
}
status = 0;
}
counter++;
}
return array;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T12:02:12.840",
"Id": "484245",
"Score": "0",
"body": "@superb rain I just added extra explanation."
}
] |
[
{
"body": "<ul>\n<li>Instead of that <code>while</code>-loop, I'd use a <code>for</code>-loop and use the common loop/index variable <code>i</code>.</li>\n<li>Instead of a separate <code>status</code> variable, I'd simply use <code>i % 2</code>.</li>\n<li>I'd deduplicate the two cases.</li>\n<li>Putting the current two array elements into variables avoids duplicating the longer <code>array[i]</code> and <code>array[i + 1]</code> and simplifies the swap.</li>\n<li>As Joop Eggen points out, it's probably better to not modify the array in-place <em>and</em> return it. (Unless you have a good reason to, which it seems you don't, as your own calling code ignores the returned value.)</li>\n</ul>\n<p>Code:</p>\n<pre><code> private static void zigZag(int[] array) {\n for (int i = 0; i < array.length - 1; i++) {\n int a = array[i], b = array[i + 1];\n if (i % 2 == 0 ? a > b : a < b) {\n array[i] = b;\n array[i + 1] = a;\n }\n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T13:52:30.637",
"Id": "484261",
"Score": "2",
"body": "Very nice. It would be perfect when advising to use a void result, as the passed array is modified in-situ. Also a proof with pre and post conditions would be feasible, but that would ruin the compactness of your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T15:56:14.990",
"Id": "484278",
"Score": "0",
"body": "@JoopEggen Right, added that (rephrased a bit)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T10:12:22.187",
"Id": "247429",
"ParentId": "247428",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T10:02:29.997",
"Id": "247428",
"Score": "5",
"Tags": [
"java",
"array",
"sorting"
],
"Title": "ZigZag array implementation"
}
|
247428
|
<p>I have a List that I want to compare to an <code>Enum</code>.</p>
<p>If <code>a.Value</code> is found in the <code>Enum</code> we return <code>true</code>.</p>
<p>I feel that I should be able to make this a single line, but have struggled.</p>
<pre class="lang-cs prettyprint-override"><code>private bool IsFound(IEnumerable<SomeAttribute> attributes)
{
foreach (AttributesInMethod option in Enum.GetValues(typeof(AttributesInMethod)))
{
if (attributes.Any(a => option.GetDisplayNameENUM().Contains(a.Value)))
{
return true;
}
}
return false;
}
</code></pre>
|
[] |
[
{
"body": "<p>I would suggest a two lines of code solution instead of one. :)</p>\n<p>Let me show you first the solution then the explanation.</p>\n<h2>Solution</h2>\n<pre class=\"lang-cs prettyprint-override\"><code>private static readonly Lazy<IEnumerable<string>> enumValues = new Lazy<IEnumerable<string>>(() => Enum.GetValues(typeof(AttributesInMethod)).Cast<AttributesInMethod>().Select(option => option.GetDisplayNameENUM()));\n\nprivate bool IsFound(IEnumerable<SomeAttribute> attributes) => attributes.Select(att => att.Value).Any(enumValues.Value.Contains);\n</code></pre>\n<h2>Explanation</h2>\n<h3>Two methods instead of one</h3>\n<ul>\n<li>You have two kinds of data\n<ul>\n<li>A fairly static data, which could be changed only with code change\n<ul>\n<li>The mapped values of the enumeration</li>\n</ul>\n</li>\n<li>An absolutely dynamic data, which could change by each and every method call\n<ul>\n<li>The <code>IsFound</code> input parameter</li>\n</ul>\n</li>\n</ul>\n</li>\n</ul>\n<p>You don't need to calculate each and every time the derived data from the enumeration. It should be calculated once and stored for long term.</p>\n<h3>Usage of Lazy</h3>\n<p><em>"It should be calculated once and stored for long term."</em> > That's where the <code>Lazy<T></code> type comes into play.</p>\n<p>All you have to do is to provide a factory method (how to compute the derived data) and then the calculated information should be stored in a long-living variable. <code>Lazy<T></code> gives us thread-safety so there is a guarantee that it will be calculated only once.</p>\n<h3>How to derive the data</h3>\n<pre class=\"lang-cs prettyprint-override\"><code>Enum.GetValues(typeof(AttributesInMethod))\n .Cast<AttributesInMethod>()\n .Select(option => option.GetDisplayNameENUM())\n</code></pre>\n<p><code>GetValues</code> returns an <code>Array</code> so you have to call <code>Cast<T></code> to be able to use Linq operator on it.</p>\n<h3>Composing functions</h3>\n<p>For each input data check the existence of it in a predefined collection.</p>\n<ul>\n<li>For each input data: <code>attributes.Select(att => att.Value)</code></li>\n<li>check the existence of it: <code>.Any(... .Contains)</code></li>\n<li>in a predefined collection: <code>enumValues.Value</code></li>\n</ul>\n<p>All you have to do to compose them to create a new higher level function.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T12:39:52.343",
"Id": "247436",
"ParentId": "247431",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "247436",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T10:31:55.227",
"Id": "247431",
"Score": "5",
"Tags": [
"c#",
"linq",
"enum"
],
"Title": "Compare List to Enum Where Contains Any"
}
|
247431
|
<p>I have an Excel file containing a free-form text column (that sometimes is structured like an email), where I need to <strong>find all first and last names and add an extra columns saying TRUE/FALSE</strong> to these fields. I do not need to extract matched data (i.e. note it down in an adjacent column), although that could be an advantage.</p>
<p><strong>NB</strong>: I do not know the names that I need to find, so it is pure guesswork. I have a list of registered first names with 40k+ entries, as well as a list of most common last names with another 16k+ entries.</p>
<p>So far, I managed to filter out roughly 10000 rows out out ~20000 row file, although my solution contains a lot of false positives. <em>e.g.</em> some rows marked TRUE for first names, contain text like "<strong>Det er OK.</strong>", where Python (I assume) merges the entire text together and extracts any matching substing to a name from a list, in this case I guess that could be "<strong>t er O</strong>" or "<strong>r OK</strong>", since my list has names "<strong>Tero</strong>" and "<strong>Rok</strong>" (although the case does not match and it combines letters from 2/3 separate words, which is not what I want)... Weirdly enough, this is <strong>NOT TRUE</strong> for the same text written in lowercase and without "<strong>.</strong>" at the end, i.e. "<strong>det er ok</strong>", which is marked as FALSE! P.S. there are unfortunatelly few names in the emails that are written in lowercase letters and not sentence case as it should be...</p>
<p><strong>Sample email</strong> (with names Thomas, Lars, Ole, Per):</p>
<blockquote>
<p>Hej <em>Thomas</em>,</p>
<p>De 24 timer var en af mange sager som vi havde med til møde med <em>Lars</em> og <em>Ole</em>. De har godkendt den under dette møde.</p>
<p>Mvh. <em>Per</em></p>
</blockquote>
<p><strong>My code:</strong></p>
<pre class="lang-py prettyprint-override"><code># Import datasets and create lists/variables
import pandas as pd
from pandas import ExcelWriter
namesdf = pd.read_excel('names.xlsx', sheet_name='Alle Navne')
names = list(namesdf['Names'])
lastnamesdf = pd.read_excel('names.xlsx', sheet_name='Frie Efternavne')
lastnames = list(lastnamesdf['Frie Efternavne'])
# Import dataset and drop NULLS
df = pd.read_excel(r'Entreprise Beskeder.xlsx', sheet_name='dataark')
df["Besked"].dropna(inplace = True)
# Compare dataset to the created lists to match first and last names
df["Navner"] = df["Besked"].str.contains("|".join(names)) # Creates new column and adds TRUE/FALSE for first names
df["Efternavner"] = df["Besked"].str.contains("|".join(lastnames)) # Creates new column and adds TRUE/FALSE for last names
# Save the result
writer = ExcelWriter('PythonExport.xlsx')
df.to_excel(writer)
writer.save()
</code></pre>
<p><strong>I would appreciate any suggestions that could potentially improve my code</strong> and reduce manual work that it will take to filter out all of these false positive cells that I found! I think the best case scenario would be a case sensitive piece of code that finds only the specific name without merging the text together. Also, it would be great if I could extract a specific string that Python finds a match in, as that would reduce manual work when trying to figure out why exactly a specific block of text was marked as TRUE. All in all, every suggestion is welcome! Thanks :)</p>
|
[] |
[
{
"body": "<p>It sounds like the thing you're trying to do is <em>somewhat</em> insane. With 40k first names to search for, false positives are inevitable. At the same time, with only 40k names, false <em>negatives</em> are also inevitable. <a href=\"https://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/\" rel=\"nofollow noreferrer\">People's names are untidy</a>; hopefully you have plans to accommodate. Even when you get <em>correct</em> matches for a "first" and "last" name, as your example email shows, there's no guarantee that they'll be the first and last names <em>of the same person</em>.</p>\n<p>Maybe someone with experience in natural-language-processing AI would be able to solve your problem in a robust way. More likely you've resigned yourself to a solution that simply <em>isn't</em> robust. You still pretty definitely need case-sensitivity and "whole word" matching.</p>\n<p>I'm not convinced by the example you give of a false positive. The pandas function you're using is regex-based. <code>r'tero'</code> does <em>not</em> match <code>'t er o'</code>; it <em>does</em> match <code>'interoperability'</code>. With name lists as long as you're using, it seems more likely that you over-looked some other match in the email in question. I would kinda expect just a few of the names to be responsible for the majority of false-positives; outputting the matched text will help you identify them.</p>\n<ul>\n<li>Case-sensitive regex matching should be the default.</li>\n<li>I think <code>\\b...\\b</code> as a regex pattern will give the kind of "whole word" matching you need.</li>\n<li><a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.extract.html\" rel=\"nofollow noreferrer\">pandas.extract</a> will do the capturing.</li>\n</ul>\n<p>Given the size of your datasets, you may be a bit concerned with the performance. Or you may not, it's up to you.</p>\n<p>I haven't tested this at all:</p>\n<pre class=\"lang-py prettyprint-override\"><code># Import datasets and create lists/variables\nimport pandas as pd\nfrom pandas import ExcelWriter\nfrom typing import Iterable\n\n# Document, sheet, and column names:\nnames_source_file = 'names.xlsx'\nfirst_names_sheet = 'Alle Navne'\nfirst_names_column = 'Names'\nlast_names_sheet = 'Frie Efternavne'\nlast_names_column = 'Frie Efternavne'\nsubject_file = 'Entreprise Beskeder.xlsx'\nsubject_sheet = 'dataark'\nsubject_column = 'Besked'\noutput_first_name = 'Navner'\noutput_last_name = 'Efternavner'\noutput_file = 'PythonExport.xlsx'\n\n# Build (very large!) search patterns:\nfirst_names_df = pd.read_excel(names_file, sheet_name=first_names_sheet)\nfirst_names: Iterable[str] = namesdf[first_names_column]\nfirst_names_regex = '''\\b{}\\b'''.format('|'.join(first_names))\nlast_names_df = pd.read_excel(names_file, sheet_name=last_names_sheet)\nlast_names: Iterable[str] = lastnamesdf[last_names_column]\nlast_names_regex = '''\\b{}\\b'''.format('|'.join(last_names))\n\n# Import dataset and drop NULLS:\ndata_frame = pd.read_excel(subject_file, sheet_name=subject_sheet)\ndata_frame[subject_column].dropna(inplace=True)\n\n# Add columns for found first and last names:\ndata_frame[output_first_name] = data_frame[subject_column].str.extract(\n first_names_regex,\n expand=False\n)\ndata_frame[output_last_name] = data_frame[subject_column].str.extract(\n last_names_regex,\n expand=False\n)\n\n# Save the result\nwriter = ExcelWriter(output_file)\ndf.to_excel(writer)\nwriter.save()\n</code></pre>\n<p>One obvious problem that I still haven't talked about is that there may be multiple name matches in a given subject. Assuming that you care about multiple matches, you can probably do something with <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.extractall.html#pandas.Series.str.extractall\" rel=\"nofollow noreferrer\">extractall</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-10T08:09:52.740",
"Id": "485010",
"Score": "0",
"body": "Thanks for suggestion! If I use `str.extract(first_names_regex, expand=False)` then I get `ValueError: pattern contains no capture groups`, which points to `expand=False`. However, I have tried to use your code with `str.contains`, which unfortunately gives the exact same match of rows as it did with my original code.\nI have also tried `str.extractall` method, which for some reason gives me a `ValueError: pattern contains no capture groups` pointing to `(first_names_regex)` part of `extractall` method..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-10T13:56:34.017",
"Id": "485022",
"Score": "0",
"body": "Ah. Most tools that use regex capture groups count _the whole regex_ as \"capture group zero\". It sounds like these pandas functions aren't doing that, which is obnoxious I guess. Try adding a [capture group](https://regular-expressions.mobi/refcapture.html?wlr=1)? `first_names_regex = '''\\b({})\\b'''.format(...)`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T14:35:14.823",
"Id": "247474",
"ParentId": "247434",
"Score": "3"
}
},
{
"body": "<p>To see what is being matched, use <code>apply()</code> with a python function:</p>\n<pre><code>import re\n\nregex = re.compile(pat)\n\ndef search(item):\n mo = regex.search(item)\n if mo:\n return mo[0]\n else:\n return ''\n\ndf.msg.apply(search)\n</code></pre>\n<p>This will yield a Series with the names that matched or '' if there isn't a match.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T16:59:08.197",
"Id": "247480",
"ParentId": "247434",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T12:19:26.297",
"Id": "247434",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"strings",
"pandas",
"email"
],
"Title": "Python - use a list of names to find exact match in pandas column containing emails"
}
|
247434
|
<p><strong>Description</strong></p>
<p>A class representing an undirected graph. At the moment, it supports integer values as vertices. An example of the type of graph represented is shown in the following diagram:</p>
<p><a href="https://i.stack.imgur.com/Tudc3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Tudc3.png" alt="enter image description here" /></a></p>
<p>It is represented internally as an array of adjacency lists. Each index of this array corresponds to a vertex number, and contains a <code>List<int></code> of vertex numbers to which it is connected.</p>
<p><strong>Purpose</strong></p>
<p>Purely as an exercise in implementing a data structure. Implemented in C# after studying a Java-based implementation.</p>
<p><strong>Code</strong></p>
<p>The data structure class definition</p>
<pre><code>public class UndirectedGraph
{
// number of vertices
private int _V;
// number of edges
private int _E = 0;
// array of adjacency lists
private List<int>[] _adj;
/// <summary>
/// Constructor to create a graph.
/// </summary>
/// <param name="v">Number of vertices</param>
public UndirectedGraph(int v)
{
this._V = v;
// create array of lists
// initialise all lists to empty
this._adj = new List<int>[v];
for (int i = 0; i < this._adj.Length; i++)
this._adj[i] = new List<int>();
}
// number of vertices
public int V
{
get { return this._V; }
}
// number of edges
public int E
{
get { return this._E; }
}
/// <summary>
/// Add an edge to the graph.
/// </summary>
/// <param name="v">One vertex of the new edge.</param>
/// <param name="w">The other vertex of the new edge.</param>
public void addEdge(int v, int w)
{
// validate given node numbers
if ((v > this._adj.Length) || (w > this._adj.Length))
throw new ArgumentException("Invalid node number specified.");
// add to adjacency lists
this._adj[v].Add(w);
this._adj[w].Add(v);
// increment edge count
this._E++;
}
/// <summary>
/// Get an adjacency list for a vertex.
/// </summary>
/// <param name="v">The vertex.</param>
/// <returns></returns>
public List<int> getAdjacency(int v)
{
return this._adj[v];
}
/// <summary>
/// Get a string representation of the graph's adjacency lists.
/// </summary>
/// <returns></returns>
public override string ToString()
{
StringBuilder builder = new StringBuilder();
builder.AppendLine(this._V + " vertices, " + this._E + " edges");
for (int v = 0; v < this._V; v++)
{
builder.Append(v + ": ");
foreach (var w in this._adj[v])
{
builder.Append(w + " ");
}
builder.AppendLine(string.Empty);
}
return builder.ToString();
}
}
</code></pre>
<p>Sample usage. Prints out a string representation of the example graph in the diagram above to the console:</p>
<pre><code>UndirectedGraph myGraph = new UndirectedGraph(7);
myGraph.addEdge(0,1);
myGraph.addEdge(0,2);
myGraph.addEdge(2,3);
myGraph.addEdge(2,4);
myGraph.addEdge(2,5);
myGraph.addEdge(5,6);
Console.Write(myGraph.ToString());
// RESULT:
7 vertices, 6 edges
0: 1 2
1: 0
2: 0 3 4 5
3: 2
4: 2
5: 2 6
6: 5
</code></pre>
<p><strong>Questions</strong></p>
<ul>
<li>Any feedback about variable names, commenting and implementation details.</li>
<li>Changes, if any, to make it unit-testable.</li>
<li>Ways to include C# 7.0 features, if they haven't been already.</li>
<li>How to extend this to other data types, such as <code>string</code>.</li>
<li>Performance improvements might be interesting.</li>
</ul>
|
[] |
[
{
"body": "<h1>Naming</h1>\n<p>Renaming your instance variable <code>_V</code> and <code>_E</code> to <code>nbVertices</code> and <code>nbEdges</code> respectively allows you get rid of two unnecessary comments and also makes the rest of the code much clearer, especially to someone who's not too familiar with graph notation.</p>\n<p>I'm also not a big fan of prefixing private instance variables with underscores, but that's just my personal opinion.</p>\n<p>Similarly, you could give most of your methods' arguments much clearer names.</p>\n<p>The standard naming convention for C# is to use <code>PascalCase</code> for methods & properties, and <code>camelCase</code> for fields, so I would rename <code>getAdjacency()</code> and <code>addEdge()</code> to <code>GetAdjacency()</code> and <code>AddEdge()</code>.</p>\n<h1>Properties</h1>\n<pre><code> // number of vertices\n public int V\n {\n get { return this._V; }\n }\n\n // number of edges\n public int E\n {\n get { return this._E; }\n }\n</code></pre>\n<p>can be changed to</p>\n<pre><code> // number of vertices\n public int V\n {\n get => this._V;\n }\n\n // number of edges\n public int E\n {\n get => this._E;\n }\n</code></pre>\n<p>which can further be simplified to</p>\n<pre><code> // number of vertices\n public int V => this._V;\n\n // number of edges\n public int E => this._E;\n</code></pre>\n<p>You could go one step further and merge <code>V</code> and <code>_V</code> into a single property, like this :</p>\n<pre><code>public int V { get; private set; }\n\npublic int E { get; private set; }\n</code></pre>\n<p>and since <code>V</code> doesn't change after being set in the constructor, you can go even <em>further beyond</em> and make <code>V</code> into a read-only property :</p>\n<pre><code>public int V { get; }\n</code></pre>\n<p>This makes it so that <code>V</code> can only be set once in the constructor.</p>\n<h1>Comments</h1>\n<p>Personal opinion again, but I don't like comments, especially when they can be made useless by simply changing a variable or a method's name, as was the case with your declarations of <code>_V</code> or <code>_E</code>.</p>\n<p>I also really don't like comments that just say what the code is doing, like in your <code>addEdge()</code> method :</p>\n<pre><code>public void addEdge(int v, int w)\n{\n // validate given node numbers\n if ((v > this._adj.Length) || (w > this._adj.Length))\n throw new ArgumentException("Invalid node number specified.");\n\n // add to adjacency lists\n this._adj[v].Add(w);\n this._adj[w].Add(v);\n // increment edge count\n this._E++;\n}\n</code></pre>\n<p>These comments add nothing more than redundant, distracting text that makes the code harder to read. If you see a line of code that says <code>NbEdges++;</code>, do you really need a comment to say <code>// increment edge count</code> ?</p>\n<h1>Exceptions</h1>\n<p>I'd recommend always throwing the exception that most closely fits the issue, which in this case would be an <code>ArgumentOutOfRangeException</code> (which is derived from <code>ArgumentException</code>).</p>\n<p>Additionally, I would make the exception message more clear and give more information about what actually went wrong. Imagine being a user and seeing "Invalid node number specified."; which argument was wrong? Was it <code>v</code> or <code>w</code>? Why was the value wrong?</p>\n<p>You could go even further and create your own exception class that inherits said exception, in order to reduce code repetition and give your exceptions meaningful names which would help your users.</p>\n<pre><code>if (v < 0 || v > this._adj.Length)\n{\n throw new ArgumentOutOfRangeException($"Error, the value provided for 'v' should be" + \n "between 0 and {this._adj.Length - 1}\\n" + \n "\\tv = {v}\\n");\n}\n\nif (w < 0 || w > this._adj.Length)\n{\n throw new ArgumentOutOfRangeException($"Error, the value provided for 'v' should be" + \n "between 0 and {this._adj.Length - 1}\\n" + \n "\\tv = {v}\\n");\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T15:03:18.317",
"Id": "247440",
"ParentId": "247435",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "247440",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T12:39:14.937",
"Id": "247435",
"Score": "3",
"Tags": [
"c#",
".net",
"classes"
],
"Title": "Undirected graph data structure in C#"
}
|
247435
|
<p>I have implemented a solution for finding all anagrams. Are there any other suggestions for improving the solution?</p>
<pre><code>package main.algorithms;
import java.util.ArrayList;
import java.util.List;
public class AllAnagrams {
// Sliding window
public static void main(String args[]) {
// s: "cbaebabacd" p: "abc"
String str = "cbaebabacd";
String partial = "abc";
findAnagrams(str, partial);
}
public static void findAnagrams(String s, String p){
List<Integer> list = new ArrayList<>();
if (s == null || s.length() == 0 || p == null || p.length() == 0) return;
int[] hash = new int[256]; //character hash
//record each character in p to hash
for (char c : p.toCharArray()) {
hash[c]++;
}
//two points, initialize count to p's length
int left = 0, right = 0, count = p.length();
while (right < s.length()) {
//move right everytime, if the character exists in p's hash, decrease the count
//current hash value >= 1 means the character is existing in p
if (hash[s.charAt(right++)]-- >= 1) count--;
//when the count is down to 0, means we found the right anagram
//then add window's left to result list
if (count == 0) list.add(left);
//if we find the window's size equals to p, then we have to move left (narrow the window) to find the new match window
//++ to reset the hash because we kicked out the left
//only increase the count if the character is in p
//the count >= 0 indicate it was original in the hash, cuz it won't go below 0
if (right - left == p.length() && hash[s.charAt(left++)]++ >= 0) count++;
}
System.out.println(list);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T13:16:22.873",
"Id": "484627",
"Score": "0",
"body": "What the inputs `s` and `p` mean, and what is the expected output? And what does this have to do with anagrams?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-10T03:39:01.313",
"Id": "484980",
"Score": "0",
"body": "Are you looking for readability or performance?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T12:40:21.510",
"Id": "247437",
"Score": "3",
"Tags": [
"java"
],
"Title": "Hashing and sliding window for string"
}
|
247437
|
<p>I have a script that makes a bunch of api calls (xml) and it's not adhering to DRY because I am repeating a lot of the code in the functions, what would be the best way to clean this up and reduce the amount of repeat code?</p>
<pre><code>def get_api_key(hostname, username, password):
url = 'https://' + hostname + '/api'
values = {'type': 'keygen', 'user': username, 'password': password}
response = requests.post(url, params=values, verify=False, proxies=proxies)
return ET.fromstring(response.text).find('.//result/key').text
def add_template(hostname, api_key, template_name, name):
url = 'https://' + hostname + '/api'
values = {'type': 'config',
'action': 'set',
'xpath': f"entry[@name='{template_name}']/",
'element': f"<tag>{name}</tag>",
'key': api_key
}
requests.post(url, params=values, verify=False, proxies=proxies)
return(template_name)
def add_template_stack(hostname, api_key, stack_name, template_name):
url = 'https://' + hostname + '/api'
values = {'type': 'config',
'action': 'set',
'xpath': f"entry[@name='{stack_name}']",
'element': f"<tag>{template_name}</tag>",
'key': api_key
}
requests.post(url, params=values, verify=False, proxies=proxies)
return(stack_name)
def add_variable(template_name, var_name, netmask, hostname, api_key):
url = 'https://' + hostname + '/api'
values = {'type': 'config',
'action': 'set',
'xpath': f"entry[@name='{template_name}']/variable/entry[@name='{var_name}']",
'element': f"<tag>{netmask}</tag>",
'key': api_key
}
requests.post(url, params=values, verify=False, proxies=proxies)
return(var_name)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T17:47:20.847",
"Id": "484298",
"Score": "1",
"body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state the task accomplished by the code. Please see [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask), as well as [How to get the best value out of Code Review: Asking Questions](https://codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T21:59:25.393",
"Id": "484323",
"Score": "0",
"body": "Not enough for an answer, but `return` shouldn't have parenthesis after it. Just `return x`."
}
] |
[
{
"body": "<p>I think a good way to reduce the WET code here is to consolidate and generalize the core functionality to a single function, and tweak the arguments going into it accordingly. I left the <code>get_api_key</code> function alone and focused on the other ones as they are the most similar. See below:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def add_template_2(hostname, api_key, template_name, name):\n return add(hostname, api_key, template_name, name)\n\n\ndef add_template_stack_2(hostname, api_key, stack_name, template_name):\n return add(hostname, api_key, stack_name, template_name)\n\n\ndef add_variable_2(template_name, var_name, netmask, hostname, api_key):\n return add(hostname, api_key, template_name, netmask, var_name)\n\n\ndef add(hostname, api_key, xpath_name, element, xpath_var=None):\n url = f'https://{hostname}/api'\n\n if xpath_var:\n xpath = f"entry[@name='{xpath_name}']/variable/entry[@name='{xpath_var}']"\n ret_val = xpath_var\n else:\n xpath = f"entry[@name='{xpath_name}']"\n ret_val = xpath_name\n\n values = {'type': 'config',\n 'action': 'set',\n 'xpath': xpath,\n 'element': f"<tag>{element}</tag>",\n 'key': api_key\n }\n requests.post(url, params=values, verify=False, proxies=proxies)\n return(ret_val)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T20:24:58.857",
"Id": "247453",
"ParentId": "247449",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T17:36:16.443",
"Id": "247449",
"Score": "5",
"Tags": [
"python"
],
"Title": "What is the best way to make this code dry?"
}
|
247449
|
<p>So I started this question, I believe i have synchronized the methods correctly, need some insight on whats wrong and what should be done. I have to modify ths class Purse so that the method AddCoin is synchronized and implement a synchronized RemoveCoin method with a Coin argument, I believe that is done just fine. Where im really having trouble is implementing thread that adds pennies, another thread that adds quarters, and another thread that removes and prints randomly selected coins, pennies, quarters, any one. Then finally synchronize the threads to wait for each other when necessary. Here is what I have so far:</p>
<p><strong>Purse.cs</strong></p>
<pre><code>using System;
using System.Collections;
using System.Threading;
namespace TestingProject
{
/// <summary>
/// A purse holds a collection of coins.
/// </summary>
public class Purse
{
/// Constructs an empty purse.
public Purse()
{
coins = new ArrayList();
}
/// Add a coin to the purse.
/// @param aCoin the coin to add
public void Add(Coin aCoin)
{
Monitor.Enter(coins);
coins.Add(aCoin);
Monitor.Exit(coins);
}
public void RemoveCoin(Coin aCoin)
{
Monitor.Enter(coins);
coins.Remove(aCoin);
Monitor.Exit(coins);
}
/// Get the total value of the coins in the purse.
/// @return the sum of all coin values
public double GetTotal()
{
double total = 0;
for (int i = 0; i < coins.Count; i++)
{
Coin aCoin = (Coin)coins[i];
total = total + aCoin.GetValue();
}
return total;
}
private ArrayList coins;
}
}
</code></pre>
<p><strong>Coin.cs</strong></p>
<pre><code>using System;
using System.Collections;
namespace TestingProject
{
/// <summary>
/// A coin with a monetary value.
/// </summary>
public class Coin {
/// Constructs a coin.
/// @param aValue the monetary value of the coin
/// @param aName the name of the coin
public Coin(double aValue, String aName)
{
value = aValue;
name = aName;
}
public Coin()
{
}
/// Gets the coin value.
/// @return the value
public double GetValue()
{
return value;
}
/// Gets the coin name.
/// @return the name
public String GetName()
{
return name;
}
public override bool Equals(Object otherObject)
{
Coin other = (Coin)otherObject;
return name==other.name
&& value == other.value;
}
// C# requirement:
// since we override Equals, MUST also override GetHashCode ( !! )
public override int GetHashCode()
{
return base.GetHashCode ();
}
private double value;
private string name;
}
}
</code></pre>
<p><strong>pursetest.cs</strong></p>
<pre><code>using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualBasic;
namespace TestingProject
{
class PurseTest
{
public static void Main(string[] args)
{
// Random object used by each thread
Random random = new Random();
Purse purse =new Purse();
Coin coin = new Coin();
// output column heads and initial buffer state
Console.WriteLine("{0,-35}{1,-9}{2}\n",
"Operation", "Buffer", "Occupied Count");
Thread purseThread =
new Thread(new ThreadStart(purse.Add))
{
Name = "Purse"
};
Thread coinThread =
new Thread(new ThreadStart(coin.GetValue));
coinThread.Name = "coin";
// start each thread
purseThread.Start();
coinThread.Start();
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T20:08:29.357",
"Id": "484310",
"Score": "4",
"body": "1. `ArrayList` should only be used if it's before 2005. Read up on generics (`List<Coin>`).\n2. Don't use `Monitor.Enter`/`Exit` manually, investigate the `lock` keyword."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T20:15:07.650",
"Id": "484313",
"Score": "0",
"body": "familiar with list<coin> but I had to use ArrayList for some reason on this program"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T07:24:44.887",
"Id": "484354",
"Score": "2",
"body": "Is this a conversion of a Java program? The code has a distinctly Java feel to it... Anyway, are you limited to an early .Net framework? Some of the advice I'd give isn't applicable if you're stuck on an old version."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T08:14:31.047",
"Id": "484357",
"Score": "0",
"body": "@tylerj You have missed the synchronization for `Purse`'s `GetTotal`. While you are iterating through the `coins` you don't want to allow to change the collection."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T14:35:41.183",
"Id": "484388",
"Score": "0",
"body": "The `Purse` class could be almost implemented by using [SynchronizedCollection<T>](https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.synchronizedcollection-1?view=netframework-4.8), which provides a ready made thread safe container instead of locking yourself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T15:53:39.093",
"Id": "484392",
"Score": "1",
"body": "For anything regarding money or currency, you should prefer `Decimal` over `double`. `double` is a binary floating point and its an *approximation* to a value, whereas `Decimal` is base-10 floating point and represents exact values. This is particularly critical with decimal places."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T15:55:47.003",
"Id": "484393",
"Score": "1",
"body": "Can you provide a stronger justification as to why you believe you must use `ArrayList`?"
}
] |
[
{
"body": "<p>Taking a look at your Coin class, there are a few things that aren't quite idiomatic C#.</p>\n<p>The most obvious thing is that you're using what looks nearly like Java Doc comments. C# uses XML doc comments so this:</p>\n<pre><code>/// Constructs a coin.\n/// @param aValue the monetary value of the coin\n/// @param aName the name of the coin\n</code></pre>\n<p>Should be:</p>\n<pre><code>/// <summary>Constructs a Coin.</summary>\n/// <param name="aValue">The monetary value of the Coin.</param>\n/// <param name="aName">The name of the Coin.</param>\n</code></pre>\n<p>In C#, we have properties which mean you don't need to write explicit GetXyz and SetXyz. I'm not sure whether you're using an old version of .Net (e.g. using ArrayList) but it's normal to have those as auto-implemented properties like this:</p>\n<pre><code> public double Value { get; }\n public string Name { get; }\n</code></pre>\n<p>If you can't use auto-properties, you'll have to do a bit more typing. I'm going to assume you're stuck on an older .Net and try to avoid newer features.</p>\n<pre><code>private readonly double value;\npublic double Value \n{\n get\n {\n return value;\n }\n}\n</code></pre>\n<p>That means you get rid of GetValue and GetName methods. I'd also suggest that you remove the empty constructor to force creation with a value and a name. That only leaves your Equals and GetHashcode implementations.</p>\n<p>Let's consider a couple of test cases:</p>\n<pre><code>new Coin().Equals("blah"); // InvalidCastException :(\nnew Coin().Equals(null); // NullReferenceException :(\n</code></pre>\n<p>Oh dear, we've got a problem here! Let's fix those bugs:</p>\n<pre><code>public override bool Equals(Object otherObject)\n{\n return Equals(otherObject as Coin);\n}\n\npublic bool Equals(Coin coin)\n{\n if (ReferenceEquals(null, coin))\n return false;\n\n return coin.Value == this.Value && coin.Name == this.Name;\n}\n</code></pre>\n<p>That's nice and clear and most importantly, is correct! This is a common pattern and you can implement IEquatable at the same time if you want.\nI think a coin should have a name in your model so you should validate that in the constructor.</p>\n<p>So we're up to here:</p>\n<pre><code>/// <summary>\n/// A coin with a monetary value.\n/// </summary>\npublic class Coin : IEquatable<Coin>\n{\n private readonly double value;\n \n public double Value\n {\n get\n {\n return value;\n }\n }\n \n private string name;\n \n public string Name \n {\n get\n {\n return name;\n }\n }\n\n /// <summary>Constructs a coin.</summary>\n /// <param name="value">The monetary value of the Coin</param>\n /// <param name="name">The name of the Coin</param>\n public Coin(double value, string name)\n {\n if (name == null)\n throw new ArgumentNullException("name");\n this.value = value;\n this.name = name;\n }\n\n public override bool Equals(Object otherObject)\n {\n return Equals(otherObject as Coin);\n }\n\n public bool Equals(Coin coin)\n {\n if (ReferenceEquals(null, coin))\n return false;\n\n return coin.Value == this.Value && coin.Name == this.Name;\n }\n \n // C# requirement: \n // since we override Equals, MUST also override GetHashCode ( !! )\n public override int GetHashCode()\n {\n return base.GetHashCode();\n }\n \n}\n</code></pre>\n<p>So, only one thing left to talk about: <code>GetHashCode</code>. We must override GetHashCode <strong>and implement it correctly</strong>. I'll link you to this SO post: <a href=\"https://stackoverflow.com/questions/371328/why-is-it-important-to-override-gethashcode-when-equals-method-is-overridden\">https://stackoverflow.com/questions/371328/why-is-it-important-to-override-gethashcode-when-equals-method-is-overridden</a></p>\n<p>Your <code>GetHashCode</code> should look like this:</p>\n<pre><code>public override int GetHashCode()\n{\n int hash = 13;\n hash = (hash * 7) + Value.GetHashCode();\n hash = (hash * 7) + Name.GetHashCode();\n return hash;\n}\n</code></pre>\n<p>Now we've got a class that correctly implements equality.</p>\n<p>ETA:</p>\n<p>As has been pointed out in the comments, <code>value</code> is a contextual keyword so you may want to think twice before calling a field <code>value</code>. I don't see the problem myself as syntax highlighting in VS, for example, would know it wasn't a keyword. Calling it <code>theValue</code> would be worse for readability in my opinion. If you're on C# 6 or later, you should prefer the auto property so you don't need the field. Either way, if you write this class well at the beginning, the field is an implementation detail and you'll never read this source code again.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T12:29:02.670",
"Id": "484373",
"Score": "0",
"body": "`value` is a keyword, you cannot use it as a field name."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T12:50:26.657",
"Id": "484376",
"Score": "0",
"body": "I can't find when it was introduced right now but more recent versions of .NET have a System.HashCode struct for generating hashcodes like this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T13:06:52.020",
"Id": "484378",
"Score": "0",
"body": "@Vivelin - I've only seen that used in .Net Core so I think it's pretty new. It was definitely after Tuple got introduced as people were using that to get a good hash. It's definitely a good one to know though!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T13:34:50.050",
"Id": "484381",
"Score": "0",
"body": "@Flater - it's a contextual keyword like async so it's valid. Perhaps it is bad to use here (and I typed it into CR so didn't even think about it). It's the same reason you can do this: `class async { public async Do(async async) => async; }`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T21:06:33.973",
"Id": "484418",
"Score": "0",
"body": "Actually seen in code at one point: `float @double = (int)3.1415m;` Just because you *can* doesn't mean you *should*..."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T08:09:05.073",
"Id": "247464",
"ParentId": "247450",
"Score": "8"
}
},
{
"body": "<p>The <code>Purse</code> class could be rewritten in the following way:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public class Purse\n{\n private ArrayList coins = new ArrayList();\n private readonly object lockObject = new object();\n\n public void Add(Coin aCoin)\n {\n lock (lockObject)\n {\n coins.Add(aCoin);\n }\n }\n public void RemoveCoin(Coin aCoin)\n {\n lock (lockObject)\n {\n coins.Remove(aCoin);\n }\n }\n\n public double GetTotal()\n {\n lock (lockObject)\n {\n return coins.Cast<Coin>().Sum(aCoin => aCoin.GetValue());\n }\n }\n}\n</code></pre>\n<p>Some remarks regarding the code:</p>\n<ol>\n<li>As the OP stated <code>ArrayList</code> could not be change. So here we can't use neither generic collections nor concurrent collections.<br />\n1.1) In order to be able to use <code>System.Linq</code> on an <code>ArrayList</code>, first we have to call the <code>Cast<T></code> operator</li>\n<li>Syncronization is needed not just for the write operations but also for read operations as well.<br />\n2.1) All shared resource access should be protected when you want to expose thread-safe methods<br />\n2.2) You should consider to use <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.threading.readerwriterlockslim?view=netcore-3.1\" rel=\"noreferrer\">Read Write Lock</a> if you want to allow multiple read access at the same time</li>\n<li>You should use a dedicated lock object as the <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/lock-statement#guidelines\" rel=\"noreferrer\">Guidlines</a> says<br />\n3.1) Visual Studio can warn you if you forgot to protect one of the shared resource access\n<a href=\"https://i.stack.imgur.com/8q6X6.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/8q6X6.png\" alt=\"Missing lock statement\" /></a></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T12:34:15.390",
"Id": "484374",
"Score": "1",
"body": "ad 3) that's a misreading of the guidelines. The full quote is \"lock on a dedicated object instance [...] or another instance that is unlikely to be used as a lock object by unrelated parts of the code. **Avoid using the same lock object instance for different shared resources**\" (emphasis mine). Locking a collection when you access that specific collection is consistent with this guideline, and far less confusing. And since it's a private, never-exposed variable, it is very unlikely to be used by unrelated parts of the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T14:03:39.027",
"Id": "484386",
"Score": "0",
"body": "@SebastianRedl Yes, your observation is correct. In this particular case all requirements are satisfied by the `coins` private field. Personally I prefer to have a separate lock object. I also try to strive to have at most one shared resource per type."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T08:33:04.633",
"Id": "247465",
"ParentId": "247450",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T17:54:12.187",
"Id": "247450",
"Score": "8",
"Tags": [
"c#",
"object-oriented",
"multithreading",
"thread-safety"
],
"Title": "C# threading and synchronizing methods"
}
|
247450
|
<p>I decided that in order to get better at programming, I should focus on building and improving simple projects. I have made a library program that contains collections of unique books of varying quantities. Although this runs as expected, I am not satisfied with the potential of expanding it to complexities. What are the ways I can improve the efficiency of this program's code, and allow greater potential of increasing the complexity of it? Thank you.</p>
<h2>Book.java</h2>
<pre><code>/*
* This class defines the uniqueness of each individual book
* that is part of a separate collection
*
*/
public class Book {
private boolean borrowed; //Each book is either borrowed or not
public Book() {
this.borrowed = false;
}
public void setToBorrowed() { //Method will fire once a book has been checked out
this.borrowed = true;
}
public void setToReturned() { //Method will fire once book has been returned to the library catalog
this.borrowed = false;
}
public boolean isBorrowed() { //Determines whether the book is borrowed or not
return this.borrowed;
}
}
</code></pre>
<h2>BookCollection.java</h2>
<pre><code>
import java.util.ArrayList;
import java.util.List;
/*
* The purpose of this class is to define a collection of books for different titles
*/
public class BookCollection {
private int quantity; //Number of copies for each book collection
List<Book> books = new ArrayList<>(); //Collection of individual books
public BookCollection(int quantity) { //Creates a collection of books with a defined # of copies
this.quantity = quantity;
for(int i = 0; i < quantity; i++) {
books.add(new Book());
}
}
public void addBook() { //Adds a new book object to the collection of books
books.add(new Book());
}
public boolean borrowBook() { //Borrows a book from the collection
for(Book b : books) {
if(!b.isBorrowed()) {
b.setToBorrowed();
return true; //Book has been borrowed successfully
}
else {
continue;
}
}
System.out.println("All books are borrowed, sorry");
return false; //Book has failed to be borrowed
}
public boolean returnBook() { //Returns a book back to the catalog
for(Book b : books) {
if(b.isBorrowed()) {
b.setToReturned();
return true; //Book has been returned successfully
}
else {
continue;
}
}
System.out.println("Cannot return book at this time, sorry!");
return false; //Book has failed to be returned
}
public void printBooks() {
for(Book b : books) {
System.out.println("Borrowed? " + b.isBorrowed());
}
}
public int getQuantity() { //Returns the # of copies the collection has, borrowed or not
return this.quantity;
}
}
</code></pre>
<h2>Library.java</h2>
<pre><code>import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
/*
* This class is the engine of the program
*/
public class Library {
static Map<BookCollection, String> bookCatalog =
new HashMap<BookCollection, String>(); //Entire collection of books
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
//Test BookCollection objects:
BookCollection book1 = new BookCollection(5);
BookCollection book2 = new BookCollection(3);
BookCollection book3 = new BookCollection(2);
bookCatalog.put(book1, "Cracking the Coding Interview");
bookCatalog.put(book2, "Crime and Punishment");
bookCatalog.put(book3, "Catch-22");
//Client borrows 2 copies of Catch-22
borrowBook("Catch-22");
borrowBook("Catch-22");
printCatalog();
System.out.println();
//Client returns the copies
returnBook("Catch-22");
returnBook("Catch-22");
//Test if catalog has been updated correctly
printCatalog();
System.out.println();
}
/*
* printCatalog()
*
* Return type: void
*
* This method prints out each collection of books
*/
public static void printCatalog() {
for(Map.Entry<BookCollection, String> entry : bookCatalog.entrySet()) {
BookCollection bc = (BookCollection) entry.getKey();
System.out.println("Title: " + entry.getValue());
bc.printBooks();
System.out.println();
}
}
/*
* I am sure there is a way to simplify 'borrowBook()' and 'returnBook()' by use of a new method
* that does what both of these already do (searching for a book title match)
*/
/*
* borrowBook(String bookTitle)
*
* Return type: void
*
* This method borrows a book from a collection
*/
public static void borrowBook(String bookTitle) { //Borrows a book from the entire library catalog
for(Map.Entry<BookCollection, String> entry : bookCatalog.entrySet()) {
if(entry.getValue().equals(bookTitle)) {
BookCollection bc = (BookCollection) entry.getKey();
if(bc.borrowBook())
System.out.println("You have successfully borrowed " + bookTitle);
else
System.out.println("All copies of " + bookTitle + " have been checked out already, sorry! :(");
return;
}
else {
continue;
}
}
System.out.println(bookTitle + " doesn't exist - sorry!");
}
/*
* returnBook(String bookTitle)
*
* Return type: void
*
* This method returns a book back to the collection of books
*
*/
public static void returnBook(String bookTitle) {
for(Map.Entry<BookCollection, String> entry : bookCatalog.entrySet()) {
if(entry.getValue().equals(bookTitle)) {
BookCollection bc = (BookCollection) entry.getKey();
if(bc.returnBook())
System.out.println("You have successfully returned " + bookTitle);
else
System.out.println(bookTitle + " cannot be returned at this time");
return;
}
else {
continue;
}
}
System.out.println(bookTitle + " doesn't exist - sorry!");
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T01:50:03.590",
"Id": "484337",
"Score": "2",
"body": "At first glance, you need to change most of your Library class code from static to non-static. Creating one instance of Library is more extensible than a static class. Also, your bookCatalog map belongs in a model class. The model / view / controller pattern is powerful when creating a Java application. https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T05:52:27.740",
"Id": "484344",
"Score": "0",
"body": "@GilbertLeBlanc I appreciate your comment and will study the MVC design pattern. I was concerned with my map's implementation and its lack of flow with the rest of the program."
}
] |
[
{
"body": "<p>As suggested by <em>Gilbert Le Blanc</em> there are some useful structural patterns that\ncan be applied in your case. But one thing at a time.</p>\n<p>In your <code>Library</code> class there is this comment:</p>\n<blockquote>\n<p>I am sure there is a way to simplify 'borrowBook()' and 'returnBook()' by use of\nnew method that does what both of these already do (searching for a book title\nmatch)</p>\n</blockquote>\n<p>You are right, there are some improvements that could be made on that part. The\nfirst one I see is the usage of your map; One advantage of a map is to\nquickly/efficiently retrieve an item by key. In your case the key is not the\nbook, but the <em>title</em>.</p>\n<pre><code>private static static Map<String, BookCollection> booksByTitle = new HashMap<>();\n\n// ...\n\npublic static void borrowBook(String bookTitle) {\n if ( !booksByTitle.containsKey(bookTitle) ) {\n System.out.println(bookTitle + " doesn't exist - sorry!");\n return;\n }\n \n BookCollection collection = booksByTitle.get(bookTitle);\n if(collection.borrowBook())\n System.out.println("You have successfully borrowed " + bookTitle);\n else\n System.out.println("All copies of " + bookTitle + " have been checked out already, sorry! :(");\n}\n</code></pre>\n<p>Once done, you see that the two methods <code>borrowBook</code> and <code>returnBook</code> are similar,\nonly the operation and message is different. You can then refactor your code to\nextract that code :</p>\n<pre><code>private static void doInCollection(String title, Consumer<BookCollection> operation) {\n if (!booksByTitle.containsKey(title)) {\n System.out.println(title + " doesn't exist - sorry!");\n return;\n }\n operation.accept(booksByTitle.get(title));\n}\n</code></pre>\n<p>(<strong>Added with edit 1</strong>:)\nThat you use with :</p>\n<pre><code>public void borrowBook(String bookTitle) {\n doInCollection(bookTitle, collection -> {\n if (collection.borrowBook())\n System.out.println("You have successfully borrowed " + bookTitle);\n else\n System.out.println("All copies of " + bookTitle + " have been checked out already, sorry! :(");\n });\n}\n</code></pre>\n<p>At that time, you should convert the methods from your <code>Library</code> to instance\nmethods and took that opportunity to encapsulate the <code>booksByTitle</code> map.</p>\n<pre><code>public static void main(String[] args) {\n Library library = new Library();\n library.add(5, "Cracking the Coding Interview");\n library.add(3, "Crime and Punishment");\n library.add(2, "Catch-22");\n\n library.borrowBook("Catch-22");\n library.borrowBook("Catch-22");\n\n library.printCatalog();\n System.out.println();\n\n //Client returns the copies\n library.returnBook("Catch-22");\n library.returnBook("Catch-22");\n\n //Test if catalog has been updated correctly\n library.printCatalog();\n System.out.println();\n} \n</code></pre>\n<p>At this time, we can wonder what is the role of your <code>Book</code> class ? It is just a\nwrapper around a <code>boolean</code>. You are also printing them as a boolean while, it\nwould be easier to print the number of copie available and borrowed.</p>\n<p>So you can remove the <code>Book</code> class and manage two counters in your<br />\n<code>BookCollection</code>.</p>\n<pre><code>class BookCollection {\n private int quantity;\n private int available;\n \n // ...\n public boolean borrowBook() { //Borrows a book from the collection\n if ( available>0 ) {\n available -= 1;\n return true;\n } else {\n System.out.println("All books are borrowed, sorry");\n return false;\n }\n }\n \n // ...\n}\n</code></pre>\n<p>Now, if you want to apply the <em>MVC</em> pattern, your <code>BookCollection</code> seems to be a\ngood candidate for the model while the <code>Library</code> looks like a controller once\nall call to <code>System.out</code> are moved to a dedicated (view) class.</p>\n<p>Another improvement would be to use <em>Exceptions</em> and query methods instead of\n<code>boolean</code> to manage exceptional cases.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T19:39:06.987",
"Id": "484411",
"Score": "0",
"body": "Thank you for the very helpful suggestions. I have not seen the 'Consumer' interface in Java until now, so I am trying to figure out its role in your reply. in the 'doInCollection' method, what does operation.accept() entail?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T06:00:54.987",
"Id": "484445",
"Score": "1",
"body": "Let's say that `Consumer` is a function that receive one parameter (`BookCollection` in our case) and return nothing. The _lambdas syntax_ (>=Java 8) allow you to create one with a simple syntax: `parameter -> { body }`. I will edit my answer to add this example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T00:48:15.430",
"Id": "484563",
"Score": "0",
"body": "I just want to make sure I understand your example of functional programming because this concept is new to me. With the code `doCollection(bookTitle, collection -> {//Code});` are we telling the program to pass in the result of an accepted `BookCollection` value into a block of code that will later check if a book can be borrowed or not? Thank you again for your response."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T10:02:06.157",
"Id": "484607",
"Score": "1",
"body": "Yes, you have understood it well."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T07:38:26.210",
"Id": "247463",
"ParentId": "247455",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "247463",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T21:09:51.977",
"Id": "247455",
"Score": "6",
"Tags": [
"java"
],
"Title": "Book library with borrowing support"
}
|
247455
|
<p>I would like your opinion of my <a href="https://docs.microsoft.com/en-us/powershell/" rel="nofollow noreferrer">PowerShell</a> function. Does it follow conventions, and what could can I do to improve it. It is made to create <a href="https://en.wikipedia.org/wiki/Lightweight_Directory_Access_Protocol" rel="nofollow noreferrer">LDAP</a> friendly username from a full name in <a href="https://en.wikipedia.org/wiki/Serbian_language" rel="nofollow noreferrer">Serbian language</a>.</p>
<pre><code>function Get-UsernameFromFullName
{
[CmdletBinding()]
param
(
[Parameter(Position = 0, Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
[string]
$FullName,
[Parameter(Position = 1, Mandatory = $false, ValueFromPipelineByPropertyName = $true)]
[ValidateSet('First', 'Last')]
[string]
$LastNamePosition = 'First'
)
$usernameComponents = $FullName.ToLower().Split(" ")
switch ($LastNamePosition)
{
'First' { $firstName = $usernameComponents.Length -1; $lastName = 0 }
'Last' { $firstName = 0; $lastName = $usernameComponents.Length -1 }
Default { $firstName = $usernameComponents.Length -1; $lastName = 0 }
}
$chars = ($usernameComponents.Get($firstName) + "." + $usernameComponents.Get($lastName)).ToCharArray()
foreach($char in $chars)
{
switch($char)
{
'ć' { $segment = "c" }
'č' { $segment = "c" }
'đ' { $segment = "dj" }
'š' { $segment = "s" }
'ž' { $segment = "z" }
default { $segment = $char }
}
$Username += $segment
}
return $Username
}
</code></pre>
<p>Here is a <a href="https://github.com/Zoran-Jankov/Uni-PowerShell-Library/blob/master/Get-UsernameFromFullName.psm1" rel="nofollow noreferrer">link</a> to GitHub page of the actual <code>.psm1</code> file.</p>
<p>This is an example of the function usage:</p>
<pre><code>Get-UsernameFromFullName -FullName "Čedomir Đorđević"
</code></pre>
<p>cedomir.djordjevic</p>
<pre><code>Get-UsernameFromFullName -FullName "JANKOV ZORAN"
</code></pre>
<p>zoran.jankov</p>
<pre><code>Get-UsernameFromFullName -FullName "Stojić Gradimir"
</code></pre>
<p>gradimir.stojic</p>
<pre><code>Get-UsernameFromFullName -FullName "Vučićević R Željko"
</code></pre>
<p>zeljko.vucicevic</p>
<pre><code>Get-UsernameFromFullName -FullName "Magda Boškić" -LastNamePosition Last
</code></pre>
<p>magda.boskic</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T02:04:18.763",
"Id": "484339",
"Score": "2",
"body": "could you add some sample names & the result from processing them? i have a hard time thinking about things without something solid to work with ... [*blush*]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T06:05:20.177",
"Id": "484346",
"Score": "0",
"body": "@Lee_Dailey I have added the picture of the function usage example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T07:40:27.760",
"Id": "484355",
"Score": "4",
"body": "PLEASE, do not post images of text/code/sample-data/errors. why force others to squint to read it ... or to type it in to test it? for example, the reason to ask for samples is to see how the code runs when given sample data to work with. i am not willing to type up 4-5 sample names just to help test your code. so _please_ post the requested sample data in a usable format - text. [*grin*]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T11:50:07.437",
"Id": "484370",
"Score": "0",
"body": "@Lee_Dailey Is this good enough?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T04:05:05.387",
"Id": "484440",
"Score": "2",
"body": "yep! [*grin*] all i needed was the names, not the command line ... but that gives me some sample data to work with after i strip out the commands. i have a few ideas, so i otta have a bit of commentary sometime in the next 18 hours or so. gotta take care of \"real life\" 1st ... [*grin*]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T04:48:14.247",
"Id": "484441",
"Score": "0",
"body": "is the 1st example of the desired output reversed? you show `input = \"Čedomir Đorđević\" ` and `output = cedomir.djordjevic`, but your default is to show `last.first`, not `first.last`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T12:49:32.763",
"Id": "484503",
"Score": "0",
"body": "@Lee_Dailey 1st example is a my typing error and not the error of the function"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T12:52:42.330",
"Id": "484504",
"Score": "3",
"body": "Please do not edit the code after you have an answer! See our [help center](https://codereview.stackexchange.com/help/someone-answers)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T13:28:52.307",
"Id": "484512",
"Score": "2",
"body": "@ZoranJankov - thank you for the info ...i was wondering why ... [*grin*]"
}
] |
[
{
"body": "<p>i think the comments cover the why of things, but please feel free to ask if you have any questions. [<em>grin</em>]</p>\n<pre><code>#region >>> fake reading in a list of names\n# in real life, use Get-Content\n$InStuff = @'\nČedomir Đorđević\nJANKOV ZORAN \nStojić Gradimir\nVučićević R Željko\nMagda Boškić\n'@ -split [System.Environment]::NewLine\n\n<# intended output\ncedomir.djordjevic\nzoran.jankov\ngradimir.stojic\nzeljko.vucicevic \nmagda.boskic [lastname @ end]\n#>\n#endregion >>> fake reading in a list of names\n\n\n\nfunction Get-UserNameFromFullName\n # your "Get-UsernameFromFullName" name leaves the "N" in "Username" in lowercase\n # that is not consistent with your use of that in other names of items\n {\n\n <#\n where is the Comment Based Help?\n #>\n\n [CmdletBinding ()]\n Param\n (\n [Parameter (\n Position = 0,\n # the following are switches that default to "$False"\n # that means there is no need to add "= $True"\n # the simple presense of the attribute flips it to "$True"\n Mandatory,\n ValueFromPipeline,\n # the following requres the pipeline object contain a property named ".FullName"\n # is that always going to be the case?\n # if not, then the "ValueFromPipeline" above will handle bare values\n ValueFromPipelineByPropertyName\n )]\n [string]\n $FullName,\n\n [Parameter (\n Position = 1,\n # making this mandatory makes little sense when a default is supplied\n #Mandatory,\n # does it make any sense to use the following attribute?\n ValueFromPipelineByPropertyName\n )]\n # don't use "First" and "Last" for _position_ info when the same words are used for the name parts\n # it's needlessly confusing\n #[ValidateSet ('First', 'Last')]\n [ValidateSet ('Start', 'End')]\n [string]\n $LastNamePosition = 'Start'\n )\n\n begin {}\n\n process\n {\n # properly supporting the pipeline requires one to have a "process" block.\n # otherwise all code is run in a virtual "end" block ... and that does not correctly support pipeline input\n\n # mixing camelCase and PascalCase for variable names is confusing [*grin*] \n # the recommended style for PoSh is PascalCase\n #$usernameComponents = $FullName.ToLower().Split(" ")\n # the 2nd sample name has a trailing space\n # the ".Trim()" removes that\n # good practice in PoSh is to avoid using double quotes since that can trigger unwanted expansion of $Vars\n $UserNameComponents = $FullName.Trim().ToLower().Split(' ')\n\n switch ($LastNamePosition)\n {\n 'Start' {\n # "index -1, index 0" for the $UserNameComponents skips any middle name or initial\n $UserName = '{0}.{1}' -f $UserNameComponents[-1], $UserNameComponents[0]\n }\n 'End' {\n $UserName = '{0}.{1}' -f $UserNameComponents[0], $UserNameComponents[-1]\n }\n # this is a binary choice, so the "default" is not needed\n #Default { $firstName = $UserNameComponents.Length -1; $lastName = 0 }\n }\n\n # there is no need to assign the output to anything\n # whatever is left unassigned will be sent out\n # there is also no need for "return"\n # that is disrecommeded since it gives the false impression that ONLY the item to its right will be returned\n # the "-replace" operator can be chained. so can the ".Replace()" method\n # that allows us to skip breaking things into an array of chars\n $UserName -replace \n 'č', 'c' -replace\n 'ć', 'c' -replace\n 'đ', 'dj' -replace\n 'š', 's' -replace\n 'ž', 'z'\n\n } # end >>> process\n\n end {}\n\n } # end >>> function Get-UserNameFromFullName\n</code></pre>\n<p>run with all names, no parameters, and using the pipeline ...</p>\n<pre><code>$InStuff |\n Get-UserNameFromFullName\n</code></pre>\n<p>output ...</p>\n<pre><code>djordjevic.cedomir\nzoran.jankov\ngradimir.stojic\nzeljko.vucicevic\nboskic.magda\n</code></pre>\n<p>run with all parameters listed and only one input value ...</p>\n<pre><code>Get-UserNameFromFullName -FullName $InStuff[-1] -LastNamePosition End\n</code></pre>\n<p>output = <code>magda.boskic</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-08T15:15:25.513",
"Id": "484865",
"Score": "0",
"body": "Thank you for your great advice! I have created a new version of my function based on your suggestions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-09T05:27:31.157",
"Id": "484888",
"Score": "1",
"body": "@ZoranJankov - you are most welcome! glad to have helped somewhat ... [*grin*]"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T05:16:28.333",
"Id": "247503",
"ParentId": "247456",
"Score": "3"
}
},
{
"body": "<p>I have created a new version of my function based on <a href=\"https://codereview.stackexchange.com/users/182122/lee-dailey\">Lee_Dailey</a> suggestions.</p>\n<pre><code>function Get-UserNameFromFullName\n{\n [CmdletBinding()]\n param\n (\n [Parameter(Position = 0, Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]\n [string]\n $FullName,\n\n [Parameter(Position = 1, ValueFromPipelineByPropertyName)]\n [switch]\n $ReverseNamePositions = $false\n )\n \n process\n { \n if ($ReverseNamePositions)\n {\n $Front = -1\n $End = 0\n }\n else\n {\n $Front = 0\n $End = -1\n }\n\n $UserNameComponents = $FullName.Trim().ToLower().Split(' ')\n\n $UserName = '{0}.{1}' -f $UserNameComponents[$Front], $UserNameComponents[$End]\n\n $UserName -replace 'č', 'c' `\n -replace 'č', 'c' `\n -replace 'ć', 'c' `\n -replace 'đ', 'dj' `\n -replace 'š', 's' `\n -replace 'ž', 'z'\n }\n}\n</code></pre>\n<p>If someone thinks that the function is lacking something feel free to tell me. I would be grateful.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-09T05:30:59.860",
"Id": "484889",
"Score": "1",
"body": "backticks are ... problematic ... in that they are easy to overlook. that means you can do some editing, leave one behind, and then spend HOURS tracking down the reason for your code misbehaving. [*grin*] try to avoid the backtick whenever you can. that is why i used that odd-looking structure in my version. ///// otherwise, very neat code! [*grin*]"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-08T15:20:25.413",
"Id": "247655",
"ParentId": "247456",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "247503",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T21:15:19.423",
"Id": "247456",
"Score": "5",
"Tags": [
"powershell"
],
"Title": "Get username from full name - PowerShell function"
}
|
247456
|
<p>I wanted to make a script that would parse a main file (with <code>int main()</code>) look in its <code>#include "..."</code> local headers, and if they were not in the current dir, then find those headers, then its source files and provided them as implementation in <code>g++</code>. In other words, I wanted to have a script-helper, that would watch for dependencies. I think I made it, <code>perl</code> was used. I would like to get some reviews:</p>
<pre><code> #!/usr/bin/perl
use autodie;
use Cwd qw[getcwd abs_path];
use Getopt::Long qw[GetOptions];
use File::Find qw[find];
#global arrays
@src; #source files -> .cpp
@hed; #headers files -> .hpp
@dep; #dependencies -> .hpp + .cpp
$command;
GetOptions(
"s" => <span class="math-container">\$opt_s, #headers the same as source files
"h" => \$</span>opt_h, #help message
"o=s" => <span class="math-container">\$opt_o, #output filename
"i=s" => \%opt_i, #dependencies
"debug" => \$</span>opt_debug #output the command
) or die "command options\n";
if($opt_h){
print "usage: exe [-h][--debug][-s][-o output_file][-i dir=directory target=source]... sources...\n";
exit 1;
}
die "no args" if !($out=$ARGV[0]);
$out = $opt_o if $opt_o;
#-------------------------------------------------
sub diff {
my $file = shift;
$file = "$file.cpp";
open MAIN, $file;
opendir CWD, getcwd;
my @file_dep = map { /#include "([^"]+)"/ ? abs_path($1) : () } <MAIN>;
my %local = map { abs_path($_) => 1 } grep { !/^\./ } readdir CWD;
#headers found in the main file
my @tmp;
for(@file_dep){
push @tmp, $_ if ! $local{$_};
}
@tmp = map {/.+\/(.+)/} @tmp;
#finding absolute path for those files
my @ret;
for my $i (@tmp){
find( sub {
return unless -f;
return unless /$i/;
push @ret, $File::Find::name;
}, '/home/shepherd/Desktop');
}
@ret = map { "$_.cpp" } map {/(.+)\./} @ret;
return \@ret;
}
sub dependencies{
my $dir=shift; my $target=shift;
my @ar, my %local;
#get full names of target files
find( sub {
return unless -f;
push @ar, $File::Find::name;
}, $dir);
%local = map { $_ => 1 } @ar;
#and compare them againts the file from MAIN
for(@{diff($target)}){
push @dep, $_ if $local{$_};
}
}
sub debug{
print "final output:\n$command\n\nDependencies:\n";
print "$_\n" for @dep;
exit 1;
}
#------------------------------------------------------
#providing source and headers
if($opt_s){
@src = map { "$_.cpp" } @ARGV;
@hed = map { !/$out/ and "$_.hpp" } @ARGV;
} else {
@src = map { !/_h/ and "$_.cpp"} @ARGV;
@hed = map { /_h/ and s/^(.+)_.+/$1/ and "$_.hpp" } @ARGV;
}
if(%opt_i){
my @dirs; my @targets;
for(keys %opt_i){
push @dirs, $opt_i{$_} if $_ eq "dir";
push @targets, $opt_i{$_} if $_ eq "target";
}
if(@dirs!=@targets){
print "you have to specify both target and directory. Not all targets have their directories\n";
exit -1;
}
my %h;
@h{@dirs} = @targets;
dependencies($_, $h{$_}) for keys %h;
$command = "g++ ";
$command .= "-I $_ " for keys %h;
$command .= "-o $out.out @hed @dep @src";
debug if $opt_debug;
system $command;
exec "./$out.out";
} else {
$command = "g++ -o $out.out @hed @src";
debug() if $opt_debug;
system $command;
exec "./$out.out";
}
</code></pre>
<p>Now an example:</p>
<pre><code>$pwd
/home/user/Desktop/bin/2
$ls
main.cpp student2.cpp student2.hpp
</code></pre>
<p>Student2.cpp has some dependencies (it uses struct defined in <code>student.cpp</code> and a function defined in <code>grade.cpp</code>), with the script you can see what would it give you: (script is in <code>/usr/local/bin/exe</code>)</p>
<pre><code>$exe -h
usage: exe [-h][--debug][-s][-o output_file][-i dir=directory target=source]... sources...
$exe --debug -i target=student2 -i dir=/home/user/Desktop/bin/1 main student2
final output:
g++ -I /home/user/Desktop/bin/1 -o main.out /home/user/Desktop/bin/1/grade.cpp /home/user/Desktop/bin/1/student.cpp main.cpp student2.cpp
Dependencies:
/home/user/Desktop/bin/1/grade.cpp
/home/user/Desktop/bin/1/student.cpp
</code></pre>
<p>As you can see, the script found a dependencies in <code>studen2.cpp</code> which were in another directory and included them to final command. You just have to specify the source files without extension (just file base names). In conclusion I just for each target file (which could have dependencies in its <code>#include "dependecy.hpp"</code> source file), I provide a directory where the dependency (dependency=header+source[implementation]) is, that's it. All the rest does the script</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T04:11:11.793",
"Id": "484342",
"Score": "1",
"body": "\"Could it always work\" that's a dangerous question, but I assume you've tested it at least on your own system and that it works there?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T08:41:15.897",
"Id": "484358",
"Score": "2",
"body": "Please provide a description of how the different command line options should work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T08:51:19.230",
"Id": "484359",
"Score": "0",
"body": "`a.pl -i path/to/dependencies/cpp main` does the program assume that the `main.cpp` and `a.pl` must be in the same directory? I.e., is it possible to call the program like this: `a.pl -i path/to/dependencies/cpp path2/main` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T09:42:24.543",
"Id": "484360",
"Score": "0",
"body": "Note that if you have `#include \"dir1/bar.hpp\"` in `main.cpp` the location of the file `bar.hpp` does not have to be in a subdirectory `dir1` in the directory of `main.cpp`. For example it can be in a directory `/path2/dir1/bar.hpp` (provided you compile `main.cpp` with `g++ -I/path2 ... main.cpp`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T09:44:01.090",
"Id": "484361",
"Score": "3",
"body": "Also specify why you did not use `cmake` or `make` instead of rolling your own solution"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T13:18:15.520",
"Id": "484379",
"Score": "0",
"body": "@cmake or make does not have the capability of regular language - things like array, hashes and regexes come in hand in my solution. I have added help message althought not that verbose. By adding feature of `-i target/dir` makes it more general to specify for any source/header, which has dependecy in it. You can try it now"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T16:23:42.637",
"Id": "484396",
"Score": "1",
"body": "The modern compilers have a capability to generate dependencies for you. I would rather trust this job to the compiler."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T17:15:36.217",
"Id": "484398",
"Score": "0",
"body": "@vnp well some could but I do not know about one. It just get annoyed to always type the directory where the implementation is defined (If it wasn't in my current one). So i made a script where I can just pass a `target` from which the script would find those dependencies and include them to final command. It is not that \"advanced\", but does the job I want -> I can just simply directory to look at for any target files (that needs dependency - extern implementation), that's all it does"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T18:21:57.927",
"Id": "484404",
"Score": "0",
"body": "I still don't understand why you aren't using `cmake` or `make`. Perhaps you can clean up the question to make it easier to comprehend your end goal."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T22:37:27.723",
"Id": "484430",
"Score": "0",
"body": "you can get the `make` tool to do some of this work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T23:29:57.017",
"Id": "484435",
"Score": "2",
"body": "`> g++ -MMD -MP -MF <FileName>.d <FileName>.cpp; cat <FileName>.d` Normally you do this by adding appropriate definitions to your make file."
}
] |
[
{
"body": "<p>It is not so easy to get a clear picture of what the program is doing\nand why it is doing what it is doing. I think adding more\ndocumentation and comments would help, and also trying to code in a\nway that is easy to read. That means using function and variable names\ncarefully to enhance readability. Avoid using compact/clever\nconstructs if they are not easy to read, instead prefer more verbose\ncode if it can improve readability and maintainability.</p>\n<p>It is not clear why you did not want to use <code>make</code> or <code>cmake</code> to\nhandle dependencies in a more efficient way.\nAnother issue is the purpose of the command line switches. It would\nhelp to provide more documentation and background for their usage.</p>\n<p>Automatic compilation of dependencies is\nusually done with <code>make</code> or <code>cmake</code>. But this requires you to write a\n<code>Makefile</code> or a <code>CMakeLists.txt</code> file that specify dependencies. Another\noption that avoids this is to use <code>g++ -MMD -MP -MF</code> as mentioned by\n@MartinYork in the comments. Also note that <code>make</code> and <code>cmake</code> has the\nadded benefit of only recompiling the source files that have changed\n(i.e. those that are newer than the target file). This can markedly\nspeed up compilation times for a large project. The Perl script on the\nother hand, will recompile\nevery dependency into a single object each time whether some of the\ndependencies has changed or not.</p>\n<p>On the other hand, an advantage of using the Perl script can be to avoid writing the\n<code>Makefile</code> (though I would recommend learning to write a <code>Makefile</code> or\na <code>CMakeLists.txt</code> as it is the common way of doing it).\nThe script also automatically runs the executable file after compilation, though it\ndoes not check if the compilation failed or not (if the compilation\nfails it does\nnot make sense to run the executable).\nAnother advantage can be that it does not generate multiple <code>.o</code> files\n(as <code>make</code> and <code>cmake</code> does to to enable recompilation only of changed files).</p>\n<p>The Perl script as you named <code>exe</code> (I will rename it to <code>exe.pl</code> for clarity) can\nbe used in many ways. From reading the source code, here is what I found:</p>\n<p>Firstly, it can be used to\ncompile specific files in the current directory (and then run the\ngenerated executable). For example:</p>\n<pre><code>$ exe.pl main student2\n</code></pre>\n<p>This will run <code>g++ -o main.out main.cpp student2.cpp</code>. The <code>-o</code> option\ncan be used to specify another name for the exe (but the suffix will\nalways be <code>.out</code>):</p>\n<pre><code>$ exe.pl -o prog main student2\n</code></pre>\n<p>runs <code>g++ -o prog.out main.cpp student2.cpp</code>. The <code>-s</code> option can be\nused to add headers to the compilation (though I could not see why this\nis useful, as headers are commonly included from within a <code>.cpp</code> file,\nand therefore should be included automatically by the <code>g++</code> preprocessor):</p>\n<pre><code>$ exe.pl -s main student2\n</code></pre>\n<p>runs <code>g++ -o main.exe main.cpp student2.cpp student2.hpp</code>. Note that <code>main.hpp</code> is not added. The script considers\nthe first filename on the command line (here <code>main</code>) as the "main"\nscript, and the <code>-s</code> option will not add a header file for the main\nscript. (Please consider clarify why this is done!)\nHeaders can still be added without using the <code>-s</code>\noption by supplying names that matches "_h":</p>\n<pre><code>$ exe.pl main student2 student2_h\n</code></pre>\n<p>runs <code>g++ -o main.exe main.cpp student2.cpp student2.hpp</code>. Next, the\nthe <code>-i</code> switch is used to handle dependencies. A dependency is a <code>.cpp</code> file\nin another directory, let's call it DD, from the main directory, DM, where the script is\nrun from. If the dependency includes header files, the\nscript checks if the header files are located in DM, if so they are\nexcluded from the later compilation (please consider clarify why this is\ndone).</p>\n<p>For example, consider DM=<code>/home/user/Desktop/bin/2</code>. We see that DM is located in a\nparent directory DT=<code>/home/user/Desktop</code> which the script will use as the\ntop of the source tree. Then if for example the dependency directory\nis DD=<code>/home/user/Desktop/bin/1</code>\nand the dependency file is <code>student.cpp</code> which contains an include\nstatement <code>#include "grade.hpp"</code>, the script first checks if <code>grade.hpp</code>\nalready exists in DM. If it does, it is excluded from the later <code>g++</code>\ncompilation command (please consider explaining why it is done). Next,\nthe script tries to find\n<code>student.cpp</code> in DT or any of it sub directories recursivly using\n<code>File:Find</code>. If it finds the file (or more than one file) and it turns\nout that the file is\nin DD (and not some other directory in DT), it is assumed that there\nalso exists a <code>.cpp</code> file with the same\nname in DD and the absolute path of this <code>.cpp</code> file is included in the\nlater <code>g++</code> compilation command. Also, the absolute path of DD is added\nas an include search path (<code>-I</code> option) to the <code>g++</code> command.</p>\n<p>I would recommend that the motivation behind the above logic (which is\nnot at all clear to me) be explained carefully in the source\ncode as comments.</p>\n<p>To summarize, the above example corresponds to the following\ncommand line:</p>\n<pre><code>$ exe.pl -i target=student -i dir=/home/user/Desktop/bin/1 main student2\n</code></pre>\n<p>and the script will then produce the following <code>g++</code> command:</p>\n<p><code>g++ -I /home/user/Desktop/bin/1 -o main.exe /home/user/Desktop/bin/1/student.cpp main.cpp student2.cpp</code></p>\n<h1>Logical issues</h1>\n<h2>The -i option does not work with more than one pair of (target, dir)</h2>\n<p>Currently, the <code>-i</code> option does not work for more than one target. For example,\nfor the command line:</p>\n<pre><code>$ exe.pl -i target=student2 -i dir=/home/user/Desktop/bin/1 -i target=student3 -i dir=/home/user/Desktop/bin/3\n</code></pre>\n<p><code>GetOptions()</code> will return for the hash <code>%opt_i</code> corresponding to\nthe input parameters <code>"i=s" => \\%opt_i</code> the following hash</p>\n<pre><code>%opt_i = (target => "student3", dir => "/home/user/Desktop/bin/3")\n</code></pre>\n<p>Notice that the first target <code>student2</code> is missing, this is because\nboth targets use the same hash key <code>target</code>. To fix this, you can try use\narrays instead of hashes as parameters to <code>GetOptions()</code>. For example:</p>\n<pre><code>"target=s" => \\@opt_t,\n"dir=s" => \\@opt_d,\n</code></pre>\n<h2>Dependencies in sub directories are not checked for</h2>\n<p>As mentioned above, the code tries to exclude dependencies that are\npresent in the main directory. But if a dependency is in a sub\ndirectory of that directory it will not find it. This is due to the\nusage of <code>readdir()</code> :</p>\n<pre><code>my %local = map { abs_path($_) => 1 } grep { !/^\\./ } readdir CWD;\n</code></pre>\n<p>Here, <code>readdir()</code> will only return the files in <code>CWD</code>, not those in\nany sub directory below it.</p>\n<h2>Account for multiple versions of the same dependency file</h2>\n<p>Currently the code uses the file in the main directory if there are\nmultiple versions of the same file name.</p>\n<p>Let's say the dependency file <code>/home/user/Desktop/bin/1/student.hpp</code> contains:</p>\n<pre><code>#include "grade.hpp"\n</code></pre>\n<p>and there exists two versions of the corresponding <code>.cpp</code> file. One in the dependency\ndirectory <code>/home/user/Desktop/bin/1/</code></p>\n<pre><code>/home/user/Desktop/bin/1/grade.cpp\n</code></pre>\n<p>and one in the CWD (where the script is run from)</p>\n<pre><code>/home/user/Desktop/bin/2/grade.cpp\n</code></pre>\n<p>What is the correct file? The script should at least give a warning.</p>\n<h2>Not checking recursivly for dependencies</h2>\n<p>Let's say <code>student.hpp</code> has a <code>#include "grade.hpp"</code> and <code>grade.hpp</code> has an\ninclude <code>#include "calc.hpp"</code>. Then, it will not find and compile <code>calc.cpp</code>.</p>\n<h2>The <code>_h</code> command line trick does not work correctly</h2>\n<p>The following code is used to check for header files on the command\nline:</p>\n<pre><code>@hed = map { /_h/ and s/^(.+)_.+/$1/ and "$_.hpp" } @ARGV;\n</code></pre>\n<p>Notice that the first regex <code>/_h/</code> matches any file with a <code>_h</code>\nanywhere in the filename, for example <code>sah_handler</code>. I think you need\nto add an end-of-string anchor to the regex: <code>/_h$/</code>.</p>\n<h2>Matching of #include files name in a dependency file</h2>\n<p>The code uses</p>\n<pre><code>my @file_dep = map { /#include "([^"]+)"/ ? abs_path($1) : () } <MAIN>;\n</code></pre>\n<p>to extract the dependencies from a dependency file. Note that this\nrequires that there is no space between <code>#</code> and <code>include</code>. But the\nassumption is not correct, it is in fact allowed to have spaces there, for example</p>\n<pre><code># include "student.hpp"\n</code></pre>\n<p>is a legal C++ include statement.</p>\n<h1>Language related issues</h1>\n<h2>Use strict, warnings</h2>\n<p>It is recommended to include <code>use strict; use warnings</code> at the top of\nyour program. This will help you catch errors at an early stage.</p>\n<h2>Try to limit the use of global variables</h2>\n<p>Extensive use of global variables makes it harder to reason about a\nprogram. It is crucial that a program is easy to read (and understand)\nin order to maintain and extend it effectively (at a later point).\nIt also makes it easier to track down bugs.</p>\n<p>Note that if you add <code>use strict</code> at the top of the program, global\nvariable needs to be declared similar to lexical variables. You\ndeclare a global variable with <code>our</code>.</p>\n<h2>Old style open() and opendir()</h2>\n<p>Modern perl uses the three-argument form of <code>open</code> and avoids global\nbareword filehandle names. Instead use lexical filehandles. So instead\nof this:</p>\n<pre><code>open MAIN, $file;\n</code></pre>\n<p>do this (assuming no <code>autodie</code>):</p>\n<pre><code>open (my $MAIN, '<', $file) or die "could not open $file: $!";\n</code></pre>\n<p>See <a href=\"http://modernperlbooks.com/mt/2010/04/three-arg-open-migrating-to-modern-perl.html\" rel=\"nofollow noreferrer\">Three-arg\nopen()</a>\nfrom the book "Modern Perl" for more information.</p>\n<h2>Shebang</h2>\n<p>See <a href=\"https://www.cyberciti.biz/tips/finding-bash-perl-python-portably-using-env.html\" rel=\"nofollow noreferrer\">this</a> blog for more information.\nConsider replacing <code>#!/usr/bin/perl</code> with <code>#!/usr/bin/env perl</code>\nMost systems have <code>/usr/bin/env</code>. It will also allow your script to run if you e.g.have multiple <code>perls</code> on your system. For example if you are using <code>perlbrew</code>.</p>\n<h2>Clever use of map()</h2>\n<p>The code uses <code>map</code> to produce very concise code, but such\ncode can be difficult to understand and make it harder to maintain\nyour code in the future.</p>\n<p>Also note that returning false from the map {} code block like in</p>\n<pre><code>@src = map { !/_h/ and "$_.cpp"} @ARGV;\n</code></pre>\n<p>produces an empty string element in @src, if you want to not produce\nan element you must return an empty list <code>()</code> instead of false:</p>\n<pre><code>@src = map { !/_h/ ? "$_.cpp" : () } @ARGV;\n</code></pre>\n<h2>Use good descriptive names for the subs.</h2>\n<p>The sub <code>diff()</code> is supposed to find dependency files that are not\npresent in the current directory. But the name <code>diff()</code> does not\nclarify what the sub is doing. On the other hand, the following name might be too verbose:</p>\n<pre><code>find_abs_path_of_dep_files_that_does_not_exist_in_curdir()\n</code></pre>\n<p>but it is at least easier to understand.</p>\n<h2>Use positive return values with <code>exit</code></h2>\n<p>The exit code from a linux process is usually an integer between zero\n(indicating success) and 125, see <a href=\"https://unix.stackexchange.com/a/418802/45537\">this</a> answer for more information.</p>\n<h2>Check the return value of <code>system $command</code></h2>\n<p>You should check the return value from the <code>system()</code> call for\n<code>g++</code>. The compilation may fail, and then the exit code will be\nnonzero. In that case, there is no point in running the executable\nafter the compilation has finished.</p>\n<h2>Use <code>say</code> instead of <code>print</code></h2>\n<p>You can avoid typing a final newline character for print statements by\nusing <code>say</code> instead of <code>print</code>. The <code>say</code> function was introduced in\nperl 5.10, and is mad available by adding <code>use v5.10</code> or use <code>use feature qw(say)</code> to the top of your script.</p>\n<h1>Example code</h1>\n<p>Here is an example of how you can write the code, following some of\nthe principles I discussed above. I use an object oriented approach to\navoid passing too many variables around in the parameter lists of the\nsubs. It also avoids using global variables.</p>\n<pre><code>#! /usr/bin/env perl\n\npackage Main;\nuse feature qw(say);\nuse strict;\nuse warnings;\nuse Cwd qw(getcwd);\nuse File::Spec;\nuse Getopt::Long ();\nuse POSIX ();\n\n{ # <--- Introduce scope so lexical variables do not "leak" into the subs below..\n my $self = Main->new( rundir => getcwd() );\n $self->parse_command_line_options();\n $self->parse_command_line_arguments();\n $self->find_dependencies();\n $self->compile();\n $self->run();\n}\n\n# ---------------------------------------\n# Methods, alphabetically\n# ---------------------------------------\n\nsub check_run_cmd_result {\n my ( $self, $res ) = @_;\n\n my $signal = $res & 0x7F;\n if ( $res == -1 ) {\n die "Failed to execute command: $!";\n }\n elsif ( $signal ) {\n my $str;\n if ( $signal == POSIX::SIGINT ) {\n die "Aborted by user.";\n }\n else {\n die sprintf(\n "Command died with signal %d, %s coredump.",\n $signal, ( $res & 128 ) ? 'with' : 'without'\n );\n }\n }\n else {\n $res >>= 8;\n die "Compilation failed.\\n" if $res != 0;\n }\n}\n\nsub compile {\n my ( $self ) = @_;\n\n my @command = ('g++');\n push @command, ("-I", $_) for @{$self->{inc}};\n push @command, "-o", "$self->{out}.out";\n push @command, @{$self->{hed}}, @{$self->{deps}}, @{$self->{src}};\n $self->debug( "@command" ) if $self->{opt_debug};\n my $res = system @command;\n $self->check_run_cmd_result( $res );\n}\n\nsub debug{\n my ( $self, $cmd ) = @_;\n\n say "final output:\\n$cmd\\n\\nDependencies:";\n say for @{$self->{dep}};\n exit 1;\n}\n\nsub find_dependency {\n my ( $self, $target, $dir ) = @_;\n\n $target .= '.cpp';\n my $fn = File::Spec->catfile($dir, $target);\n open ( my $fh, '<', $fn ) or die "Could not open file '$fn': $!";\n my @include_args = map { /^#\\s*include\\s*"([^"]+)"/ ? $1 : () } <$fh>;\n close $fh;\n my @deps;\n for (@include_args) {\n my $fn = File::Spec->catfile( $dir, $_ );\n # TODO: In your program you checked if file also existed in\n # $self->{rundir}, and excluded it if so. Do you really need to check that?\n if (-e $fn) { # the file exists in target dir\n my ($temp_fn, $ext) = remove_file_extension( $fn );\n if (defined $ext) {\n check_valid_header_file_extension( $ext, $fn );\n push @deps, "$temp_fn.cpp";\n # TODO: Here you could call $self->find_dependency() recursively\n # on basename($temp_fn)\n }\n }\n }\n if (@deps) {\n push @{$self->{deps}}, @deps;\n push @{$self->{inc}}, $dir;\n }\n}\n\nsub find_dependencies {\n my ( $self ) = @_;\n\n $self->{deps} = [];\n $self->{inc} = [];\n my $targets = $self->{opt_t};\n my $dirs = $self->{opt_d};\n for my $i (0..$#$targets) {\n my $target = $targets->[$i];\n my $dir = $dirs->[$i];\n $self->find_dependency( $target, $dir );\n }\n}\n\nsub parse_command_line_arguments {\n my ( $self ) = @_;\n\n check_that_name_does_not_contain_suffix($_) for @ARGV;\n # TODO: Describe the purpose of -s option here!!\n if($self->{opt_s}){\n $self->{src} = [ map { "$_.cpp" } @ARGV ];\n # NOTE: exclude header file for main program name ($self->{out})\n # So if main program name is "main", we include main.cpp, but not main.hpp\n # TODO: describe why it is excluded\n $self->{hed} = [ map { !/^$self->{out}$/ ? "$_.hpp" : () } @ARGV];\n }\n else {\n # TODO: Describe what is the purpose of "_h" here!!\n $self->{src} = [ map { !/_h$/ ? "$_.cpp" : () } @ARGV ];\n $self->{hed} = [ map { /^(.+)_h$/ ? "$1.hpp" : () } @ARGV ];\n }\n}\n\nsub parse_command_line_options {\n my ( $self ) = @_;\n\n Getopt::Long::GetOptions(\n "s" => <span class=\"math-container\">\\$self->{opt_s}, # headers the same as source files\n \"h\" => \\$</span>self->{opt_h}, # help message\n "o=s" => <span class=\"math-container\">\\$self->{opt_o}, # output filename\n \"target=s\" => \\@{$self->{opt_t}}, # target name for dependency\n \"dir=s\" => \\@{$self->{opt_d}}, # target dir for dependency\n \"debug\" => \\$</span>self->{opt_debug} # output the generated command\n ) or die "Failed to parse options\\n";\n\n usage() if $self->{opt_h};\n usage("Bad arguments") if @ARGV==0;\n $self->{out} = $self->{opt_o} // $ARGV[0];\n check_that_name_does_not_contain_suffix( $self->{out} );\n $self->validate_target_and_dir_arrays();\n}\n\nsub run {\n my ( $self ) = @_;\n\n exec "./$self->{out}.out";\n}\n\nsub validate_target_and_dir_arrays {\n my ( $self ) = @_;\n\n my $target_len = scalar @{$self->{opt_t}};\n my $dir_len = scalar @{$self->{opt_d}};\n\n die "Number of targets is different from number of target dirs!\\n"\n if $target_len != $dir_len;\n $_ = make_include_dir_name_absolute($_) for @{$self->{opt_d}};\n}\n\n#-----------------------------------------------\n# Helper routines not dependent on $self\n#-----------------------------------------------\n\nsub check_that_name_does_not_contain_suffix {\n my ($name) = @_;\n\n if ($name =~ /\\.(?:hpp|cpp)$/ ) {\n die "Argument $name not accepted: Arguments should be without extension\\n";\n }\n}\n\nsub check_valid_header_file_extension {\n my ( $ext, $fn ) = @_;\n\n warn "Unknown header file extension '$ext' for file '$fn'"\n if $ext !~ /^(?:hpp|h)/;\n}\n\nsub make_include_dir_name_absolute {\n my ($path ) = @_;\n\n if ( !File::Spec->file_name_is_absolute( $path )) {\n warn "Warning: Converting include path '$path' to absolute path: \\n";\n $path = Cwd::abs_path( $path );\n warn " $path\\n";\n }\n return $path;\n}\n\nsub new {\n my ( $class, %args ) = @_;\n\n return bless \\%args, $class;\n}\n\n\nsub remove_file_extension {\n my ( $fn ) = @_;\n\n if ( $fn =~ s/\\.([^.]*)$//) {\n return ($fn, $1);\n }\n else {\n warn "Missing file extension for file '$fn'";\n return ($fn, undef);\n }\n}\n\nsub usage {\n say $_[0] if defined $_[0];\n say "usage: exe.pl [-h][--debug][-s][-o output_file][[-dir=directory -target=source]] <main source> <other sources>...";\n # TODO: Please add more explanation of the options here!!\n exit 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-10T21:16:11.100",
"Id": "485066",
"Score": "0",
"body": "Very thanks for reply. There are many idioms I did not even know perl is capable of. Helped a lot."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-10T21:25:09.477",
"Id": "485070",
"Score": "0",
"body": "I think this is that kind of scripts, where perl is still beter then python, for these kind of tasks (finding files in system, calling system commands, regexes, etc.)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-10T18:39:04.597",
"Id": "247727",
"ParentId": "247459",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "247727",
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-03T22:43:20.643",
"Id": "247459",
"Score": "9",
"Tags": [
"c++",
"perl",
"compiler"
],
"Title": "Is possible to use script for dependencies in c++?"
}
|
247459
|
<p>I write code in a Test-Driven way and I often build my functions starting with tests for the easy edge cases.</p>
<p>For example, given a flat array of <code>Item</code>s that have a <code>category</code> property, return an array of <code>Group</code>s, each built with all the items for one of the categories in the input.</p>
<p>One edge case I find helpful to test first is the behavior when the items are all from the same category. This gives me a chance to see how the <code>Group</code> should look like.</p>
<p>In this case there are (at least) two approaches one can take: two granular tests vs. a single one.</p>
<h3>Granular</h3>
<p>One could write two granular tests for these conditions:</p>
<ol>
<li>Given an array with items all from the same category, the output should be an array with a single group</li>
<li>A group should contain all the items for its category and only those</li>
</ol>
<p>In Swift, these tests might look something like this</p>
<pre class="lang-swift prettyprint-override"><code>func testGroupingArrayOfSameCategoryReturnsOneGroup() {
let items = [
Item(name: "a", category: .foo),
Item(name: "b", category: .foo),
Item(name: "c", category: .foo),
]
let groups = groupByCategory(items)
XCTAssertEqual(groups.count, 1)
}
func testGroupingBuildsGroupWithAllItemsForCategory() throws {
let items = [
Item(name: "a", category: .foo),
Item(name: "b", category: .foo),
Item(name: "c", category: .foo),
]
let groups = groupByCategory(items)
let group = try XCTUnwrap(groups.first)
XCTAssertEqual(group.category, .foo)
XCTAssertEqual(group.items.count, 3)
XCTAssertEqual(group.items[0].name, "a")
XCTAssertEqual(group.items[1].name, "b")
XCTAssertEqual(group.items[2].name, "c")
}
</code></pre>
<p>I like how the two behaviors of having a 1:1 match with groups and categories and how the groups are built are separated, but I see a lot of duplication between those tests.</p>
<h3>Aggregated</h3>
<p>A different approach would be to check both facets of the behavior in the same test.</p>
<pre class="lang-swift prettyprint-override"><code>func testGroupingArrayOfSameCategoryReturnsOneGroupWithAllItemsForCategory() {
let items = [
Item(name: "a", category: .foo),
Item(name: "b", category: .foo),
Item(name: "c", category: .foo),
]
let groups = groupByCategory(items)
XCTAssertEqual(groups.count, 1)
let group = try XCTUnwrap(groups.first)
XCTAssertEqual(group.category, .foo)
XCTAssertEqual(group.items.count, 3)
XCTAssertEqual(group.items[0].name, "a")
XCTAssertEqual(group.items[1].name, "b")
XCTAssertEqual(group.items[2].name, "c")
}
</code></pre>
<p>Which do you think is clearer and why?</p>
|
[] |
[
{
"body": "<p>I prefer the second option: using a test for both facets of the behavior.</p>\n<p>While it has a lot of assertions, I feel it covers the behavior well in one go, removing duplication.</p>\n<p>From a pure code economy point of view, we achieve the same thoroughness as the two tests scenario with just one extra line of code.</p>\n<p>Moreover, in the two tests example, the first test would pass regardless of how the output is built, as long as it contains only one element. Yes, the second test is there to make sure the <code>Group</code> is built properly, but I'm somehow uncomfortable with how close to a false positive the test that only checks the array count is.</p>\n<p>If the second tests was to be removed, code coverage tools wouldn't register a change in coverage, but the thoroughness of what is checked would decrease.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T00:23:13.527",
"Id": "247461",
"ParentId": "247460",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T00:20:37.583",
"Id": "247460",
"Score": "3",
"Tags": [
"unit-testing",
"swift"
],
"Title": "Granular vs a aggregated tests when dealing with arrays"
}
|
247460
|
<p>I have two Python lists, <code>label</code> and <code>presence</code>. I want to do cross-tabulation <em>and</em> get the count for each block out of four, such as A, B, C, and D in the below code.</p>
<ul>
<li>Both the lists have values <code>True</code> and <code>False</code>.</li>
<li>I have tried <a href="https://en.wikipedia.org/wiki/Pandas_%28software%29" rel="nofollow noreferrer">Pandas'</a> crosstab function. However, it's slower than my code which is below.</li>
<li>One problem with my code is it's not vectorized and is using a <em>for</em> loop which slows things down.</li>
</ul>
<p><strong>Could the below function in Python be made any faster?</strong></p>
<pre><code>def cross_tab(label,presence):
A_token=0
B_token=0
C_token=0
D_token=0
for i,j in zip(list(label),list(presence)):
if i==True and j==True:
A_token+=1
elif i==False and j==False:
D_token+=1
elif i==True and j==False:
C_token+=1
elif i==False and j==True:
B_token+=1
return A_token,B_token,C_token,D_token
</code></pre>
<p>Some sample data and example input and output.</p>
<pre><code>##input
label=[True,True,False,False,False,False,True,False,False,True,True,True,True,False]
presence=[True,False,False,True,False,False,True,True,False,True,False,True,False,False]
##processing
A,B,C,D=cross_tab(label,presence)
print('A:',A,'B:',B,'C:',C,'D:',D)
##Output
A: 4 B: 2 C: 3 D: 5
</code></pre>
<p><strong>Edit</strong>: Answer provided by Maarten Fabre below is working perfectly. To anyone who will stumble here in future, the logic flow is as follows.</p>
<p><strong>Goal: find a way for vectorization: Below are the solution steps</strong></p>
<ol>
<li>Analyze and find unique value at each evaluation. This will help save logical output in single array.</li>
<li>By multiplying 2 with any given array and adding resultant array with other array we can get results in single array with unique coded value for each logic.</li>
<li>Get count of the unique element in array and fetch values.</li>
<li>Since calculation can be done in arrays without loop, convert list into np array to allow vectorized implementation.</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T10:06:22.213",
"Id": "484609",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T10:11:33.383",
"Id": "484611",
"Score": "0",
"body": "I haven't copied any code from answer. You can check question edit history and answer for that. I did not say anywhere in the question that i am using numpy array, but it was suggested by the answerer to use numpy for performance. Let me know if am missing anything."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T11:04:04.783",
"Id": "484617",
"Score": "0",
"body": "It wasn't an attack, it was a pre-emptive comment. Please don't take it personally."
}
] |
[
{
"body": "<h1>Algorithm</h1>\n<p>If you look at your code, and follow the <code>if-elif</code> part, you see that there are 4 combinations of <code>i</code> and <code>j</code></p>\n<blockquote>\n<pre><code>i j : result\nTrue, True : A\nFalse, True : B\nTrue, False : C\nFalse, False : D\n</code></pre>\n</blockquote>\n<p>If you use the tuple <code>(i, j)</code> as key, you can use a dict lookup</p>\n<pre><code>{\n (True, True): "A",\n (False, True): "B",\n (True, False): "C",\n (False, False): "D",\n}\n</code></pre>\n<p>Or simpler:</p>\n<pre><code>{\n (True, True): 3,\n (False, True): 1,\n (True, False): 2,\n (False, False): 0,\n}\n</code></pre>\n<p>The choice of numbers is deliberate, since when you use <code>True</code> as <code>1</code> and <code>False</code> as <code>0</code>, you can do</p>\n<pre><code>def crosstab2(label, presence):\n for i, j in zip(label, presence):\n yield i * 2 + j\n\nc = collections.Counter(crosstab2(label, presence))\nprint('A:',c[3],'B:',c[1],'C:',c[2],'D:',c[0])\n</code></pre>\n<p>This is not faster than your original solution, but this is something you can vectorize</p>\n<pre><code>label = np.array([True, True, False, False,False, False,True, False, False, True, True, True, True, False])\npresence = np.array([True, False, False, True, False, False, True, True, False, True, False, True, False, False])\nc = collections.Counter(label * 2 + presence)\nprint('A:',c[3],'B:',c[1],'C:',c[2],'D:',c[0])\n</code></pre>\n<p>Which is significantly faster, even if you account for the few seconds of overhead for the creation of the numpy arrays</p>\n<h1>Formatting</h1>\n<p>Try to follow pep8.</p>\n<ul>\n<li>spaces around operators (<code>=</code>, <code>+</code>, ...)</li>\n<li>spaces after a <code>,</code></li>\n</ul>\n<h1>naming</h1>\n<p>I try to give collections of elements a plural name. In this case, I would use <code>labels</code>., so if you ever need to iterate over them, you can do <code>for label in labels</code>, which is a lot more clear than <code>for i in label:</code></p>\n<h1><code>list</code></h1>\n<p>The extra call to <code>list</code> in <code> zip(list(label),list(presence))</code> is not necessary. <code>zip</code> takes any iterable, and doesn't modify it in place.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T11:40:30.550",
"Id": "484368",
"Score": "0",
"body": "Thank you for your help! **It is faster solution indeed.** One thing though, i am trying to understand your solution from data structure algorithm perspective. Can you suggest how you broke the task and deviced the solution in that regard? I will really appreciate your guidance and suggestion which can help me develop that thinking."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T11:56:24.930",
"Id": "484371",
"Score": "1",
"body": "is this explanation clearer?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T13:04:17.297",
"Id": "484377",
"Score": "0",
"body": "I summarize logic below. Let me know if it's correct, I will add in the question as edit. Goal: find a way for vectorization:\nstep1: Analyze and find unique value at each evaluation. This will help save logical output in single array.\nstep2: By multiplying 2 with any given array and adding resultant array with other array we can get results in single array with unique coded value for each logic.\nStep3: Get count of the unique element in array and fetch values.\nStep4: since calculaton can be done in arrays without loop, convert list into np array to allow vectorized implementation."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T08:54:13.637",
"Id": "247466",
"ParentId": "247462",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "247466",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T05:35:31.030",
"Id": "247462",
"Score": "4",
"Tags": [
"python",
"performance",
"python-3.x",
"vectorization"
],
"Title": "Vectorized crosstabulation in Python for two arrays with two categories each"
}
|
247462
|
<p>I've created the following <a href="https://data.stackexchange.com/scifi/query/1271796/reputation-averages?ExcludeNewUsers=0" rel="nofollow noreferrer">SEDE query</a> which calculates the reputation averages of users on a particular site. It also optionally excludes "new" users (users with rep of 1 or 101 so note 100% accurate).</p>
<pre><code>DECLARE @exclude_new_users INT
SET @exclude_new_users = ##ExcludeNewUsers:int?0##
DECLARE @excluded_rep_table TABLE (Rep INT)
INSERT INTO @excluded_rep_table VALUES (1),(101)
DECLARE @rep_table TABLE (Reputation INT)
INSERT INTO @rep_table (Reputation)
SELECT Reputation
FROM USERS
WHERE Reputation <>
CASE WHEN @exclude_new_users = 0
THEN -1
ELSE (SELECT IIF (EXISTS (SELECT Rep FROM @excluded_rep_table WHERE Rep = Reputation), Reputation, -1))
END
SELECT COUNT(*) AS [Total Users],
MIN(Reputation) AS [Minimum],
MAX(Reputation) AS [Maximum],
SUM(Reputation) / COUNT(*) AS [Mean],
(
SELECT TOP 1 Reputation
FROM @rep_table
GROUP BY Reputation
ORDER BY COUNT(Reputation) DESC
) AS [Mode],
(
SELECT
(
(
SELECT MAX(Reputation)
FROM
(
SELECT TOP 50 PERCENT Reputation
FROM @rep_table
ORDER BY Reputation
) AS [Bottom Half]
)
+
(
SELECT MIN(Reputation)
FROM
(
SELECT TOP 50 PERCENT Reputation
FROM @rep_table
ORDER BY Reputation DESC
) AS [Top Half]
)
) / 2
) AS [Median],
STDEVP(Reputation) AS [Standard Deviation]
FROM @rep_table
</code></pre>
<p>I'm quite the SQL novice and mainly did this for some practice so I'm really after general feedback: ways to improve/optimise the code but also to improve the layout, it looks ugly and I can't imagine it fits with style guidelines.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T07:11:19.857",
"Id": "484452",
"Score": "1",
"body": "Looks OK, the only thing is that there are faster methods to calculate Median: https://stackoverflow.com/a/1567946/861716"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T08:55:27.787",
"Id": "484472",
"Score": "0",
"body": "@GertArnold Great tip, [done that](https://data.stackexchange.com/scifi/query/1272492/reputation-averages?ExcludeNewUsers=0) and it's certainly neater."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T09:40:05.023",
"Id": "247468",
"Score": "3",
"Tags": [
"t-sql",
"stackexchange"
],
"Title": "SEDE query calculating user reputation averages"
}
|
247468
|
<p>I have a numpy array called <code>contour</code> of <span class="math-container">\$N\$</span> coordinates <code>(x,y)</code> of dimension <code>(N, 2)</code>.</p>
<p>For each point in this table, I would like to create a square centered at that point and perform a test on the square formed.</p>
<p>My current code is slow, probably due to the <code>for</code> loop. Can the execution speed be improved?</p>
<p>My code:</p>
<pre><code>def neighbour(point , mask , n ): # Create the square around this point and count the number of neighbors.
mask = mask[point[0] - int(n/2) : point[0] + int(n/2) + 1,point[1] - int(n/2):point[1] + int(n/2) + 1]
return n**2 - np.count_nonzero(mask)
def max_neighbour(contour , mask=maske , n=ne): # Find the point with as many neighbors as possible
t = np.zeros(len(contour)) # contour is the numpy array of dimension (2,N)
for i in range(len(contour)):
t[i] = neighbour(contour[i],mask,n)
return contour[np.argmax(t)] # t contains the list of neighbors for each contour point.
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T01:46:58.720",
"Id": "484701",
"Score": "0",
"body": "Take a look at `scipy.spatial.cKDTree`. `query_ball_tree()` with `r=n` and `p=1` should return a list of points with a manhatten distance <= n."
}
] |
[
{
"body": "<p>Okay, so there are a lot of problems here. I think the best way to address them is in stages. I want to show you how to go through your own code critically and address problems in it as you write.</p>\n<p>Before I begin, for the benefit of someone who will review your code, it is helpful to include all the imports you used so that the person doing the review can just copy your code into their environment and run it if they need to.</p>\n<p>So a good first inclusion would be:</p>\n<p><code>import numpy as np</code></p>\n<p>My first stylistic point is that you really should conform to PEP8, it creates a standard that all Python programmers should follow and while some of its requirements can be a bit frustrating at times it is, for the most part, a very good style guideline.</p>\n<pre><code>def count_neighbours(point, mask, n):\n # Create the square around this point and count the number of neighbors.\n # Change 1: changed name from 'neighbour' to 'count neighbours'.\n # It is often helpful to have expressive names for functions and\n # variables. Since functions DO something I find verb-object phrases\n # very intuitive when I'm not working on a project where function\n # names are standardised. Someone looking at your code can ask\n # "what does this function do?", answer: oh it "counts neighbours".\n # Change 2: fixed spacing in arguments. Look into PEP8 and a linter that\n # will tell you when you place spaces in poor or unconventional\n # locations.\n mask = mask[point[0] - int(n/2) : point[0] + int(n/2) + 1,point[1] - int(n/2):point[1] + int(n/2) + 1]\n return n**2 - np.count_nonzero(mask)\n # Change 3: made indent of count_neighbours function a multiple of four.\n # Again, please follow PEP8 guidelines.\n</code></pre>\n<p>All my present changes are simply style related, now lets talk about this... thing:</p>\n<p><code>mask = mask[point[0] - int(n/2) : point[0] + int(n/2) + 1,point[1] - int(n/2):point[1] </code></p>\n<p>There's no way around the fact that this is quite ungainly. What can we do about it? The biggest problem, aesthetics aside, is that at first glance I have no idea what it's actually supposed to do. Here I approve very much that you added a comment to give some explantion as to what this function does, that comment is the only thing that made figuring out the intention easier.</p>\n<p>Python actually attaches a string encountered directly after a function defintion as a docstring for that function. You can find <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">style guidelines for writing doctrings here</a>. Let's make that comment more explicit and put it in a docstring.</p>\n<pre><code>def count_neighbours(point, mask, n):\n """\n Count the neighbours of a point, where neighbours are other points in\n mask that are within a square of side length n, centered on point.\n\n If a copy of point appears in mask it is counted as a neighbour.\n\n Arguments:\n point -- the point on which the square will be centered.\n mask -- the set of points to check.\n n -- the side length of the square.\n """\n mask = mask[point[0] - int(n/2) : point[0] + int(n/2) + 1,point[1] - int(n/2):point[1] + int(n/2) + 1]\n return n**2 - np.count_nonzero(mask)\n</code></pre>\n<p>Here I have guessed at what is supposed to be contained in <code>mask</code> and written it in the docstring. I have made this assumption based on what the function is supposed to do, but based on the call in your other function: <code>neighbour(contour[i], mask, n)</code> where you have said that <code>contour</code> is in fact your list of points I suspect there may be some confusion at the variable naming stage.</p>\n<p>I am going to give <code>mask</code> the revised name <code>all_points</code> in order to make it clearer what the argument is, and update the docstring accordingly. Now, we've finally arrived back at this<br />\n<code>all_points = all_points[point[0] - int(n/2) : point[0] + int(n/2) + 1,point[1] - int(n/2):point[1]</code>.<br />\nHow can I make this easier to follow? One obvious idea is that, since we seem to be concerned with a plane we can name some variables of interest:</p>\n<pre><code>px = point[0] # x-value (first coordinate) of the point p\npy = point[1] # y-value (second coordinate) of the point p\noffset = n/2 # half of square side length\n</code></pre>\n<p>And now finally, after some cleaning up, we actually realise that there is a deeper problem here: the confusion expression was not only poorly written, but logically flawed! Why are we slicing using the nearest integer to the boundaries of the square as indicies? This makes no sense. We are interested in comparing the bounds <code>px-offset</code> and <code>px+offset</code> to the <em>contents</em> of <code>all_points</code>, not to the indicies of <code>all_points</code>.</p>\n<p>So, what we really want to know which points in <code>all_points</code> satisfy these inequalities:</p>\n<pre><code>neighbours_x = all_points[:, 0] >= px-offset\n# is a point >= the lower bound in x?\nneighbours_x &= all_points[:, 0] <= px+offset\n# is a point <= the upper bound in x?\nneighbours_y = all_points[:, 1] >= py-offset # lower bound in y\nneighbours_y &= all_points[:, 1] <= py+offset # upper bound in y\nneighbours = neighbours_x & neighbours_y # neighbours in both axes\n</code></pre>\n<p>Go through each step of this process and print the output at each step using the example given at the end and see what each step does.</p>\n<p>Finally we want to return the number of neighbours. Both of the below expressions work. The former is faster, but the latter might give you more intuition about what we're doing:</p>\n<pre><code>return neighbours.sum()\nreturn all_points[neighbours].shape[0]\n</code></pre>\n<p>I also recommend you print <code>all_points[neighbours]</code> and see what the output is, again using the example at the end.</p>\n<pre><code>import numpy as np\nfrom itertools import product\n\n\ndef count_neighbours(point, all_points, n):\n """\n Count the neighbours of a point, where neighbours are other points in\n all_points that are within a square of side length n, centered on point.\n\n Arguments:\n point -- the point on which the square will be centered.\n all_points -- the set of points to check.\n n -- the side length of the square.\n """\n px = point[0] # x-value (first coordinate) of the point p\n py = point[1] # y-value (second coordinate) of the point p\n offset = n/2 # half of square side length\n neighbours_x = all_points[:, 0] >= px-offset\n # is a point >= the lower bound in x?\n neighbours_x &= (all_points[:, 0] <= px+offset)\n # is a point <= the upper bound in x?\n neighbours_y = all_points[:, 1] >= py-offset # lower bound in y\n neighbours_y &= all_points[:, 1] <= py+offset # upper bound in y\n neighbours = neighbours_x & neighbours_y # neighbours in both axes\n\n return neighbours.sum()\n\n\n# example 1\nX = np.array(list(product([-2,-1,0,1,2], [-2,-1,0,1,2])))\ncount_neighbours(X[0], X, 2)\n\n# example 2\nX = np.array(list(product([-2.1,-1,0.3,1.7,2], [-2.2,-1.8,0.1,1,2])))\ncount_neighbours(X[0], X, 4.7)\n</code></pre>\n<p>I hope this helps you identify logical errors in future. I think you should be able to review and refactor the other function on your own. Feel free to edit your question with the updated version later if you still want a second opinion one it is clearer what the function is doing and then we can address performance issues.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T09:18:02.593",
"Id": "484732",
"Score": "0",
"body": "Thank you for your answer, I agree with you. \nI deliberately neglected the presentation because it seemed pretty basic to me. \n\nI tried to follow your code to execute it on all my points and not just one but I can't do it. So for the moment the subject is not closed because I have no solution to propose.\n\nOf course I'll try to look for it myself and avoid bothering you again.\n\nSmall detail for the return of your function, you wanted to write 'neighbours.sum()'"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T12:05:31.273",
"Id": "484745",
"Score": "0",
"body": "Corrected the error. In order to run the function on all points you must iterate through `all_points` and call the `count_neighbours()` on each point."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T13:10:02.523",
"Id": "484748",
"Score": "0",
"body": "Ok i tried with your version and it's 6 time longer than mine.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-09T20:15:59.540",
"Id": "484951",
"Score": "0",
"body": "Okay, we can look at some other options. Most of the inefficiency in my suggestion come from the fact that we must perform 4 checks on `all_points` and then a boolean operation on an array of the same size. Before we try and figure out a one-pass way to do it ourselves, have you tried user @RootTwo's suggestion of using `scipy.spatial.cKDTree.query_ball_tree()`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-12T07:48:25.647",
"Id": "485236",
"Score": "0",
"body": "Not yet, i try to understand how to use it in my problem ! But thank you again for you time !"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T00:06:34.440",
"Id": "247593",
"ParentId": "247469",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T09:52:06.227",
"Id": "247469",
"Score": "1",
"Tags": [
"python",
"performance",
"array",
"numpy"
],
"Title": "Count the number of neighbors"
}
|
247469
|
<p>In Python 3.7, I frequently find myself writing something like this in <code>__init__</code>:</p>
<pre><code> self.foo: Optional[Foo] = None
</code></pre>
<p>For example:</p>
<pre><code>window = Window()
# do some more setup here before going to user
path = get_path_from_user()
window.build(path)
class Window:
def __init__(self):
self.image: Optional[Image] = None
def build(self, path):
self.image = Image(path)
</code></pre>
<p>I justify this to myself as:</p>
<ol>
<li>Wishing to keep <code>__init__</code> light (for maximum reuseabilty) or</li>
<li>Being unable to complete the instance when <code>__init__</code> executes.</li>
</ol>
<p>However, I typically don't use the None value for any real <em>meaning</em> in the code. In this example, suppose a Window is meaningless without an image. It's just a placeholder until <code>build</code> is called so...</p>
<p><strong>Is this an anti-pattern when doing so for either of the two reasons?</strong><br />
If so, what is a better way to do it?<br />
(Your opinion is what I'm seeking)</p>
<p>Simply removing the line from <code>__init__</code> flags a code inspection warning in PyCharm: "Instance Attribute instantiated outside <code>__init__</code>". This seems reasonable to me as it ensures I'm able to look in <code>__init__</code> and know I'm always seeing all the data attributes.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T12:25:40.010",
"Id": "484372",
"Score": "0",
"body": "It strongly depends on the context, but in general you need to create an object passing a certain set of parameters, to the optional elements a default value is given and if needed they are included later (as an aggregation). If it is mandatory to provide an object with the same attributes it has then be it so. Now, it is rare to see an object which does not need constructor parameters."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T12:44:17.757",
"Id": "484375",
"Score": "0",
"body": "@MiguelAvila thank you. It's not to avoid passing constructor parameters, I always pass them if possible. It's for 2 cases: either Foo construction would be heavy/slow so I'm thinking it shouldn't be mandatory for derived classes. Or if Foo construction can't take place during __init__ because qux is unknown at that point."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T17:27:51.267",
"Id": "484399",
"Score": "1",
"body": "This question is incomplete. To help reviewers give you better answers, please add sufficient context to your question. The more you tell us about what your code does and what the purpose of doing that is, the easier it will be for reviewers to help you. [Questions should include a description of what the code does](//codereview.meta.stackexchange.com/q/1226). I'm sure there's more to your code too, since this is pretty much just instancing things. Keep in mind Code Review requires [concrete code from a project, in its context](https://codereview.meta.stackexchange.com/a/3652)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T19:28:21.717",
"Id": "484410",
"Score": "0",
"body": "@Mast Thanks for the pointer. I'll add some more concrete code if you think it will help. I thought this question was too much an opinion-question for StackOverflow and a number of people suggested code review would be a better place. Is there a better place to post general questions about coding patterns? I'm learning Python on my own at home and trying not to develop bad habits."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T11:55:17.347",
"Id": "484489",
"Score": "0",
"body": "Remove `def __init__(self):`, deindent `self.image: Optional[Image] = None` and remove the `self.` from `self.image`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T12:01:44.723",
"Id": "484490",
"Score": "0",
"body": "@Peilonrayz thanks but that would make it a class attribute. If I created a second window it would have to share the same image."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T12:07:26.107",
"Id": "484492",
"Score": "0",
"body": "@Peilonrayz please clarify. The code I'm writing is seeking to have one image per window instance. I believe your suggested changes would create one image for the window class (accessible as Window.image)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T12:23:37.473",
"Id": "484495",
"Score": "0",
"body": "@Peilonrayz just ran it with your suggested changes plus adding Window. in front of image in build (doesn't run otherwise). First instance window1.image.path returns the value of window2.image.path as suspected. So no, it doesn't work that way in Python, at least not on my computer. ;-) Thanks anyway."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T12:38:20.200",
"Id": "484498",
"Score": "0",
"body": "@Peilonrayz Yes I did I indeed. \"AttributeError: 'NoneType' object has no attribute 'path'\" when I attempt to print window1.image.path. Without Window. \"image\" is just a local variable in the method build() so setting it has no effect. Thank you for trying to help but lets end this discussion here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T12:44:23.903",
"Id": "484500",
"Score": "0",
"body": "@RobinCarter It's still an instance variable when you do `self.image = ...`... [Like it runs fine online](https://ideone.com/NLGQMN) so you must have changed something your side."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T14:03:46.843",
"Id": "484524",
"Score": "0",
"body": "@Peilonrayz yes you're right. Thank you. I didn't know that instance variables could be annotated directly below \"class\" (I should have read PEP 526 more carefully). I'm trying to avoid setting Image to None so here's the solution I came up with. https://ideone.com/1GkPZB I can now refactor my code and it will be more readable. Shame the question is closed or I could have given it to you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T14:28:52.297",
"Id": "484531",
"Score": "0",
"body": "@Peilonrayz well maybe not according to PEP 526: \"As a matter of convenience (and convention), instance variables can be annotated in __init__ or other methods, rather than in the class\". However I am a believer in consistency and I like the idea of being able to read off a list of all the data attributes and their types without having to scan code that performs actions too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T14:36:57.150",
"Id": "484533",
"Score": "0",
"body": "@RobinCarter You are right that was added in rev2 of PEP 526. Wow that's grim."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T11:55:48.540",
"Id": "484620",
"Score": "0",
"body": "@Peilonrayz I've come full circle. I now think it should be in init as Optional[Image] = None. 1) If it's annotated below Class: PyCharm doesn't flag that it's not initialised so the error is at runtime 2) Unintended class variable exposed with potential to change behaviour of the instance variable via it's default 3) None does have a useful meaning: it means it's not properly initialised yet. 4) It's explicit which instance variables have not been initialised in init 5) class and instance variables are clearly delineated 6) compact: annotation and default value on the same line in init"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T11:57:59.653",
"Id": "484621",
"Score": "0",
"body": "@RobinCarter I would disagree with putting it in `__init__`, but if it works for you then great!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T12:36:27.167",
"Id": "484623",
"Score": "0",
"body": "@Peilonrayz thanks again for your help and for introducing me to ideone"
}
] |
[
{
"body": "<p>According to PEP 526, the initializer isn't needed. Have you tried:</p>\n<pre><code>class Window:\n def __init__(self):\n self.image: Optional[Image] # <== this is just a type hint, no initialization\n\n def build(self, path):\n self.image = Image(path)\n</code></pre>\n<p>I don't use PyCharm, so I don't know if it would still complain.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T22:56:59.257",
"Id": "484433",
"Score": "0",
"body": "I would like to do that, or even just self.image: Image. However, that still raises the warning in PyCharm and apparently also in PyLint according to this: https://stackoverflow.com/questions/19284857/instance-attribute-attribute-name-defined-outside-init. It's a \"weak\" warning and it can be turned off. PEP 526 seems concerned with type annotations and I did not see an example of an instance data attribute not being initialised in __init__? https://www.python.org/dev/peps/pep-0526/#class-and-instance-variable-annotations"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T11:52:34.517",
"Id": "484488",
"Score": "0",
"body": "This is not how it's done."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T14:07:31.723",
"Id": "484525",
"Score": "0",
"body": "@RootTwo your solution is very close. According to PEP 526, the solution to my problem seems to be to write self.image: Image directly below class Window: and to remove self.image from ```__init__``` altogether. As here https://ideone.com/1GkPZB"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T19:32:51.667",
"Id": "484545",
"Score": "1",
"body": "If you use this pattern a lot, I would consider disabling the check in PyCharm or PyLint and creating a custom checker for your use case. It could check to make sure all instance vars are initalized in either `__init__()` or `build()` (if there is one)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T11:51:47.680",
"Id": "484619",
"Score": "0",
"body": "I've come full circle. I now think it should be in ```__init__``` as ```Optional[Image] = None```. 1) If it's annotated below Class: PyCharm doesn't flag that it's not initialised so the error is at runtime 2) Unintended class variable exposed which might even change behaviour of the instance variable via it's default 3) None does have a *meaning*: it means it's not properly initialised yet. 4) It's explicit which instance variables have not been initialised in ```__init__``` 5) class and instance variables are clearly delineated 6) compact: annotation and default value on the same line"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T19:55:41.603",
"Id": "247485",
"ParentId": "247470",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "247485",
"CommentCount": "16",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T11:49:17.950",
"Id": "247470",
"Score": "3",
"Tags": [
"python"
],
"Title": "Setting instance data attributes to None in __init__"
}
|
247470
|
<p>Mash-up code, the language behind power query. A functional language primarily written with functions called to evaluate and return results, in Excel and Power BI.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T12:35:31.910",
"Id": "247471",
"Score": "0",
"Tags": null,
"Title": null
}
|
247471
|
Mash-up code, the language behind power query.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T12:35:31.910",
"Id": "247472",
"Score": "0",
"Tags": null,
"Title": null
}
|
247472
|
<p>The challenge is to sort an integer array containing only ones and zeros with the lowest complexity possible.</p>
<p>As always, I am interested in any improvements suggested but in this question I am most interested in whether the complexity that I have assigned to the algorithm is correct (as well as the lowest possible). I have included two implementations that have two different running times. I believe that they are still both the same complexity. The larger purpose in posting this is to improve or verify my understanding of Complexity and big oh notation.</p>
<p>I assign the complexity as O(n) to this first algorithm since it only looks at every value in the array once, and only once.</p>
<p><strong>Algorithm I</strong></p>
<pre><code> /// <param name="value">A list of values to sort where all values are either one or zero.</param>
/// <returns>Sorted value array.</returns>
public static int[] SortOnesZeros(int[] value)
{
int j = value.Length - 1;
int i = 0;
while (i < j)
{
if (value[i] < 0 || value[i] > 1 || value[j] < 0 || value[j] > 1)
{
throw new Exception("Value array can only contain 1's and 0's.");
}
while (value[i] == 0)
{
i++;
}
while (value[j]== 1)
{
j--;
}
if (j > i && value[i] > value[j] )
{
int temp = value[j];
value[j] = value[i];
value[i] = temp;
j--;
i++;
}
}
return value;
}
</code></pre>
<p>I have a second implementation that I believe is also O(n) though it is longer since it runs through n twice, but it is not nested. I believe this is true because O(2n) reduces to O(n) since multiplied constants are not considered in big-oh complexity analysis. It is also longer because it changes every value on the second pass. No need to improve on this algorithm, I believe that the first algorithm is already better.:</p>
<p><strong>Algorithm II</strong></p>
<pre><code> public static int[] SortOnesZerosAlternate(int[] values)
{
int countOfZeros = 0;
foreach(int value in values)
{
if (value == 0)
{
countOfZeros++;
}
if (value <0 || value > 1)
{
throw new Exception("Value array can only contain 1's and 0's.");
}
}
for (int i = 0; i < countOfZeros; i++)
{
values[i] = 0;
}
for (int i = countOfZeros; i < values.Length; i++)
{
values[i] = 1;
}
return values;
}
</code></pre>
<p>EDIT ***************************************</p>
<p>@superb rain is correct: The first algorithm has a mistake where, under the right conditions, it tries to sort values in the value array that are not actually on the list. This issue will occur on any list where all the values are the same. I have fixed this in my own code by making the change below:</p>
<pre><code> while (i < j && value[i] == 0)
{
i++;
}
while (i < j && value[j]== 1)
{
j--;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T17:44:50.433",
"Id": "484403",
"Score": "1",
"body": "Your first one crashes for `{0, 0}`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T07:50:55.147",
"Id": "484455",
"Score": "0",
"body": "For the second algorithm, wouldn't the cost of running through `n` be compensated by the very predictable element access ? Also, does anything like likely attribute exist in c# ? https://stackoverflow.com/questions/51797959/how-to-use-c20s-likely-unlikely-attribute-in-if-else-statement"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T17:03:57.757",
"Id": "484646",
"Score": "0",
"body": "@anki I think you are correct, and I think that saying that the time complexity O(n) == O(2n) is saying the same thing. See the comments in spyr03's answer for details from actual speed test results. I don't think there is anything like likely in C# but that is interesting, thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T22:00:00.283",
"Id": "484695",
"Score": "1",
"body": "How fast is simply using C#'s sort method?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T16:48:18.370",
"Id": "484765",
"Score": "0",
"body": "Ha Ha, that probably violates the spirit of the thing...."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T17:13:41.653",
"Id": "484780",
"Score": "0",
"body": "OK, so algorithm I performs 83% faster than Array.Sort(). In Microsoft's defense, it is sorting on any value, not just 1's and 0's...."
}
] |
[
{
"body": "<p>I agree with your analysis that both algorithms have O(n) time complexity (where n is the number of elements in the array). An important factor to note is that both algorithms also use constant extra space.</p>\n<p>However, you can include other metrics in your analysis too. Anything that may be expensive to do can be considered. Two common metrics are the number of comparisons and the number of exchanges.</p>\n<p>The number of comparisons tells you how often an element of the array is accessed and then compared. Memory access can be quite expensive, depending on how far up the memory hierarchy (registers, cache levels, RAM, local storage, external storage) you need to traverse before getting the value.</p>\n<p>The number of exchanges tells you how many times elements are swapped. This can be expensive any time writing to memory is. For instance, writing to shared memory in a multi-process program.</p>\n<hr />\n<p>Taking the above into account, ignoring the error checking case, and also ignoring any potential optimisations from the compiler, I would argue the second algorithm is better. For the first implementation I count 2 comparisons per element, and 1 exchange per element. For the second, I count 1 comparison per element, and then 1 assignment per element (an assignment of a constant is cheaper than exchanging two elements).</p>\n<p>You can replace the exchange with assignments in the first implementation. Since the array only contains the values 0 and 1, and you've checked that the two elements are different.</p>\n<pre><code>if (j > i && value[i] > value[j] )\n{\n value[j] = 1;\n value[i] = 0;\n j--;\n i++;\n}\n</code></pre>\n<p>Without profiling the code, I don't think it is possible to tell if the extra number of comparisons in the first implementation are more costly than the overhead of the second pass through the array in the second implementation. I would not be surprised if the numerous bounds checks in the first piece of code (<code>i < j</code>) are the actually largest performance hit.</p>\n<hr />\n<h2>Third implementation</h2>\n<p>Based on the comment that the first implementation is still faster, here is another solution that tries to improve upon the second. I'm hoping that by writing it with well known operations, the compiler can work some magic.</p>\n<pre><code>public static int[] SortOnesZerosAlternate(int[] values)\n{\n int countOfZeros = values.Length - values.sum();\n // Maybe replace this with values.Clear?\n for (int i = 0; i < countOfZeros; i++)\n {\n values[i] = 0;\n }\n\n for (int i = countOfZeros; i < values.Length; i++)\n {\n values[i] = 1;\n }\n\n return values;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T16:41:37.263",
"Id": "484641",
"Score": "0",
"body": "I just ran a test of a randomly generated array with 100 Million values. The first algorithm won being roughly 95% faster. I believe that is because you are focusing on worst case where the list is sorted in descending order... I will test this for the fun of it. Your fix to the first algorithm improved the time by roughly 15%. Based on an unscientific observation the results for the first algorithm can vary by about 10% on my system."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T16:51:23.490",
"Id": "484642",
"Score": "0",
"body": "Interesting. I will add a third solution as an edit, if you want to try profiling it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T16:52:24.460",
"Id": "484643",
"Score": "0",
"body": "How interesting: When tested at the worst case where there is an equal balance of 1's and 0's and the list is sorted in descending order, both algorithms complete in the same time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T16:53:25.457",
"Id": "484644",
"Score": "0",
"body": "It's fine, or you could add it to your answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T17:03:57.977",
"Id": "484647",
"Score": "1",
"body": "@amalgamate It might be worth pointing out that with 100 million values and an even balance of 0s and 1s, `countOfZeros` could overflow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T17:06:02.967",
"Id": "484648",
"Score": "0",
"body": "I think that explains an earlier crash. :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T17:41:49.460",
"Id": "484654",
"Score": "0",
"body": "Ooops I deleted some incorrect information caused by mislabeled functions....\nThe correct results:"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T17:54:27.937",
"Id": "484657",
"Score": "0",
"body": "and... corrected my math..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T18:02:57.380",
"Id": "484659",
"Score": "0",
"body": "Algorithm I ran 79% faster than Algorithm III for Average Case. \nAlgorithm I ran 34% faster than Algorithm III for Worst Case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T18:03:10.853",
"Id": "484660",
"Score": "1",
"body": "I improved Algorithm III by assigning \"values = new int[values.Length];\" instead of assigning all of the zero values. \nThis improved the results where...\nAlgorithm I ran 50% faster than Algorithm III for Average Case. \nAlgorithm I ran 8% faster than Algorithm III for Worst Case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T18:05:47.377",
"Id": "484661",
"Score": "1",
"body": "You might consider looking into whatever the C# equivalent of std::fill is. It might be better optimised."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T18:06:21.170",
"Id": "484662",
"Score": "0",
"body": "Through repeated tests, algorithm performs just ever so slightly worse than algorithm I at worst case."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T15:43:50.843",
"Id": "247572",
"ParentId": "247479",
"Score": "4"
}
},
{
"body": "<p>I think you might be able to get a marginal boost by implementing this in two steps: move all the 1s to the end, set everything before to 0. Your current alternate is: count 0s, write 0s, write 1s.</p>\n<pre><code>public static void SortOnesZeros(int[] input)\n{\n var oneCursor = input.Length - 1;\n for (var i = oneCursor; i >= 0; i--)\n {\n if (input[i] == 1)\n {\n input[oneCursor--] = 1;\n }\n }\n // if the cursor is still at the end we have an all 0 array so nothing to clear.\n if (oneCursor != input.Length - 1)\n {\n Array.Clear(input, 0, oneCursor + 1);\n }\n}\n</code></pre>\n<p>Unfortunately Array.Clear is O(N) (although N here is number of 0s, not total elements so worst case is O(N)). There are some interesting techniques to zero the first part faster though: <a href=\"https://stackoverflow.com/a/25808955/1402923\">https://stackoverflow.com/a/25808955/1402923</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T18:17:54.267",
"Id": "484663",
"Score": "0",
"body": "Using Array.Clear, which I admit @spyr03 suggested, Shaved enough time that Algorithm III (@spyr03) now beats Algorithm I in worst case. Algorithm I is still faster by 40%."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T18:22:44.190",
"Id": "484665",
"Score": "0",
"body": "Ah - I must have missed that suggestion, @amalgamate. Have you tested against creating a new array and returning that? Then it's only one pass through the input but you use twice as much memory."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T19:25:22.663",
"Id": "484677",
"Score": "0",
"body": "See the comment that starts with \"\nI improved Algorithm III by assigning \"values = new int[values.Length];\" in @spyr03's answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T20:30:29.273",
"Id": "484685",
"Score": "0",
"body": "Kudos! I implemented your code and it wins the speed challenge. Percentages will not do here. At an array size of 10 million, your algorithm which I guess I should call IV, gets the values of 40ms for random values, and 51ms for worst case. The first algorithm (I) gets the values of 42ms for random values, and 63ms for worst case."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T18:05:57.347",
"Id": "247584",
"ParentId": "247479",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "247572",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T16:47:57.493",
"Id": "247479",
"Score": "7",
"Tags": [
"c#",
"sorting",
"complexity"
],
"Title": "Determine the complexity of sorting a binary array"
}
|
247479
|
<p>I just completed the first release for my first game on Python, called Dungeon Ball. I'm looking for people to test out the app and give me some feedback and constructive criticism. I'd like to use this project as a way to improve my programming skills and hopefully learn some efficient programming practices.</p>
<p>The game is called Dungeon Ball. It is pretty basic at the moment. It is pretty similar to games on breaking bricks with a ball and a racquet/paddle but I haven't included the bricks just yet. Currently, the goal is to just keep the ball from falling using the paddle. By hitting the paddle you get points, which causes you to level up. The higher the level, the faster the paddle and ball move.</p>
<p><strong>Main.py</strong></p>
<pre><code>import pygame
from pygame.locals import *
import numpy as np
import math
from sys import exit
pygame.init()
from variables import *
def gameOver():
pygame.mixer.music.stop()
sounds['gameOver'].play()
keyStatus = True
blinkerCount = 0
blinkerState = True
blinkTime = 15
while keyStatus:
pygame.draw.rect(DISPLAYSURF, colours['grey'], dimensions['arena'])
# pygame.draw.rect(DISPLAYSURF, colours['brown'], dimensions['arena'], borderWidth)
if blinkerState:
textSurfaceObj = fonts['largeFont'].render('GAME OVER!', True, colours['red'])
textRectObj = textSurfaceObj.get_rect()
textRectObj.center = (boxSize[0]/2, boxSize[1]/2)
DISPLAYSURF.blit(textSurfaceObj, textRectObj)
scoreSurface = fonts['midFont'].render('Score : {}'.format(gameStatus['points']), True, colours['white'])
scoreSurfaceRect = scoreSurface.get_rect()
scoreSurfaceRect.center = (boxSize[0]/2, boxSize[1]/2 + 50)
DISPLAYSURF.blit(scoreSurface, scoreSurfaceRect)
blinkerCount += 1
if blinkerCount % blinkTime == 0:
blinkerCount = 0
blinkerState = not blinkerState
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
sounds['gameOver'].stop()
keyStatus = False
elif event.key == pygame.K_ESCAPE:
pygame.quit()
exit()
pygame.display.update()
fpsClock.tick(FPS)
if keyStatus == False:
break
main()
def renderFunction():
global gameStatus
pygame.draw.rect(DISPLAYSURF, colours['black'], dimensions['arena'])
pygame.draw.rect(DISPLAYSURF, colours['brown'], dimensions['arena'], borderWidth)
pygame.draw.rect(DISPLAYSURF, colours['red'], dimensions['paddle'])
pygame.draw.circle(DISPLAYSURF, colours['blue'], (ball['position']['x'], ball['position']['y']), ball['rad'] , 0)
pointSurface = fonts['tinyFont'].render('Points : ' + str(gameStatus['points']), True, colours['white'])
pointSurfaceRect = pointSurface.get_rect()
pointSurfaceRect.center = (40, boxSize[1]-10)
DISPLAYSURF.blit(pointSurface, pointSurfaceRect)
levelSurface = fonts['tinyFont'].render('Level : ' + str(gameStatus['level']), True, colours['white'])
levelSurfaceRect = levelSurface.get_rect()
levelSurfaceRect.center = (boxSize[0]-40, boxSize[1]-10)
DISPLAYSURF.blit(levelSurface, levelSurfaceRect)
def introScreen():
keyStatus = True
blinkerCount = 0
blinkerState = True
blinkTime = 15
pygame.mixer.music.load('audio/startScreenMusic.wav')
pygame.mixer.music.play(-1, 0.0)
while keyStatus:
pygame.draw.rect(DISPLAYSURF, colours['grey'], dimensions['arena'])
# pygame.draw.rect(DISPLAYSURF, colours['brown'], dimensions['arena'], borderWidth)
textSurfaceObj = fonts['largeFont'].render(gameStatus['name'], True, colours['gold'])
textRectObj = textSurfaceObj.get_rect()
textRectObj.center = (boxSize[0]/2, boxSize[1]/2)
DISPLAYSURF.blit(textSurfaceObj, textRectObj)
if blinkerState:
spaceSurfaceObj = fonts['midFont'].render('Press Enter to Continue', True, colours['white'])
spaceRectObj = spaceSurfaceObj.get_rect()
spaceRectObj.center = (boxSize[0]/2, boxSize[1]/2+50)
DISPLAYSURF.blit(spaceSurfaceObj, spaceRectObj)
versionSurface = fonts['tinyFont'].render(gameStatus['version'], True, colours['white'])
versionSurfaceRect = versionSurface.get_rect()
versionSurfaceRect.center = (boxSize[0]-20, boxSize[1]-10)
DISPLAYSURF.blit(versionSurface, versionSurfaceRect)
blinkerCount += 1
if blinkerCount % blinkTime == 0:
blinkerCount = 0
blinkerState = not blinkerState
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
keyStatus = False
elif event.key == pygame.K_ESCAPE:
pygame.quit()
exit()
pygame.display.update()
fpsClock.tick(FPS)
keyStatus=True
pygame.mixer.music.stop()
def eventHandler():
global dimensions
keys=pygame.key.get_pressed()
if keys[K_LEFT] and not (dimensions['paddle'].left <= (dimensions['arena'].left+borderWidth)):
direction = -1*paddle['speed']
# print('hi left')
paddle['position']['x'] += direction
elif keys[K_RIGHT] and not (dimensions['paddle'].right >= (dimensions['arena'].right-borderWidth)):
direction = paddle['speed']
# print('hi right')
paddle['position']['x'] += direction
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
exit()
dimensions['paddle'] = pygame.Rect(paddle['position']['x'], paddle['position']['y'], paddle['length'], 10)
def ballEngine():
global gameStatus
if (ball['position']['x'] <= (dimensions['arena'].left+borderWidth+ball['rad'])):
# print('LeftSideBounce')
ball['direction'] = 180 - ball['direction'] + np.random.randint(-1*gameStatus['random'],gameStatus['random'])
sounds['wallHit'].play()
elif (ball['position']['x'] >= (dimensions['arena'].right-borderWidth-ball['rad'])):
# print('RightSideBounce')
ball['direction'] = 180 - ball['direction'] + np.random.randint(-1*gameStatus['random'],gameStatus['random'])
sounds['wallHit'].play()
elif ball['position']['y'] <= (dimensions['arena'].top+borderWidth+ball['rad']):
# print('TopBounce')
ball['direction'] = 360 - ball['direction'] + np.random.randint(-1*gameStatus['random'],gameStatus['random'])
if ball['direction'] >= 250 and ball['direction'] <= 290:
ball['direction'] += np.random.randint(-2*gameStatus['random'],2*gameStatus['random'])
sounds['wallHit'].play()
elif ball['position']['y'] >= (dimensions['arena'].bottom - borderWidth - ball['rad']):
# print('BottomBounce')
# ball['speed'] = 0
# gameStatus = True
gameOver()
# print(ball['direction'])
if (ball['position']['y'] >= (paddle['position']['y']-ball['rad']) and ball['position']['y'] <= paddle['position']['y']+dimensions['paddle'].height+ball['rad']) and ball['position']['x'] >= dimensions['paddle'].left and ball['position']['x'] <= dimensions['paddle'].right:
# print('Paddle hit')
ball['direction'] = 360 - ball['direction'] + np.random.randint(-1*gameStatus['random'],gameStatus['random'])
gameStatus['points'] = gameStatus['points'] + 1
sounds['paddleHit'].play()
print(ball['position'], paddle['position'], ball['direction'])
gameStatus['paddleHitsPerLevel'] += 1
if ball['position']['y'] >= dimensions['paddle'].top and ball['position']['y'] <= dimensions['paddle'].bottom:
ball['position']['y'] = dimensions['paddle'].top - ball['rad']
if gameStatus['paddleHitsPerLevel'] == (gameStatus['level']*5) and not gameStatus['points'] == 0:
ball['speed'] += 2
gameStatus['level'] += 1
gameStatus['random'] += 2
gameStatus['paddleHitsPerLevel'] = 0
sounds['levelUp'].play()
if gameStatus['points'] % 10 == 0 and not gameStatus['points'] == 0:
paddle['speed'] += 1
if (ball['direction']>360 or ball['direction'] < 0):
ball['direction'] %= 360
if ball['direction'] % 90 >= 85 and ball['direction'] % 90 <=89 or ball['direction'] % 90 >= 0 and ball['direction'] % 90 <= 5:
ball['direction'] += np.random.randint(-2*gameStatus['random'],2*gameStatus['random'])
if ball['position']['y'] < borderWidth+ball['rad']:
ball['position']['y'] = borderWidth+ball['rad']
elif ball['position']['x'] < borderWidth+ball['rad']:
ball['position']['x'] = borderWidth+ball['rad']
elif ball['position']['x'] > dimensions['arena'].right-borderWidth-ball['rad']:
ball['position']['x'] = dimensions['arena'].right-borderWidth-ball['rad']
ball['position']['x'] += int(ball['speed']*math.cos(ball['direction']*math.pi/180))
ball['position']['y'] += int(ball['speed']*math.sin(ball['direction']*math.pi/180))
def init():
global ball, paddle, gameStatus
ball['position']['x']=boxSize[0]/2
ball['position']['y']=int(boxSize[1]/3)
ball['direction']=np.random.randint(295, 325)
ball['speed']=5
ball['rad']=5
paddle['position']['x']=boxSize[0]/2
paddle['position']['y']=boxSize[1]-50
paddle['length']=100
paddle['speed']=5
gameStatus['points']=0
gameStatus['level']=1
gameStatus['random']=5
def main():
introScreen()
init()
pygame.mixer.music.load('audio/gamePlayMusic.wav')
pygame.mixer.music.play(-1, 0.0)
while True:
eventHandler()
ballEngine()
renderFunction()
pygame.display.update()
fpsClock.tick(FPS)
if __name__ == '__main__':
fpsClock = pygame.time.Clock()
DISPLAYSURF = pygame.display.set_mode(boxSize, 0, 32)
pygame.display.set_caption(gameStatus['name'])
main()
</code></pre>
<p><strong>Variables.py</strong></p>
<pre><code>import numpy as np
import pygame
pygame.init()
from pygame.locals import *
import os
FPS = 30
borderWidth = 5
boxSize = (700, 400)
colours = {'black':(0, 0, 0),
'red': (255, 0, 0),
'blue':(0, 0, 255),
'brown':(210, 105, 30),
'green':(0, 255, 0),
'white':(255, 255, 255),
'gold':(255, 215, 0),
'silver':(192, 192, 192),
'grey':(128, 128, 128)}
ball = {'position':{'x':boxSize[0]/2, 'y':boxSize[1]/3}, 'direction':np.random.randint(295, 325), 'speed':5, 'rad':5}
paddle = {'position':{'x':boxSize[0]/2, 'y':boxSize[1]-50}, 'length':100, 'speed':5}
dimensions = {
'arena': pygame.Rect(0, 0, boxSize[0], boxSize[1]+10),
'paddle': pygame.Rect(paddle['position']['x'], paddle['position']['y'], paddle['length'], 10)
}
gameStatus = {'points': 0, 'level': 1, 'random': 5, 'paddleHitsPerLevel':0, 'name': 'Dungeon Ball', 'version': 'v1.0'}
fonts = {
'largeFont':pygame.font.Font(os.path.join(os.getcwd(),'fonts','Ancient_Modern_Tales_Regular.ttf'), 64),
'midFont':pygame.font.Font(os.path.join(os.getcwd(),'fonts', 'Old_School_Adventures_Regular.ttf'), 12),
'tinyFont': pygame.font.Font(os.path.join(os.getcwd(),'fonts', 'Old_School_Adventures_Regular.ttf'), 8)
}
sounds = {
'paddleHit': pygame.mixer.Sound(os.path.join(os.getcwd(), 'audio', 'paddle_hit.wav')),
'wallHit': pygame.mixer.Sound(os.path.join(os.getcwd(), 'audio', 'wall_hit.wav')),
'gameOver':pygame.mixer.Sound(os.path.join(os.getcwd(), 'audio', 'game_over.wav')),
'levelUp': pygame.mixer.Sound(os.path.join(os.getcwd(), 'audio', 'level_up.wav'))
}
</code></pre>
<p>Currently, the <a href="https://github.com/souviksaha97/brickbreaker/releases/tag/v1.0.0" rel="noreferrer">release</a> is only for Linux and Windows. Mac users could try and build the environment and run the program directly. First step, you need to download your OS specific release and unzip it. Enter the extracted directory. Windows users just double click to run. Linux users need to open the directory in terminal and run ./main.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T18:51:20.310",
"Id": "484407",
"Score": "1",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T19:03:28.700",
"Id": "484408",
"Score": "0",
"body": "@Mast thanks for the suggestion. Is this a better topic?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T19:04:58.843",
"Id": "484409",
"Score": "0",
"body": "No, I've fixed it for you. Leave the concerns to the question body."
}
] |
[
{
"body": "<p>I have not tried playing the game, but had a look at the code and I have some suggestions.</p>\n<p><strong>Code readability suggestions</strong></p>\n<p><code>boxSize[0]</code> and <code>boxSize[1]</code> is used all over your code and not very readable. There is only one place where you actually use the variable <code>boxSize</code> without indexes, so I would do the opposite and define <code>width = 700</code> and <code>height=400</code> so that you can refer to them where needed, and then in the one line that you used <code>boxSize</code> you change that to</p>\n<p><code>ISPLAYSURF = pygame.display.set_mode((width, height), 0, 32)</code></p>\n<p><strong>Readability 2</strong></p>\n<p><code> ball['direction']=np.random.randint(295, 325)</code>\nI think the numbers 295 and 325 refer to angles but they could be named to make that clearer.</p>\n<p><strong>Readability 3</strong></p>\n<p><code>ball['rad']</code></p>\n<p>I think <code>rad</code> is short for <code>radius</code> but it's not a good name. Generally avoid short versions of words. Especially <strong>rad</strong> which in mathematics commonly refers to radians used to measure angles, which confused me while thinking about the direction of the ball.</p>\n<p><strong>Readability 4</strong></p>\n<pre><code>if keys[K_LEFT] and not (dimensions['paddle'].left <= (dimensions['arena'].left+borderWidth)):\n</code></pre>\n<p><code>not <=</code> is requivalent to just <code>></code> so it would be more readable to rather write</p>\n<pre><code>if keys[K_LEFT] and (dimensions['paddle'].left > (dimensions['arena'].left+borderWidth)):\n</code></pre>\n<p><strong>Logic 1</strong></p>\n<pre><code> if blinkerCount % blinkTime == 0:\n blinkerCount = 0\n blinkerState = not blinkerState\n</code></pre>\n<p>Since you're resetting <code>blinkerCount</code> to 0 every time, you don't need the modulo operation, you can just change the if-clause to <code>if blinkerCount == blinkTime</code> . The modulo operation would make sense if you didn't reset to 0.</p>\n<p><strong>Logic 2</strong></p>\n<pre><code> for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n exit()\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_RETURN:\n sounds['gameOver'].stop()\n keyStatus = False\n elif event.key == pygame.K_ESCAPE:\n pygame.quit()\n exit()\n</code></pre>\n<p>Both <code>elif</code> here are redundant and can be replaced by just <code>if</code>.\nSince <code>pygame.QUIT</code> and <code>pygame.KEYDOWN</code> are different things, an event cannot by definition be equal to both, so the "else" in the <code>elif</code> is not needed.</p>\n<p><strong>Avoid repetition 1</strong></p>\n<p>You are making many calls to\n<code>pygame.draw.rect(DISPLAYSURF</code> which I would create a new function for, so that you don't have to repeat this over and over.</p>\n<p>It would be something like</p>\n<pre><code>def rectangle(color, _dimensions):\n pygame.draw.rect(DISPLAYSURF, colors[color], _dimensions)\n</code></pre>\n<p>and then in the other places of your code you can replace something like</p>\n<p><code>pygame.draw.rect(DISPLAYSURF, colours['grey'], dimensions['arena'])</code></p>\n<p>with just</p>\n<p><code>rectangle('grey', dimensions['arena'])</code></p>\n<p><strong>Avoid repetition 2</strong></p>\n<pre><code>sounds = {\n 'paddleHit': pygame.mixer.Sound(os.path.join(os.getcwd(), 'audio', 'paddle_hit.wav')), \n 'wallHit': pygame.mixer.Sound(os.path.join(os.getcwd(), 'audio', 'wall_hit.wav')), \n 'gameOver':pygame.mixer.Sound(os.path.join(os.getcwd(), 'audio', 'game_over.wav')),\n 'levelUp': pygame.mixer.Sound(os.path.join(os.getcwd(), 'audio', 'level_up.wav'))\n }\n</code></pre>\n<p>See how 70% of each line here is identical to the other? This is where you want to create a function for this, like</p>\n<pre><code>def get_sound(filename):\n return pygame.mixer.Sound(os.path.join(os.getcwd(), 'audio', filename))\n</code></pre>\n<p>so that you can replace the above with</p>\n<pre><code>sounds = {\n 'paddleHit': get_sound('paddle_hit.wav'), \n 'wallHit': get_sound('wall_hit.wav'), \n 'gameOver':get_sound('game_over.wav'),\n 'levelUp': get_sound('level_up.wav')\n }\n</code></pre>\n<p>(It can be made even shorter if the keys were named same as the files)</p>\n<p><strong>Code quality and readability</strong></p>\n<pre><code>if ball['position']['y'] < borderWidth+ball['rad']:\n</code></pre>\n<p>This kind of code is quite hard to read and surely a waste of space and time to write as well. I recommend you look up basic objects/classes, so that you can define a class <code>ball</code> and set its properties, so that you can instead write</p>\n<p><code>if ball.y < borderWidth+ball.radius:</code></p>\n<p>See how much easier that is?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-10T20:24:44.047",
"Id": "485054",
"Score": "0",
"body": "Okay these are really insightful. Thanks for your suggestions. If you can please try out the game when you're free? I'd like a critique on the aesthetic as well. Also do you suggest any features I could add?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-11T00:26:03.200",
"Id": "485088",
"Score": "0",
"body": "The problem with trying out the game is that I would have to set up an environment with pygame and maybe other libraries, and run code that I don't know all the details of, on my own computer, which is time consuming and a risk. I would try it if you could make it playable online somehow, in a virtual environment or something. Otherwise, I recommend making a recording of when you play it yourself and put that on Youtube, that makes it a lot more available to others and enables you to collect feedback from other people easier."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-11T00:27:38.103",
"Id": "485089",
"Score": "0",
"body": "There is also gamedev stackexchange, I don't know their policies for posting, but it might be open to feedback on your own games. If not, there are other websites and communities for that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-11T03:09:59.283",
"Id": "485098",
"Score": "0",
"body": "I've created an exe file of the app so you do not have to create the environment. But no problem. Yeah I think I could do a video on YouTube or something similar."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-11T18:57:39.627",
"Id": "485195",
"Score": "0",
"body": "Running an unknown exe file from an unknown person is an even greater risk than setting up the environment and running the code that I can at least read through. Not worth it, I'm afraid. I'd be happy to provide more code review input to an updated version of the code though, perhaps via github?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-11T18:59:11.453",
"Id": "485196",
"Score": "0",
"body": "yes I fully understand your concern. I can share the GitHub link with you?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-13T12:11:12.123",
"Id": "485381",
"Score": "0",
"body": "The github link is already in the question body, so I have that :)"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-10T19:28:56.823",
"Id": "247732",
"ParentId": "247482",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T18:10:10.707",
"Id": "247482",
"Score": "11",
"Tags": [
"python",
"python-3.x",
"pygame"
],
"Title": "Dungeon Ball, a Pygame"
}
|
247482
|
<p>This is mostly an exercise for me to try to understand the differences between semaphores and locks. It's a long and rambling because it took me quite a few tries to understand the concepts. Please bear with me. I am hoping you can either confirm that the lesson I learned was correct or pointing out my misunderstanding. Please jump to the last code section if you just would like to see my final code.</p>
<p>I read about this blog: <a href="https://vorbrodt.blog/2019/02/03/blocking-queue/" rel="nofollow noreferrer">https://vorbrodt.blog/2019/02/03/blocking-queue/</a> and it really confused me. If we were going to serialize access to the elements, what's the point of the semaphore? I originally thought a semaphore is basically a counter protected by a lock, so I was having trouble understand the differences. I decided to implement it myself without using a semaphore. Here is my first (incorrect) attempt of implementing a blocking queue with one producer and one consumer:</p>
<pre><code>#include <iostream>
#include <mutex>
#include <condition_variable>
#include <thread>
#include <queue>
template <typename T>
class OneToOneBlockingQueue {
private:
unsigned int m_maxSize;
std::queue <T> m_data;
std::mutex m_mutex;
std::condition_variable m_readCond;
std::condition_variable m_writeCond;
public:
OneToOneBlockingQueue(unsigned int size): m_maxSize(size) {
}
void push(T value) {
std::unique_lock <std::mutex> myLock(m_mutex);
m_writeCond.wait(myLock, [this]() { return m_data.size() < m_maxSize; });
m_data.push(value);
m_readCond.notify_one();
}
void pop(T& value) {
std::unique_lock <std::mutex> myLock(m_mutex);
m_readCond.wait(myLock, [this]() { return m_data.size() > 0; });
value = m_data.front();
m_data.pop();
m_writeCond.notify_one();
}
};
class Producer {
public:
Producer(OneToOneBlockingQueue <int>& bq, int id):m_bq(bq), m_id(id) {
}
void operator()() {
for (int i = 0; i < 10; i++) {
m_bq.push(i);
}
}
private:
OneToOneBlockingQueue<int> &m_bq;
int m_id;
};
class Consumer {
public:
Consumer(OneToOneBlockingQueue <int>& bq, int id):m_bq(bq), m_id(id) {
}
void operator()() {
std::cout << "Reading from queue: ";
for (int i = 0; i < 10; i++) {
int value;
m_bq.pop(value);
std::cout << value << " ";
}
std::cout << std::endl;
}
private:
OneToOneBlockingQueue <int> &m_bq;
int m_id;
};
int main() {
OneToOneBlockingQueue <int>bq(2);
std::thread producerThread (Producer(bq, 0));
std::thread consumerThread (Consumer(bq, 0));
producerThread.join();
consumerThread.join();
}
</code></pre>
<p>While it worked, I then realized it was not correct since the producer and the consumer can't read and write at the same time. Assuming the consumer is very slow, the producer would be locked out until the consumer finished reading even though the queue is not full. The only critical section is the counter, not the data itself. However, using std::queue, I couldn't separate the two. Maybe that is why the other author used an looping array instead?</p>
<p>Here is my second attempt:</p>
<pre><code>#include <iostream>
#include <mutex>
#include <condition_variable>
#include <thread>
template <typename T>
class OneToOneBlockingQueue {
private:
unsigned int m_maxSize;
T *m_data;
unsigned int m_size;
std::mutex m_mutex;
std::condition_variable m_readCond;
std::condition_variable m_writeCond;
unsigned int m_readLoc;
unsigned int m_writeLoc;
public:
OneToOneBlockingQueue(unsigned int size): m_maxSize(size), m_size(0), m_data(new T[size]), m_readLoc(0), m_writeLoc(0) {
}
void push(T value) {
std::unique_lock <std::mutex> myLock(m_mutex);
m_writeCond.wait(myLock, [this]() { return m_size < m_maxSize; });
myLock.unlock();
m_data[m_writeLoc++] = value;
if (m_writeLoc == m_maxSize) {
m_writeLoc = 0;
}
myLock.lock();
m_size++;
m_readCond.notify_one();
}
void pop(T& value) {
std::unique_lock <std::mutex> myLock(m_mutex);
m_readCond.wait(myLock, [this]() { return m_size > 0; });
myLock.unlock();
value = m_data[m_readLoc++];
if (m_readLoc == m_maxSize) {
m_readLoc = 0;
}
myLock.lock();
m_size--;
m_writeCond.notify_one();
}
};
class Producer {
public:
Producer(OneToOneBlockingQueue <int>& bq, int id):m_bq(bq), m_id(id) {
}
void operator()() {
for (int i = 0; i < 10; i++) {
m_bq.push(i);
}
}
private:
OneToOneBlockingQueue<int> &m_bq;
int m_id;
};
class Consumer {
public:
Consumer(OneToOneBlockingQueue <int>& bq, int id):m_bq(bq), m_id(id) {
}
void operator()() {
std::cout << "Reading from queue: ";
for (int i = 0; i < 10; i++) {
int value;
m_bq.pop(value);
std::cout << value << " ";
}
std::cout << std::endl;
}
private:
OneToOneBlockingQueue <int> &m_bq;
int m_id;
};
int main() {
OneToOneBlockingQueue <int>bq(2);
std::thread producerThread (Producer(bq, 0));
std::thread consumerThread (Consumer(bq, 0));
producerThread.join();
consumerThread.join();
}
</code></pre>
<p>I think the differences between semaphore and lock is that the semaphore by itself does not protect the elements, only the use count. The producer and consumer must inherently work on different elements for it to work. Is that correct?</p>
<p>Here is the code after abstracting the counter into a semaphore class.</p>
<pre><code>#include <iostream>
#include <mutex>
#include <condition_variable>
#include <thread>
class Semaphore {
private:
unsigned int m_counter;
std::mutex m_mutex;
std::condition_variable m_cond;
public:
Semaphore(unsigned int counter):m_counter(counter) {
}
void P() {
std::unique_lock <std::mutex> myLock(m_mutex);
m_cond.wait(myLock, [this]() { return m_counter > 0; });
m_counter--;
}
void V() {
std::lock_guard <std::mutex> myLock(m_mutex);
m_counter++;
m_cond.notify_one();
}
};
template <typename T>
class OneToOneBlockingQueue {
private:
unsigned int m_maxSize;
T *m_data;
Semaphore m_filledSlots;
Semaphore m_emptySlots;
unsigned int m_readLoc;
unsigned int m_writeLoc;
public:
OneToOneBlockingQueue(unsigned int size): m_maxSize(size), m_data(new T[size]), m_filledSlots(0), m_emptySlots(size), m_readLoc(0), m_writeLoc(0) {
}
void push(T value) {
m_emptySlots.P();
m_data[m_writeLoc++] = value;
if (m_writeLoc == m_maxSize) {
m_writeLoc = 0;
}
m_filledSlots.V();
}
void pop(T& value) {
m_filledSlots.P();
value = m_data[m_readLoc++];
if (m_readLoc == m_maxSize) {
m_readLoc = 0;
}
m_emptySlots.V();
}
};
class Producer {
public:
Producer(OneToOneBlockingQueue <int>& bq, int id):m_bq(bq), m_id(id) {
}
void operator()() {
for (int i = 0; i < 10; i++) {
m_bq.push(i);
}
}
private:
OneToOneBlockingQueue<int> &m_bq;
int m_id;
};
class Consumer {
public:
Consumer(OneToOneBlockingQueue <int>& bq, int id):m_bq(bq), m_id(id) {
}
void operator()() {
std::cout << "Reading from queue: ";
for (int i = 0; i < 10; i++) {
int value;
m_bq.pop(value);
std::cout << value << " ";
}
std::cout << std::endl;
}
private:
OneToOneBlockingQueue <int> &m_bq;
int m_id;
};
int main() {
OneToOneBlockingQueue <int>bq(2);
std::thread producerThread (Producer(bq, 0));
std::thread consumerThread (Consumer(bq, 0));
producerThread.join();
consumerThread.join();
}
</code></pre>
<p>And finally, to allow multiple consumer, we only need to worry about producers and consumers separately. Semaphores do not work between consumers (or producers) since it does not provide exclusive access to individual elements. So I created a producerMutex and a consumerMutex. The reason the original blog post confused me was because he was using a single mutex, which made me think the semaphore was unnecessary. Here is my final code:</p>
<pre><code>#include <iostream>
#include <mutex>
#include <condition_variable>
#include <thread>
#include <vector>
#include <queue>
#include <unistd.h>
class Semaphore {
private:
unsigned int m_counter;
std::mutex m_mutex;
std::condition_variable m_cond;
public:
Semaphore(unsigned int counter):m_counter(counter) {
}
void P() {
std::unique_lock <std::mutex> myLock(m_mutex);
m_cond.wait(myLock, [this]() { return m_counter > 0; });
m_counter--;
}
void V() {
std::lock_guard <std::mutex> myLock(m_mutex);
m_counter++;
m_cond.notify_one();
}
};
template <typename T>
class ManyToManyBlockingQueue {
private:
unsigned int m_maxSize;
T *m_data;
Semaphore m_filledSlots;
Semaphore m_emptySlots;
unsigned int m_readLoc;
unsigned int m_writeLoc;
std::mutex m_consumerMutex;
std::mutex m_producerMutex;
public:
ManyToManyBlockingQueue(unsigned int size): m_maxSize(size), m_data(new T[size]), m_filledSlots(0), m_emptySlots(size), m_readLoc(0), m_writeLoc(0) {
}
void push(T value) {
m_emptySlots.P();
std::unique_lock <std::mutex> producerLock(m_producerMutex);
m_data[m_writeLoc++] = value;
if (m_writeLoc == m_maxSize) {
m_writeLoc = 0;
}
producerLock.unlock();
m_filledSlots.V();
}
void pop(T& value) {
m_filledSlots.P();
std::unique_lock <std::mutex>consumerLock(m_consumerMutex);
value = m_data[m_readLoc++];
if (m_readLoc == m_maxSize) {
m_readLoc = 0;
}
consumerLock.unlock();
m_emptySlots.V();
}
};
class Producer {
public:
Producer(ManyToManyBlockingQueue <int>& bq, int id):m_bq(bq), m_id(id) {
}
void operator()() {
for (int i = 0; i < 10; i++) {
m_bq.push(m_id*10+i);
}
}
private:
ManyToManyBlockingQueue<int> &m_bq;
int m_id;
};
class Consumer {
public:
Consumer(ManyToManyBlockingQueue <int>& bq, int id, std::queue <int>&output):m_bq(bq), m_id(id), m_output(output) {
}
void operator()() {
for (int i = 0; i < 50; i++) {
int value;
m_bq.pop(value);
m_output.push(value);
}
}
private:
ManyToManyBlockingQueue <int> &m_bq;
int m_id;
std::queue<int> &m_output;
};
int main() {
ManyToManyBlockingQueue <int>bq(10);
std::vector <std::thread> producerThreads;
std::vector <std::thread> consumerThreads;
std::vector <std::queue<int>> outputs;
for (int i = 0; i < 10; i++) {
producerThreads.emplace_back(Producer(bq,i));
}
for (int i = 0; i < 2; i++) {
outputs.emplace_back(std::queue<int>());
}
for (int i = 0; i < 2; i++) {
consumerThreads.emplace_back(Consumer(bq,i,outputs[i]));
}
for (std::vector <std::thread>::iterator it = producerThreads.begin();
it != producerThreads.end();
it++) {
it->join();
}
for (std::vector <std::thread>::iterator it = consumerThreads.begin();
it != consumerThreads.end();
it++) {
it->join();
}
for (std::vector <std::queue<int>>::iterator it = outputs.begin();
it != outputs.end();
it++) {
std::cout << "Number of elements: " << it->size() << " Data: ";
while(!it->empty()) {
std::cout << it->front() << " ";
it->pop();
}
std::cout << std::endl;
}
}
</code></pre>
<p>Am I doing this correctly?</p>
<p>A couple of other issues I have with this code. The pop() function bugs me. I would really like it to return the value so that the caller can use it directly instead of having to have a temp variable. However, I can't access it after I have V() the other semaphore or a producer might overwrite it. Holding the lock longer would decrease parallelism. Is this the right way to do it or there's a better way?</p>
<p>The other thing is that I was new to references in C++ as I mostly used pointers before. Originally, I allocated the output queue as I was creating the thread and I was surprised that I wasn't getting any data from the first consumer. After a lot of debugging, I finally realized that the vector moved in order to grow in size. Therefore, it seems that passing a movable object by reference is dangerous. What's the best way to solve that?</p>
<p>Another issue is how best to allow producer to signal end of data. Would a "done" counter protected by another mutex be the right way?</p>
<p>Another issue is what if one partner does not respond for a while. I can't really free the queue since there is no guarantee that the partner wouldn't come back later and write into bad memory. What's the best way to handle it and abort the operation?</p>
<p>Sorry again about the long post. Thanks for your inputs.</p>
<p>p.s. I understand semaphores can behave quite differently depends on the implementation (e.g. interrupt), this is not meant to be a production code, just to understand the concept.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T18:50:30.730",
"Id": "484406",
"Score": "0",
"body": "\"Am I doing this correctly?\" Did you test it? Does the final code work the way it should, without running into race conditions and other interlock trouble? If not, it's not ready for review. Please take a look at the [help/on-topic]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T20:51:35.410",
"Id": "484413",
"Score": "0",
"body": "@Mast Yes, I did test it, to the extend of running a bunch of tests with different queue size as well as using introducing different timings. Seems to work. I guess I am mostly interested in whether this is the right way to do it rather than whether the code is 100% perfect. For example, I am not super interested in 0 size queue since it will add more code without illustrating the concept although that is a valid test case (I did test with size 1 queue though)."
}
] |
[
{
"body": "<h1>There's too much state</h1>\n<p>Each queue has four mutexes, four counters and two condition variables. That is way too much. You could do this with just a single mutex and condition variable.</p>\n<p>In your <code>push()</code> function, you first have to hold a mutex at least once to check if there are empty slots (if not, you have to wait for a condition variable to be signalled, which means multiple calls the mutex lock and unlock functions), then you have to hold a mutex to update the write location, and then hold the mutex to increment the filled slots semaphore. Locking and unlocking a mutex, despite being quite optimized, is still not free.</p>\n<p>Another issue is the duplication of information of the state of the queue. There's <code>m_filledSlots</code>, <code>m_emptySlots</code> (which should be the inverse), and the same information is also present in the difference between the read and write locations. And you have to keep everything updated.</p>\n<p>If you just take one lock, check the read and write pointers to see how many free slots there are in the queue, wait for the condition variable if necessary, then update the read or write pointer, signal the variable if necessary, and then unlock, you have spent much less cycles than with this approach with semaphores.</p>\n<h1>Making <code>pop()</code> return the value</h1>\n<p>You can just write:</p>\n<pre><code>T pop() {\n ...\n T value = m_data[m_readLoc++];\n ...\n return value;\n}\n</code></pre>\n<p>Even though it looks like there is a temporary variable that would require an extra copy, the compiler can perform <a href=\"https://en.cppreference.com/w/cpp/language/copy_elision\" rel=\"nofollow noreferrer\">return value optimization</a> here, which is mandatory in C++17, and which most compilers have been doing already for much longer.</p>\n<h1>Pointers moving when containers grow</h1>\n<p>Indeed, a <code>std::vector</code> will move its contents in memory if it grows. However, there are other container classes that you can use that do guarantee that elements already in the container will keep their address, even if it needs to allocate more memory. Amongst them are <a href=\"https://en.cppreference.com/w/cpp/container/list\" rel=\"nofollow noreferrer\"><code>std::list</code></a> and <a href=\"https://en.cppreference.com/w/cpp/container/deque\" rel=\"nofollow noreferrer\"><code>std::deque</code></a>. There are also container adapter classes such as <a href=\"https://en.cppreference.com/w/cpp/container/queue\" rel=\"nofollow noreferrer\"><code>std::queue</code></a> that by default use a <code>std::deque</code> for storage, and thus inherit its properties.</p>\n<h1>Signalling that production ended</h1>\n<p>There are two common ways to do this. First is to add a flag variable to your blocking queue class that signals that the producers finished. This flag is set, and then the condition variable that the consumers listen for is broadcast to. Consumers should check this flag each time they want to dequeue an item. If it's set, they can terminate.</p>\n<p>The other way is to have some way to enqueue an item that signals that no more data will be coming. If your queue contains pointers to objects, enqueueing a <code>nullptr</code> might suffice. Again, the condition variable should be broadcast, and a consumer should not actually pop this item from the queue, so that other consumers also get a chance to see it. Alternatively, you have to enqueue as many of these special items as there are consumer threads.</p>\n<h1>Timeouts</h1>\n<blockquote>\n<p>Another issue is what if one partner does not respond for a while. I can't really free the queue since there is no guarantee that the partner wouldn't come back later and write into bad memory. What's the best way to handle it and abort the operation?</p>\n</blockquote>\n<p>I'm not sure what you mean by "partner". Is it a consumer or a producer thread? In any case, you can only delete the queue if no threads are left that could read or write from it. You could kill threads that don't respond in time, but it is very hard to do this in a safe way. The best way is to ensure these threads never take too much time to produce or consume an item to begin with.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-09T02:44:42.750",
"Id": "484884",
"Score": "0",
"body": "Thanks for the detailed answers. However, wouldn't have a single conditional variable make notification tricky since a producer can notify another producer instead of a consumer? NotifyAll would wake everybody up unnecessarily. Also, I think having a single mutex might lower parallelism since producers would block consumers and vice versa. If the queue is not full or empty, they shouldn't block each other."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-09T07:30:56.733",
"Id": "484892",
"Score": "0",
"body": "Yes, having two condition variables might help a little bit. But two mutexes are probably unnecessary: first, the mutex is only ever held for a brief moment, it's not held when waiting for a condition variable to be notified. Second, if the producers are waiting for consumers to free up the queue, then the consumers are obviously busy doing their stuff and not holding the lock."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-09T15:16:39.067",
"Id": "484921",
"Score": "0",
"body": "Sorry, I am not sure I understand. m_consumerMutex are only locked between consumers and m_producerMutex are only locked between producers. Thus, they need to be separated from the main mutex. The two semaphores also improve parallelism. Assuming we have two producers, one waiting for full semaphore, one waiting to update the empty semaphore, if we had one semaphore, a consumer could potentially be blocked twice. Although as you said, in practice, it may not make much differences since these locks are only held briefly, but semantically, the two counters serve different purposes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-09T20:41:14.263",
"Id": "484954",
"Score": "0",
"body": "I'm retracting my statement about two condition variables helping. Because let's look at this from another angle: can it ever happen that both producers and consumers are waiting to be notified? No, because the queue cannot be both completely empty and completely full at the same time. So either it is empty, consumers are waiting for a condition variable to be notified, and the producers do not wait but merely notify it. Or if it's full, then it's the other way around. And finally if half-full, no side is blocked."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-09T23:47:01.507",
"Id": "484967",
"Score": "0",
"body": "Hmm... The whole point of the two counters was so that we can be empty and full at the same time. Say we have 10 slots and we have 10 producers all copying data into the queue. The full counter would be full as no other producers should be able to get in, but the empty counter would be empty since no data is ready for consumption. However, on closer examination, my code does not work since I can't release the producers_mutex until I have Ved the empty semaphore, thus largely negated any parallelism gains. Maybe I have to lock the entire push/pop section?"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T23:15:48.290",
"Id": "247496",
"ParentId": "247483",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T18:28:05.997",
"Id": "247483",
"Score": "6",
"Tags": [
"c++",
"locking"
],
"Title": "Blocking Queue in C++ using semaphores"
}
|
247483
|
<p>I've written a python code for finding the distribution of the leading zeros of SHA-1. Using random inputs and hashing-then-counting. Normally it is expected to fit the <code>n/2^i</code> curve where <code>n</code> is the number of trials. After this, a plot is <a href="https://crypto.stackexchange.com/a/83227/18298">drawn</a>.</p>
<pre class="lang-py prettyprint-override"><code>import hashlib
import random
import matplotlib.pyplot as plt
leading = [0] * 160
trials = 10000000000
for i in range(trials):
randomInput= random.getrandbits(128)
hasvalue = hashlib.sha1(str(randomInput).encode('ASCII')).hexdigest()
b = bin(int(hasvalue, 16))
c= b[2:].zfill(160)
zeroes = str(c).index('1')
leading[zeroes] = leading[zeroes] + 1
</code></pre>
<p>The most time-consuming part of this code is of course the SHA-1 calculation and we cannot do something for that except parallelization with <a href="https://github.com/classner/pymp" rel="nofollow noreferrer">pymp</a> or some other library. What I'm not mostly unhappy here is the whole conversions between <code>str</code>, <code>bin</code> and back.</p>
<p>Any improvements for a cleaner code and little speed up?</p>
|
[] |
[
{
"body": "<p>Instead of <code>str(random.getrandbits(128)).encode('ASCII')</code> I'd use <code>os.urandom(16)</code>. Much simpler, ought to be more random, shorter result, and a bit faster (at least for me). Or convert your random number to <code>bytes</code> directly, even faster (at least for me):</p>\n<pre><code>>>> timeit(lambda: str(random.getrandbits(128)).encode('ASCII'))\n1.320366100000001\n>>> timeit(lambda: os.urandom(16))\n0.7796178000000111\n>>> timeit(lambda: random.getrandbits(128).to_bytes(16, 'big'))\n0.6476696999999945\n</code></pre>\n<p>From <a href=\"https://docs.python.org/3/library/os.html#os.urandom\" rel=\"nofollow noreferrer\">the doc</a>:</p>\n<blockquote>\n<p><code>os.urandom(size)</code><br />\nReturn a string of <em>size</em> random bytes suitable for cryptographic use.</p>\n</blockquote>\n<p>And to count zeros, perhaps use <code>digest()</code>, make an <code>int</code> from it and ask for its bit length:</p>\n<pre><code> hashvalue = hashlib.sha1(os.urandom(16)).digest()\n i = int.from_bytes(hashvalue, 'big')\n zeroes = 160 - i.bit_length()\n</code></pre>\n<p>Benchmark results (numbers are times, so lower=faster):</p>\n<pre><code>0.56 zeroes_you\n0.31 zeroes_me\n0.29 zeroes_me2\n0.26 zeroes_me3\n\n0.60 zeroes_you\n0.31 zeroes_me\n0.28 zeroes_me2\n0.24 zeroes_me3\n\n0.57 zeroes_you\n0.31 zeroes_me\n0.28 zeroes_me2\n0.24 zeroes_me3\n</code></pre>\n<p>Benchmark code:</p>\n<pre><code>import hashlib\nimport random\nimport os\nfrom timeit import repeat\n\ndef zeroes_you():\n randomInput= random.getrandbits(128)\n hashvalue = hashlib.sha1(str(randomInput).encode('ASCII')).hexdigest()\n b = bin(int(hashvalue, 16))\n c= b[2:].zfill(160)\n zeroes = str(c).index('1')\n\ndef zeroes_me():\n hashvalue = hashlib.sha1(os.urandom(16)).digest()\n i = int.from_bytes(hashvalue, 'big')\n zeroes = 160 - i.bit_length()\n\ndef zeroes_me2():\n randomInput = random.getrandbits(128)\n hashvalue = hashlib.sha1(randomInput.to_bytes(16, 'big')).digest()\n i = int.from_bytes(hashvalue, 'big')\n zeroes = 160 - i.bit_length()\n \ndef zeroes_me3(randbits=random.getrandbits, sha1=hashlib.sha1, int_from_bytes=int.from_bytes):\n hashvalue = sha1(randbits(128).to_bytes(16, 'big')).digest()\n zeroes = 160 - int_from_bytes(hashvalue, 'big').bit_length()\n\nfor _ in range(3):\n for zeroes in zeroes_you, zeroes_me, zeroes_me2, zeroes_me3:\n t = min(repeat(zeroes, number=100000))\n print('%.2f' % t, zeroes.__name__)\n print()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T20:51:07.590",
"Id": "484412",
"Score": "0",
"body": "One issue might be it is blockable, in this case it make the run slower. I'll test. I'm not sure that my Ubuntu has run it in block mode or not. Here an article about it; [Removing the Linux /dev/random blocking pool](https://lwn.net/Articles/808575/)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T20:59:53.723",
"Id": "484417",
"Score": "0",
"body": "As I predicted. The original code is faster. I suspect that this is due to the blocking. Run with 1000000 trials. The original one is around 2 times faster"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T21:06:45.837",
"Id": "484419",
"Score": "1",
"body": "@kelalaka I'm using Windows, `os.urandom` has always been faster for me. Note the answer update, maybe at least the second part is useful for you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T21:18:48.573",
"Id": "484421",
"Score": "1",
"body": "I think it is blocking here. `0.20 zeroes_you` and `0.34 zeroes_me` plus-minus 2 at most. with your second part, it falls to `0.13`. Nice and clean."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T21:21:47.963",
"Id": "484423",
"Score": "1",
"body": "Now with the `zeroes_me2()` it is `0.10-0.12`. So I've 2 times speed up now :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T21:35:18.963",
"Id": "484425",
"Score": "1",
"body": "Now with the `zeroes_me3()` it is `0.09-0.10`"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T20:44:57.503",
"Id": "247489",
"ParentId": "247486",
"Score": "4"
}
},
{
"body": "<p>I agree with the other answer and yourself that you should try and keep away from encoding / decoding binary values altogether. The same goes for finding the highest bit from a number; converting to a string to find a character is vastly less performant than looking for bits directly. However, that's already mentioned <a href=\"https://codereview.stackexchange.com/a/247489/9555\">in the other answer</a>, so this is just code review following up on that.</p>\n<p>I'm not sure why you would not just use <code>i</code> (formatted as a byte array) as input, I just wanted to mention that as the RNG might well be dependent on a hash, and may therefore be a bigger bottleneck than the SHA-1 hash itself. Just a small note that <code>getrandbits</code> uses the Mersenne Twister underneath, so you should get non-secure but well distributed random numbers from it (so <em>that</em> particular random number generator probably won't be a bottleneck).</p>\n<p>Since Python 3.6 you can use underscores in number literals (<code>10_000_000_000</code> is easier to distinguish as 10 billion on the short scale). Otherwise you can write it down as <code>10 * 1000 * 1000 * 1000</code> which at least makes is readable without having to manually count zeros.</p>\n<p>[EDIT] I've removed the part of <code>str</code> method adding additional characters (which it seemingly still does). For this question the encoding of the characters afterwards as ASCII seems to resolve the issue anyway. Encoding as a string and then converting back to bytes immediately after still doesn't seem to be the way to go, obviously.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T14:12:53.110",
"Id": "485503",
"Score": "0",
"body": "`10**10` might be good, too. Your paragraph about encodings doesn't make sense. In what way does `str` default to UTF-8? Do you mean `str.encode`? And that *doesn't* default to including BOM (`str(123).encode()` just gives me `b'123'`). And what do you mean with \"binary values\"? And `ascii` doesn't work, you probably mean `'ascii'`. And why ASCII? Gives the same result as UTF-8 (if it gives one at all). And the OP already *does* use ASCII, so why do you tell them?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T22:19:18.013",
"Id": "485545",
"Score": "0",
"body": "It's the `str` function itself that adds the BOM as \"characters\". OK, you are right, directly encoding afterwards may again remove the BOM. However the intermediate string, if you will look at it, will be 3 chars / bytes larger because of the BOM. Of course, first converting to characters and then to bytes again makes little sense anyway."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T22:27:55.030",
"Id": "485547",
"Score": "0",
"body": "That just sounds all wrong. How exactly do you show that difference of 3 bytes?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T22:30:26.690",
"Id": "485548",
"Score": "0",
"body": "I ran into it [on stackoverflow](https://stackoverflow.com/q/63402380/589259)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T12:28:41.123",
"Id": "485570",
"Score": "0",
"body": "About the edit: `str` doesn't add additional characters here. They're using it twice, once on an integer (producing a string of just digits and no additional characters) and once on a character string (returning that string itself, unmodified). Never on a byte string."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T11:08:45.407",
"Id": "247895",
"ParentId": "247486",
"Score": "1"
}
},
{
"body": "<blockquote>\n<p>What I'm not mostly unhappy here is the whole conversions between str, bin and back.</p>\n</blockquote>\n<p>You can avoid this by first using <code>digest()</code> (instead of <code>hexdigest()</code>) to format the digest as bytes instead of a string, then converting the bytes directly to an integer:</p>\n<pre class=\"lang-py prettyprint-override\"><code>hasvalue = hashlib.sha1(random.getrandbits(128).to_bytes(16, byteorder='big', signed=False)).digest()\nhasvalue = int.from_bytes(hasvalue, byteorder='big', signed=False)\n</code></pre>\n<p>Then you take the bitlength of that integer and subtract it from 160 (or whatever is the bitlength of the hash you're using) to get the number of leading zeroes:</p>\n<pre class=\"lang-py prettyprint-override\"><code>bitlength = 0\nwhile (hasvalue):\n hasvalue >>= 1\n bitlength += 1\nleading_zeros = 160-bitlength\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-11T23:53:49.943",
"Id": "514437",
"Score": "0",
"body": "This seems lost costlier, on average the while loop will run 159 times. Can you execute a performance as [superb rain](https://codereview.stackexchange.com/a/247489/185475) did?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-12T00:04:19.707",
"Id": "514438",
"Score": "0",
"body": "Actually I didn't even realize Python had a built-in bit_length(). My way would definitely be slower than that."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-11T23:42:17.503",
"Id": "260630",
"ParentId": "247486",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "247489",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T20:13:46.830",
"Id": "247486",
"Score": "10",
"Tags": [
"python",
"cryptography"
],
"Title": "Faster and cleaner SHA-1 leading zero histogram with Python"
}
|
247486
|
<p>I use the following code which <strong>works</strong> as expected. The code uses <code>open ID connect</code> to login user. Because I'm pretty new to node and express, it will be great if I can get some tips for the <code>async</code> usage- e.g. if I’m doing it and the <strong>error handling</strong> correctly.</p>
<p>The code is doing connect via oidc layer
<a href="https://en.wikipedia.org/wiki/OpenID_Connect" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/OpenID_Connect</a>
which does a user login according to client secret and client id, then the authorization server is calling to the <code>redirect</code> route of the application and if everything is OK the user logged in to the system.</p>
<p>This is the <strong>index.js</strong></p>
<pre><code>const express = require('express');
const logon = require('./logon');
const app = express();
const port = process.env.PORT || 4000;
logon(app)
.then(() => {
console.log('process started');
});
app.use(express.json());
app.listen(port,
() => console.log(`listening on port: ${port}`));
</code></pre>
<p>This is the l<strong>ogon.js</strong></p>
<pre><code>const { Issuer, Strategy } = require('openid-client');
const cookieParser = require('cookie-parser');
const cookieSession = require('cookie-session');
const azpi = require('./azpi');
const bodyParser = require('body-parser');
const passport = require('passport');
module.exports = async (app) => {
let oSrv;
const durl = `${process.env.srvurl}/.well-known/openid-configuration`;
try {
oSrv = await Issuer.discover(durl);
} catch (err) {
console.log('error occured', err);
return;
}
app.get('/', prs(), passport.authenticate('oidc'));
const oSrvCli = new oSrv.Client({
client_id: process.env.ci,
client_secret: process.env.cs,
token_endpoint_auth_method: 'client_secret_basic',
});
passport.serializeUser((user, done) => {
done(null, user);
});
passport.deserializeUser((obj, done) => {
done(null, obj);
});
const cfg = {
scope: 'openid',
redirect_uri: process.env.ruri,
response_type: 'code',
response_mode: 'form_post',
};
const prs = () => (req, res, next) => {
passport.use(
'oidc',
new Strategy({ oSrvCli , cfg }, (tokenset, done) => {
const claims = tokenset.claims();
const user = {
name: claims.name,
id: claims.sub,
id_token: tokenset.id_token,
};
return done(null, user);
}),
);
next();
};
app.use(
bodyParser.urlencoded({
extended: false,
}),
);
app.use(cookieParser('csec'));
app.use(
cookieSession({
name: 'zta-auth',
secret: 'csect',
}),
);
app.use(passport.initialize());
app.use(passport.session());
app.get('/redirect', async (req, res, next) => {
passport.authenticate('oidc', async (err, user) => {
if (err) {
console.log(`Authentication failed: ${err}`);
return next(err);
}
if (!user) {
return res.send('no identity');
}
req.login(user, async (e) => {
if (e) {
console.log('not able to login', e);
return next(e);
}
try {
const url = await azpi.GetUsers(user.id_token);
return res.redirect(url);
} catch (er) {
res.send(er.message);
}
});
})(req, res, next);
});
};
</code></pre>
<p>Is my async code usage is okay?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T21:42:14.497",
"Id": "484819",
"Score": "0",
"body": "The purpose of the async keyword is to be allowed to use the await keyword inside (it also has a side effect of making the return be a promise). As such, you only need to declare a function async when you want to use await. You have marked several functions (in the form of lambdas) as async when you do no awaiting inside them (you await inside a nested function, only the nested one needs to be marked async)."
}
] |
[
{
"body": "<h2>Comments</h2>\n<p>While the code is mostly simple to follow, it would be good to add comments to document what decisions you made. Even if you are the only one maintaining this code your future self might not remember what considerations you had in the past. At least document the input, output and purpose of functions. Some style guides call for comments to be in certain formats - e.g. <a href=\"https://google.github.io/styleguide/jsguide.html#jsdoc\" rel=\"nofollow noreferrer\">JSDoc in Google style guide</a>.</p>\n<h2>Nesting Levels</h2>\n<p>The nesting levels gets a bit deep towards the end of logon.js- some might describe it a bit as “callback hell”. <a href=\"http://callbackhell.com/\" rel=\"nofollow noreferrer\">callbackhell.com</a> has some good tips for keeping code shallow- like naming anonymous functions so they can be moved out (also may allow for use in unit and/or feature tests), modularize (which is already done somewhat with logon.js), etc.</p>\n<h2>Variable name format</h2>\n<p>It would be best to use consistent formatting of variable names. I have worked on a PHP codebase that makes quite extensive use of hungarian notation but I am not fond of it and I haven't seen it used very often with JavaScript code. I happened to recently see <a href=\"https://stackoverflow.com/q/111933/1575353\">this Stack Overflow question about Hungarian notation</a> and while it is marked as off-topic it does have many answers. The top voted answer contains a link to an article by Joel Spolsky, CEO and co-founder of Stack Overflow: <a href=\"http://www.joelonsoftware.com/articles/Wrong.html\" rel=\"nofollow noreferrer\"><em>Making Wrong Code Look Wrong</em></a>. I know realize that much of the code throughout that codebase is “Systems Hungarian”.</p>\n<p>It appears there are two variables named using Hungarian notation (i.e. <code>oSrv</code> and <code>oSrvCli</code>) while most all other variables are all lowercase or camelCase. There seems to be one other outlier: <code>durl</code>- which seems to be the discovery URL. One could name that as <code>discoveryURL</code>, or take the server URL/host name out of it and make it a real constant - e.g. <code>const DISCOVERY_PATH = '/.well-known/openid-configuration';</code> , which can be appended to <code>process.env.srvurl</code> when used.</p>\n<h2>Async functions</h2>\n<p>As was mentioned in a comment, the <code>async</code> keyword has likely been applied to more functions that necessary. For example, only functions that contain the <code>await</code> keyword need to be declared as asynchronous- e.g. the function assigned to <code>module.exports</code>, the callback to <code>req.login()</code>).</p>\n<h2>Error handling</h2>\n<blockquote>\n<p>By default, if authentication fails, Passport will respond with a 401 Unauthorized status, and any additional route handlers will not be invoked.<sup><a href=\"http://www.passportjs.org/docs/authenticate/\" rel=\"nofollow noreferrer\">1</a></sup></p>\n</blockquote>\n<blockquote>\n<pre><code>passport.authenticate('oidc', async (err, user) => {\n if (err) {\n console.log(`Authentication failed: ${err}`);\n return next(err);\n }\n</code></pre>\n</blockquote>\n<p>This error handling seems fine. Would it be helpful to log the <code>user</code> object in the callback to the call to <code>passport.authenticate()</code>? If so, consider sanitizing any sensitive information that may be attached. You could also consider an error logging service.</p>\n<p>It appears your code follows the <em>Custom Callback</em> option for <a href=\"http://www.passportjs.org/docs/authenticate/\" rel=\"nofollow noreferrer\"><code>passport.authenticate()</code></a>. The sample under that section <strong>Custom Callback</strong> checks for <code>err</code> and when it is anything other than <code>false</code>-y it will return <code>next(err)</code></p>\n<blockquote>\n<p>If the built-in options are not sufficient for handling an authentication request, a custom callback can be provided to allow the application to handle success or failure.</p>\n</blockquote>\n<blockquote>\n<pre><code>app.get('/login', function(req, res, next) {\n passport.authenticate('local', function(err, user, info) {\n if (err) { return next(err); }\n</code></pre>\n</blockquote>\n<blockquote>\n<p>If authentication failed, <code>user</code> will be set to false. If an exception occurred, <code>err</code> will be set. An optional <code>info</code> argument will be passed, containing additional details provided by the strategy's verify callback.</p>\n</blockquote>\n<p>It may be useful for you to read other reviews about <a href=\"https://codereview.stackexchange.com/search?tab=votes&q=%5bnode.js%5d%20%20passport\">nodeJS and passport</a> as well as <a href=\"https://codereview.stackexchange.com/questions/tagged/node.js+error-handling?tab=Votes\">nodeJS and error-handling</a>. The posts below might also be helpful:</p>\n<ul>\n<li><a href=\"https://stackoverflow.com/q/15711127/1575353\">Express Passport (node.js) error handling</a></li>\n<li><a href=\"https://stackoverflow.com/q/35452844/1575353\">How to show custom error messages using passport and express</a></li>\n</ul>\n<h2>Promisifying <code>passport.authenticate()</code></h2>\n<p><a href=\"https://stackoverflow.com/q/42382498/1575353\">This Stack overflow post</a> might be interesting if you want to use <code>await</code> with the call to <code>passport.authenticate()</code>:</p>\n<blockquote>\n<p>I've been failing to get passport.authenticate to work at all inside of an async/await or promise pattern. Here is an example I feel should work, but it fails to execute passport.authenticate().</p>\n</blockquote>\n<blockquote>\n<pre><code>const passport = require("passport");\nlet user;\ntry {\n user = await __promisifiedPassportAuthentication();\n console.log("You'll never have this ", user);\n} catch (err) {\n throw err;\n}\nfunction __promisifiedPassportAuthentication() {\n return new Promise((resolve, reject) => {\n console.log("I run");\n passport.authenticate('local', (err, user, info) => {\n if (err) reject(err);\n if (user) resolve(user);\n });\n });\n}\n</code></pre>\n</blockquote>\n<p>The <a href=\"https://stackoverflow.com/a/42383763/1575353\">self-answer</a> claims that the OP needed to invoke the function returned by the call to <code>passport.authenticate()</code> passing <code>req</code> and <code>res</code>, which likely need to get passed to <code>__promisifiedPassportAuthentication()</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-11T13:46:10.440",
"Id": "485163",
"Score": "0",
"body": "Ok, thanks! regard the async after few successful calls, somethimes I got the following error `req.session[\"oidc:accounts.rvm.com\"] is undefined` for the same user not sure why, any idea as I think its related to async usage but not sure."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-11T14:08:36.527",
"Id": "485165",
"Score": "0",
"body": "i see the error in `})(req, res, next); ` in the last statement , is it related to some aysnc issue, as the it happens once on every 5-10 successful run"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-12T11:31:07.567",
"Id": "485277",
"Score": "0",
"body": "Thanks for that passport hint, I'm using it twice could you please provide exapmle how should my code be adopted to use it like you mentiond ? it will be great"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-12T14:57:24.770",
"Id": "485291",
"Score": "0",
"body": "No need as I try it out now and I got the exact same error...any other idea? thanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-12T15:06:58.050",
"Id": "485292",
"Score": "0",
"body": "Hmm... I'm not sure because I honestly haven't used PassportJS myself. I am mostly reviewing the code and can attempt to come up with something but that isn't the point of this site."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-12T15:07:04.913",
"Id": "485294",
"Score": "0",
"body": "While I don't expect you to accept the answer, please consider voting on itl. [\"_The first thing you should do after reading someone's answer to your question is vote on the answer, like any user with sufficient reputation does. Vote up answers that are helpful, and vote down answers that give poor advice._\"](https://codereview.stackexchange.com/help/someone-answers)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-12T15:55:17.027",
"Id": "485299",
"Score": "0",
"body": "1+ why you are saying\" I don't expect you to accept the answer\" ? im trying to implement your suggestions, what I miss is currenlty the error handling ,with my context could you please add it to your answer ?How do you think I can improve it? regard the logs I've added as you suggested"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-13T07:22:54.403",
"Id": "485341",
"Score": "0",
"body": "Im just waiting to provide feedback where I can user better error handling, please provide example for `best practice` ,where I miss the error handling etc,and i'll close the question with the bounty. thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-13T23:23:18.837",
"Id": "485457",
"Score": "0",
"body": "IDK if it is sufficient but I've added more to the error handling section"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T10:40:16.250",
"Id": "485481",
"Score": "0",
"body": "Thanks,I see the code you have added for the erorr handling, Im not sure that I understand what is the different to my code , I use: ` if (err) {\n console.log(`Authentication failed: ${err}`);\n return next(err);\n }` I didnt really understand , please elborate"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T17:32:29.410",
"Id": "485527",
"Score": "0",
"body": "I give you the bounty, but please provide example in my contexts how should I use better exception handling, not general , if this was your code how would you do it better then my code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T17:37:48.353",
"Id": "485528",
"Score": "0",
"body": "It depends on what the requirements are. If you are actively watching the logs then the code would be sufficient. Otherwise if you need to be notified when an error occurs then you may need to look into an error logging service or mechanism that would notify you (e.g. via email, text, etc.)"
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-11T05:38:56.537",
"Id": "247756",
"ParentId": "247488",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T20:41:24.477",
"Id": "247488",
"Score": "5",
"Tags": [
"javascript",
"beginner",
"node.js",
"asynchronous",
"oauth"
],
"Title": "Nodejs async with express server"
}
|
247488
|
<p>I have a Spring service that calls a few methods to</p>
<pre><code>@Service
@RequiredArgsConstructor
@Slf4j
public class CarService {
private final CarRepository carRepo;
private final Mail mail;
public void syncCars(Set<CarInfo> carInfos) {
carInfos.forEach(carInfo ->
carRepo.findByCarInfo(carInfo.getId()) // returns Optional
.map(car -> updateCar(car, carInfo))
.orElseGet(() -> createCar(carInfo)));
}
public void createCar(Car car) {
// some processing code
// not shown for brevity
mail.send("Following car created " + car);
}
public void updateCar(Car car, CarInfo carInfo) {
if (car.getPrice() - carInfo.getPrice() > 1000) {
mail.send(String.format("Price for %s changed by %s", car, car.getPrice() - carInfo.getPrice());
}
// some processing code
// not shown for brevity
}
public void deleteCar(Car car) {
// some processing code
// not shown for brevity
mail.send("Following car deleted " + car);
}
}
</code></pre>
<p>Mail is a Spring component:</p>
<pre><code>@Component
@Slf4j
public class Mail {
private final JavaMailSender javaMailSender;
private final String appEmailAddress;
private final String[] adminEmailAddresses;
public Mail(JavaMailSender javaMailSender, MailProperties properties) {
this.javaMailSender = javaMailSender;
appEmailAddress = properties.getAppEmailAddress();
adminEmailAddresses = properties.getAdminEmailAddresses();
}
public void sendEmail(String bodyText) {
try {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(appEmailAddress);
message.setTo(adminEmailAddresses);
message.setSubject("Car Sync Report");
message.setText(bodyText);
javaMailSender.send(message);
} catch (MailException me) {
log.error("Unable to send message due to the following error: "
+ me.toString());
}
}
}
</code></pre>
<p>With this code, the <code>CarService</code> may send multiple emails on one call to <code>syncCars</code>. However, I would like for it to only send one email with all the messages.</p>
<p>I could create an instance field to hold the email body messages but <code>CarService</code> is a singleton and that would likely have concurrency issues. Another approach is to pass a <code>String</code> or <code>StringBuilder</code> to each method to collect the messages and then call <code>mail.send</code> at the end of the syncCars method. Is there another way to collect the messages to send in an email without passing an additional collection object to each method while avoiding concurrency issues? This seems like a cross-cutting concern here.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T21:31:15.157",
"Id": "247490",
"Score": "2",
"Tags": [
"java",
"email",
"spring",
"aspect-oriented"
],
"Title": "Collect messages from a job to send in body of one email"
}
|
247490
|
<p>Previously, I built a scraper to get ranking data for ATP # 1 over the years. See <a href="https://codereview.stackexchange.com/questions/244074/webscraping-tennis-data">Webscraping tennis data</a>, and <a href="https://codereview.stackexchange.com/questions/244195/webscraping-tennis-data-1-1?noredirect=1&lq=1">follow</a> <a href="https://codereview.stackexchange.com/questions/245010/webscraping-tennis-data-1-2-optionals-streams-callbacks?noredirect=1&lq=1">ups</a>.</p>
<p>Now, I use the data to rank the players on the basis of how many weeks they've spent at #1.</p>
<p>I'd appreciate general feedback on code style and structure. <strong>The Scraper class is unchanged, so really everything else is up for review</strong>.</p>
<hr />
<h2>Code</h2>
<p><strong>Note: if you run the code below, it'll create a directory, and a bunch of files in it.</strong></p>
<p><strong>scraper package</strong></p>
<pre><code>package scraper;
// A POJO that encapsulates a ranking week and the name of the corresponding No.1 player
public class WeeklyResult {
private final String week;
private final String playerName;
public WeeklyResult(final String week, final String playerName) {
this.week = week;
this.playerName = playerName;
}
public String getWeek() {
return week;
}
public String getPlayerName() {
return playerName;
}
}
</code></pre>
<p><em>Scraper.java</em></p>
<pre><code>package scraper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.time.Duration;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;
public class Scraper {
private static final Logger logger = LogManager.getLogger(Scraper.class);
private final String urlPrefix;
private final String urlSuffix;
private final Duration timeout;
private final int totalTries;
private WeeklyResult latestResult;
public Scraper(final String urlPrefix, final String urlSuffix, final Duration timeout, final int totalTries) {
this.urlPrefix = urlPrefix;
this.urlSuffix = urlSuffix;
this.timeout = timeout;
this.totalTries = totalTries;
this.latestResult = new WeeklyResult("1973-08-16", "N/A");
}
public WeeklyResult scrape(final String week) throws ScraperException {
// in the case the latest scraped data returns an "empty" weekly result, simply retain the latest No.1
// since it is likely he wouldn't have changed. A weekly result is deemed empty if no player or week info
// can be found on the ATP page.
this.latestResult = scrapeWeekly(week)
.orElse(new WeeklyResult(updateLatestWeekByOne(), this.latestResult.getPlayerName()));
return this.latestResult;
}
private Optional<WeeklyResult> scrapeWeekly(final String week) throws ScraperException {
final Document document = loadDocument(weeklyResultUrl(week));
final boolean numberOneDataExists = selectNumberOneRankCell(document).isPresent();
final Element playerCell = numberOneDataExists ? selectPlayerCellElement(document) : null;
return Optional.ofNullable(playerCell)
.map(element -> new WeeklyResult(week, element.text()));
}
public List<String> loadWeeks() throws ScraperException {
final Document document = loadDocument(urlPrefix);
final Elements elements = selectRankingWeeksElements(document);
final List<String> weeks = extractWeeks(elements);
return noEmptyElseThrow(weeks);
}
private Document loadDocument(final String url) throws ScraperException {
for (int tries = 0; tries < this.totalTries; tries++) {
try {
return Jsoup.connect(url).timeout((int) timeout.toMillis()).get();
} catch (IOException e) {
if (tries == this.totalTries) {
throw new ScraperException("Error loading ATP website: ", e);
}
}
}
return null;
}
private static Elements selectRankingWeeksElements(final Document document) {
// extract ranking weeks from the dropdown menu
final Elements result = document.getElementsByAttributeValue("data-value", "rankDate")
.select("ul li");
Collections.reverse(result);
return result;
}
private static List<String> extractWeeks(final Collection<Element> elements) {
// refer to https://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/
// and https://www.baeldung.com/java-maps-streams.
return elements.stream()
.map(Scraper::extractWeek)
.collect(Collectors.toList());
}
private static List<String> noEmptyElseThrow(final List<String> weeks) throws ScraperException {
if (weeks.isEmpty()) {
throw new ScraperException("Cannot process empty data from the weeks calendar!");
} else {
return weeks;
}
}
private String weeklyResultUrl(final String week) {
return urlPrefix + "rankDate=" + week + urlSuffix;
}
private static Optional<Element> selectNumberOneRankCell(final Document document) {
final Element rankCell = selectPlayerRankCell(document);
return Optional.ofNullable(rankCell).filter(element -> numberOneRankCellExists(element));
}
private static Element selectPlayerCellElement(final Document document) {
return document.getElementsByClass("player-cell").first();
}
private static boolean numberOneRankCellExists(final Element rankCell) {
return rankCell.text().equals("1");
}
private static Element selectPlayerRankCell(final Document document) {
return document.getElementsByClass("rank-cell").first();
}
private static String extractWeek(final Element li) {
return li.text().replaceAll("\\.", "-");
}
private String updateLatestWeekByOne() {
return LocalDate.parse(this.latestResult.getWeek()).plusWeeks(1).toString();
}
}
</code></pre>
<p><em>ScraperException.java</em></p>
<pre><code>package scraper;
public class ScraperException extends Exception {
final String message;
public ScraperException (String message) {
this.message = message;
}
public ScraperException (String message, Throwable cause) {
super(cause);
this.message = message;
}
@Override
public String toString() {
return this.message;
}
}
</code></pre>
<p><strong>rankallocator package</strong></p>
<p><em>RankAllocator.java</em></p>
<pre><code>package rankallocator;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.config.Configurator;
import scraper.WeeklyResult;
import java.util.*;
import java.util.stream.Collectors;
// This class combines all the collective actions of parsing a weekly result
// and generating a weekly ranking of the No1 players for a given week.
public class RankAllocator {
private static final Logger logger = LogManager.getLogger(RankAllocator.class);
private final PlayerScoring trackScores;
private final int top_N; // display the top-N players for Weekly rankings.
public RankAllocator(final int N) {
this.top_N = N;
this.trackScores = new PlayerScoring();
}
public PlayerScoring getTrackScores() { return this.trackScores; }
private void updatePlayerScore(final WeeklyResult weeklyResult) {
// given a weekly result, update the trackScores hashmap
this.trackScores.updatePlayerValue(weeklyResult.getWeek(), weeklyResult.getPlayerName());
}
private List<PlayerRank> collatePlayerScores() {
// for each entry in trackScores, construct a new PlayerRank
// then return a list sorted in descending order by PlayerValue
List<PlayerRank> ranks =
(trackScores.getPlayerScorer().entrySet().stream()
.map(entry -> new PlayerRank(entry.getKey(), entry.getValue())))
.sorted(Comparator.comparingInt((PlayerRank player) ->
player.getCurrentValue().getWeeksAtNumberOne()).reversed() //get descending order by weeks @ No.1
.thenComparing(player -> player.getCurrentValue().getFirstReached())) //break ties based on who reached earlier
.collect(Collectors.toList());
return ranks;
}
public WeeklyRanking rank (final WeeklyResult weeklyResult) {
Configurator.setLevel(logger.getName(), Level.ERROR);
updatePlayerScore(weeklyResult);
logger.debug(this.trackScores.getPlayerScorer());
List<PlayerRank> weeklyScores = collatePlayerScores();
return new WeeklyRanking(weeklyResult.getWeek(), weeklyScores, this.top_N);
}
}
</code></pre>
<p><em>PlayerValue.java</em></p>
<pre><code>package rankallocator;
// POJO class to hold the "score" of a player,
// which consists of the weeks they've spent at No.1,
// and the week they first attained No.1 (to break ties deterministically)
public class PlayerValue {
private final String firstReached;
private int weeksAtNumberOne;
public PlayerValue(final String week) {
this.firstReached = week;
this.weeksAtNumberOne = 1;
}
public int getWeeksAtNumberOne() {
return weeksAtNumberOne;
}
public String getFirstReached() {
return firstReached;
}
public void updateWeeksAtNumberOne() {
this.weeksAtNumberOne++;
}
}
</code></pre>
<p><em>PlayerScoring.java</em></p>
<pre><code>package rankallocator;
// A wrapper class that uses a hashmap and additional metadata to maintain the
// score of each No.1 player. The score is maintained using the PlayerValue abstraction
import java.util.HashMap;
import java.util.Map;
public class PlayerScoring {
private Map<String, PlayerValue> playerScorer;
public PlayerScoring() {
playerScorer = new HashMap<>();
}
public Map<String, PlayerValue> getPlayerScorer() {
return playerScorer;
}
public PlayerValue findPlayerValue(final String player) {
return this.playerScorer.get(player);
}
public void updatePlayerValue (final String week, final String player) {
// if the player is a new No.1, construct a new entry
// otherwise, update (by one) his week tally
if (!this.playerScorer.containsKey(player)) {
this.playerScorer.put(player, new PlayerValue(week));
} else {
// Test to make sure values are updated properly
this.playerScorer.get(player).updateWeeksAtNumberOne();
}
}
}
</code></pre>
<p><em>PlayerRank.java</em></p>
<pre><code>package rankallocator;
//POJO coupling playerName and PlayerValue passed in to a WeeklyRanking's PriorityQueue.
public class PlayerRank {
private final String playerName;
private final PlayerValue currentValue;
public PlayerRank(final String name, final PlayerValue value) {
this.playerName = name;
this.currentValue = value;
}
public String getPlayerName() { return playerName; }
public PlayerValue getCurrentValue() { return currentValue; }
}
</code></pre>
<p><em>WeeklyRanking.java</em></p>
<pre><code>package rankallocator;
// Given a specific week, this class builds a
// list of the top ten (or the size of the queue, if lesser)
// players for that week
import java.util.ArrayList;
import java.util.List;
public class WeeklyRanking {
private final String week;
private final List<PlayerRank> ranks;
public WeeklyRanking(final String week, final List<PlayerRank> playerRanks, final int N) {
this.week = week;
// construct a list of the top N (max) players based on weeks at No.1
this.ranks = new ArrayList<>();
for (PlayerRank rank : playerRanks) {
this.ranks.add(rank);
if (this.ranks.size() == N) {
break;
}
}
}
public String getWeek() { return week; }
public List<PlayerRank> getRanks() { return ranks; }
}
</code></pre>
<p><strong>legacyvisualizer package</strong></p>
<p><em>LegacyVisualizer.java</em></p>
<pre><code>package legacyvisualizer;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.config.Configurator;
import rankallocator.PlayerRank;
import rankallocator.WeeklyRanking;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
// A class to write out a list of the "GOAT" status for each week.
public class LegacyVisualizer {
private final String dirName;
private static final Logger logger = LogManager.getLogger(LegacyVisualizer.class);
public LegacyVisualizer(final String path) {
this.dirName = path;
File dir = new File(dirName);
if (!dir.exists()) {
dir.mkdir();
}
}
private void createListFile(WeeklyRanking weeklyRanking) throws IOException {
List<String> lines = generateLegacyList(weeklyRanking);
Path file = Paths.get(dirName + "/" + weeklyRanking.getWeek()+".txt");
Files.write(file, lines, StandardCharsets.UTF_8);
}
private static List<String> generateLegacyList (WeeklyRanking weeklyRanking) {
final List<PlayerRank> ranks = weeklyRanking.getRanks();
List<String> lines = new ArrayList<>();
lines.add("Rank\t\tPlayer\t\tWeeks At #1\t\tFirst Reached On");
for (int i = 0; i < ranks.size(); i++) {
final String player = ranks.get(i).getPlayerName();
final int weeksTally = ranks.get(i).getCurrentValue().getWeeksAtNumberOne();
final String firstReached = ranks.get(i).getCurrentValue().getFirstReached();
final String line = Integer.toString(i+1) + "." + "\t\t" + player + "\t\t" + Integer.toString(weeksTally) + "\t\t" + firstReached;
lines.add(line);
}
return lines;
}
public void visualize(final WeeklyRanking weeklyRanking) {
// create a file for that week. No need to check if that file
// for the week exists - if we are retrying, it's probably due to a valid
// reason (timeout, re-running the visualization etc) and the data we get
// is at least the same or newer than the previous try,
// so overwriting the exist file would be fine.
Configurator.setLevel(logger.getName(), Level.DEBUG);
try {
createListFile(weeklyRanking);
} catch (IOException e) {
System.out.println("Failed to create file. " + e);
}
}
}
</code></pre>
<p><strong>Main package</strong></p>
<pre><code>package project;
import legacyvisualizer.LegacyVisualizer;
import rankallocator.RankAllocator;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.config.Configurator;
import rankallocator.WeeklyRanking;
import scraper.Scraper;
import scraper.ScraperException;
import scraper.WeeklyResult;
import java.time.Duration;
import java.util.List;
// Main class to manage the visualization of player's legacy rankings
public class Project {
private static final Logger logger = LogManager.getRootLogger();
private static final RankAllocator allocator = new RankAllocator(5);
private static final String dirName = System.getProperty("user.dir")+"/legacy";
private static final LegacyVisualizer visualizer = new LegacyVisualizer(dirName);
private static void generateRankingAllocation(WeeklyResult weeklyResult) {
// pass the scraped result to the next stage of the visualization logic.
logger.debug("Week: " + weeklyResult.getWeek() + " No.1: " + weeklyResult.getPlayerName());
WeeklyRanking weeklyRanking = allocator.rank(weeklyResult);
visualizer.visualize(weeklyRanking);
}
public static void main(String[] args) {
Configurator.setRootLevel(Level.INFO);
final Scraper scraper =
new Scraper("https://www.atptour.com/en/rankings/singles?",
"&rankRange=0-100", Duration.ofSeconds(90), 3);
// The flow is as follows: scrape the latest weekly results (starting from 1973),
// then pass it to the ranking logic (IPR). Rinse and repeat
try {
final List<String> weeks = scraper.loadWeeks();
for (String week : weeks) {
logger.debug(week);
WeeklyResult weeklyResult = scraper.scrape(week);
generateRankingAllocation(weeklyResult);
}
} catch (ScraperException e) {
logger.error(e.toString());
}
}
}
</code></pre>
<hr />
<h2>Testing</h2>
<p><em>RankingTests.java</em></p>
<pre><code>package ranking;
import junit.framework.TestSuite;
public class RankingTests {
public static TestSuite suite() {
TestSuite rankTest = new TestSuite("Generation of Accurate Weekly Rankings Suite");
rankTest.addTestSuite(TrackScoresTest.class);
rankTest.addTestSuite(WeeklyRankTest.class);
return rankTest;
}
}
</code></pre>
<p><em>TrackScoresTest.java</em></p>
<pre><code>package ranking;
import rankallocator.RankAllocator;
import junit.framework.TestCase;
import org.junit.Test;
import scraper.WeeklyResult;
import java.util.ArrayList;
import java.util.List;
/** Given a series of WeeklyResults, ensure that the tracking/updating of
* player's scores (given be a PlayerValue type) is achieved correctly.
* This class will test the classes PlayerScoring and PlayerValue for the following:
* 1) That the hashmap is correctly initializing scores for new No.1s
* 2) That the hashmap is updating the player values when a No.1 retains his position
* 3) That the hashmap's PlayerValues can be used to deterministically break a tie
* between players with the same tally, by favouring the player who reached No.1 earlier.
*/
public class TrackScoresTest extends TestCase {
private RankAllocator allocator;
private List<WeeklyResult> weeklyResults;
public void setUp() {
this.allocator = new RankAllocator(5);
weeklyResults = setupResults();
for (WeeklyResult weeklyResult : weeklyResults) {
allocator.rank(weeklyResult);
}
}
private List<WeeklyResult> setupResults() {
List<WeeklyResult> results = new ArrayList<>();
results.add(new WeeklyResult("2000-11-06", "Pete Sampras"));
results.add(new WeeklyResult("2000-11-13", "Pete Sampras"));
results.add(new WeeklyResult("2000-11-20", "Marat Safin"));
results.add(new WeeklyResult("2000-11-27", "Marat Safin"));
results.add(new WeeklyResult("2000-12-04", "Gustavo Kuerten"));
return results;
}
public void tearDown() {
}
@Test
public void testTotalTallies() {
assertEquals(allocator.getTrackScores().findPlayerValue("Pete Sampras").getWeeksAtNumberOne(), 2);
assertEquals(allocator.getTrackScores().findPlayerValue("Marat Safin").getWeeksAtNumberOne(), 2);
assertEquals(allocator.getTrackScores().findPlayerValue("Gustavo Kuerten").getWeeksAtNumberOne(), 1);
}
@Test
public void testFirstReached() {
assertEquals(allocator.getTrackScores().findPlayerValue("Pete Sampras").getFirstReached(), "2000-11-06");
assertFalse(allocator.getTrackScores().findPlayerValue("Marat Safin").getFirstReached().equals("2000-11-27"));
}
@Test
public void testNewNumberOne() {
assertEquals(allocator.getTrackScores().findPlayerValue("Gustavo Kuerten").getFirstReached(), "2000-12-04");
assertEquals(allocator.getTrackScores().findPlayerValue("Gustavo Kuerten").getWeeksAtNumberOne(), 1);
}
}
</code></pre>
<p><em>WeeklyRankTest.java</em></p>
<pre><code>package ranking;
// Test class to see that players get properly ranked.
// Note that since we are counting tallies on
// a weekly basis, it is impossible for players to "jump"
// over the other. i.e. if Sam was ranked 3rd by weeks at No.1,
// he has to become 2nd and then become 1st.
// This means that we only need to test for the following cases:
// 1. Players are being ranked *in descending order* by total weeks at No.1
// 2. Ties are broken by using the week first reached
// 3. Weekly Ranking top-N lists are generated correctly when a) len(list) < N and b) >= N.
// 4. When len(list) >= N, changes in the Nth ranked player are reflected correctly.
import junit.framework.TestCase;
import org.junit.Test;
import rankallocator.RankAllocator;
import rankallocator.WeeklyRanking;
import scraper.WeeklyResult;
import java.util.ArrayList;
import java.util.List;
public class WeeklyRankTest extends TestCase {
private RankAllocator allocator;
private List<WeeklyResult> weeklyResults;
private List<WeeklyRanking> weeklyRankings;
public void setUp() {
this.allocator = new RankAllocator(3);
this.weeklyResults = setUpInitialResults();
this.weeklyRankings = new ArrayList<>();
for (WeeklyResult weeklyResult : weeklyResults) {
weeklyRankings.add(allocator.rank(weeklyResult));
}
}
private List<WeeklyResult> setUpInitialResults() {
List<WeeklyResult> results = new ArrayList<>();
results.add(new WeeklyResult("1", "Max"));
results.add(new WeeklyResult("2", "James"));
results.add(new WeeklyResult("3", "Max"));
results.add(new WeeklyResult("4", "Max"));
results.add(new WeeklyResult("5", "James"));
return results;
}
public void tearDown() {
}
@Test
public void testRankingOrderAndLessThanN() {
// Cases 1, 2 & 3a).
// We'll show the list as [<week, <name, PlayerValue>>]
// After setup:
// check Max is ranked 1 for all weeks,
for (WeeklyRanking ranking : weeklyRankings) {
assertEquals(ranking.getRanks().get(0).getPlayerName(), "Max");
}
final int numWeeks = weeklyRankings.size();
final WeeklyRanking fifthWeekRanking = weeklyRankings.get(numWeeks-1);
// check weeks have been assigned correctly to weekly ranking
assertEquals(fifthWeekRanking.getWeek(), "5");
assertEquals(fifthWeekRanking.getRanks().size(), 2);
// check Max and James' tallies after week 5 to be 3 and 2.
assertEquals(fifthWeekRanking.getRanks().get(0).getCurrentValue().getWeeksAtNumberOne(), 3);
assertEquals(fifthWeekRanking.getRanks().get(1).getPlayerName(), "James");
assertEquals(fifthWeekRanking.getRanks().get(1).getCurrentValue().getFirstReached(), "2");
assertEquals(fifthWeekRanking.getRanks().get(1).getCurrentValue().getWeeksAtNumberOne(), 2);
}
@Test
public void testNPlusPlayers() {
// Case 3 b) & Case 4
// Populate with more weekly results and rankings
populateWithN();
}
private void populateWithN() {
weeklyResults.add(new WeeklyResult("6", "Will"));
weeklyResults.add(new WeeklyResult("7", "Mark"));
weeklyResults.add(new WeeklyResult("8", "Mark"));
for (WeeklyResult result : weeklyResults.subList(5, weeklyResults.size())) {
weeklyRankings.add(allocator.rank(result));
}
assertEquals(weeklyRankings.size(), 8);
// for week 7, Will should be number 3 with 1 week at No.1.
final WeeklyRanking seventhWeekRanking = weeklyRankings.get(6);
assertEquals(seventhWeekRanking.getRanks().get(2).getPlayerName(), "Will");
assertEquals(seventhWeekRanking.getRanks().get(2).getCurrentValue().getFirstReached(), "6");
assertEquals(seventhWeekRanking.getRanks().get(2).getCurrentValue().getWeeksAtNumberOne(), 1);
// for week 8, Mark should be number 3, but have the same weeks tally as James
final WeeklyRanking eighthWeekRanking = weeklyRankings.get(7);
assertEquals(eighthWeekRanking.getRanks().get(2).getPlayerName(), "Mark");
assertEquals(eighthWeekRanking.getRanks().get(2).getCurrentValue().getWeeksAtNumberOne(),
eighthWeekRanking.getRanks().get(1).getCurrentValue().getWeeksAtNumberOne());
}
}
</code></pre>
<hr />
<p>Based on the testing, I'm inclined to say my code achieves what I wanted. <em>Is there a better way to do so?</em></p>
<p>One think I'm considering is refactoring the main class, because currently I have a convoluted structure where I scrape and then pass it to rank allocation, and pass that to visualization, and so on. Is there a way to clean that up?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T22:06:05.337",
"Id": "247492",
"Score": "2",
"Tags": [
"java"
],
"Title": "Ranking Tennis No.1s"
}
|
247492
|
<p>When I first tried to implement <code>std::function</code> I thought it would as easy as creating a class that holds a function pointer. Consequently, I quickly figured out that I was wrong when I tried to use it with a capturing lambda and got an error message. As a result, I quit and until recently I wondered how <code>std::function</code> was implemented. However, that was when I found out about type erasure and realized that's how <code>std::function</code> is probably implemented. Which caused me to have a second attempt at recreating it.</p>
<p>Here is the code:<code>functional.hh</code></p>
<pre><code>#ifndef FUNCTIONAL_HH
#define FUNCTIONAL_HH
#include <utility>
#include <new>
namespace turtle
{
class bad_function_call : public std::exception
{
public:
bad_function_call() noexcept = default;
char const virtual *what() noexcept
{
return "bad function call";
}
};
namespace detail
{
template<typename>
bool constexpr is_reference_wrapper_v = false;
template<typename U>
bool constexpr is_reference_wrapper_v<std::reference_wrapper<U>> = true;
template<typename T, typename Type, typename T1, typename... Args>
decltype(auto) constexpr INVOKE(Type T::* f, T1 &&t1, Args &&... args)
{
if constexpr (std::is_member_function_pointer_v<decltype(f)>)
{
if constexpr (std::is_base_of_v<T, std::decay_t<T1>>)
return (std::forward<T1>(t1).*f)(std::forward<Args>(args)...);
else if constexpr (is_reference_wrapper_v<std::decay_t<T1>>)
return (t1.get().*f)(std::forward<Args>(args)...);
else
return ((*std::forward<T1>(t1)).*f)(std::forward<Args>(args)...);
}
else
{
static_assert(std::is_member_object_pointer_v<decltype(f)>);
static_assert(sizeof...(args) == 0);
if constexpr (std::is_base_of_v<T, std::decay_t<T1>>)
return std::forward<T1>(t1).*f;
else if constexpr (is_reference_wrapper_v<std::decay_t<T1>>)
return t1.get().*f;
else
return (*std::forward<T1>(t1)).*f;
}
}
template<typename F, typename... Args>
decltype(auto) constexpr INVOKE(F &&f, Args &&... args)
{
return std::forward<F>(f)(std::forward<Args>(args)...);
}
} /* namespace detail */
template<typename>
class function;
template<typename R, typename... Args>
class function<R(Args...)>
{
private:
union storage_union
{
using stack_storage_t = std::aligned_storage_t<sizeof(void *) * 3, alignof(void *)>;
void *dynamic;
stack_storage_t stack;
};
struct vtable_t
{
R (*invoke)(storage_union &storage, Args &&... args);
void (*copy)(storage_union &dest, storage_union const &src);
void (*move)(storage_union &dest, storage_union &src) noexcept;
void (*swap)(storage_union &lhs, storage_union &rhs) noexcept;
void (*destroy)(storage_union &storage) noexcept;
std::type_info const &(*type)() noexcept;
};
template<typename T>
struct vtable_dynamic_t
{
R static invoke(storage_union &storage, Args &&... args)
{ return detail::INVOKE(*reinterpret_cast<T *>(storage.dynamic), std::forward<Args>(args)...); }
void static copy(storage_union &dest, storage_union const &src)
{ dest.dynamic = new T(*reinterpret_cast<const T *>(src.dynamic)); }
void static move(storage_union &dest, storage_union &src) noexcept
{
dest.dynamic = src.dynamic;
src.dynamic = nullptr;
}
void static swap(storage_union &lhs, storage_union &rhs) noexcept
{ std::swap(lhs.dynamic, rhs.dynamic); }
void static destroy(storage_union &storage) noexcept
{ delete reinterpret_cast<T *>(storage.dynamic); }
std::type_info static const &type() noexcept
{ return typeid(T); }
};
template<typename T>
struct vtable_stack_t
{
R static invoke(storage_union &storage, Args &&... args)
{ return detail::INVOKE(reinterpret_cast<T &>(storage.stack), std::forward<Args>(args)...); }
void static copy(storage_union &dest, storage_union const &src)
{ new(&dest.stack) T(reinterpret_cast<const T &>(src.stack)); }
void static move(storage_union &dest, storage_union &src) noexcept
{
new(&dest.stack) T(std::move(reinterpret_cast<T &>(src.stack)));
destroy(src);
}
void static swap(storage_union &lhs, storage_union &rhs) noexcept
{
storage_union tmp_storage;
move(tmp_storage, rhs);
move(rhs, lhs);
move(lhs, tmp_storage);
}
void static destroy(storage_union &storage) noexcept
{ reinterpret_cast<T *>(&storage.stack)->~T(); }
std::type_info const static &type() noexcept
{ return typeid(T); }
};
template<typename T>
bool constexpr static requires_allocation = !(std::is_nothrow_move_constructible_v<T>
&& sizeof(T) <= sizeof(typename storage_union::stack_storage_t)
&&
alignof(T) <= alignof(typename storage_union::stack_storage_t));
template<typename T>
vtable_t static *vtable_for_type()
{
using VTable = std::conditional_t<requires_allocation<T>, vtable_dynamic_t<T>, vtable_stack_t<T>>;
vtable_t static vtable{
VTable::invoke,
VTable::copy,
VTable::move,
VTable::swap,
VTable::destroy,
VTable::type
};
return &vtable;
}
public:
function() noexcept = default;
function(std::nullptr_t) noexcept
{}
function(function const &other)
: M_VTable(other.M_VTable)
{
if (M_VTable != nullptr)
{
M_VTable->copy(M_Storage, other.M_Storage);
}
}
function(function &&other) noexcept
: M_VTable(other.M_VTable)
{
if (M_VTable != nullptr)
{
M_VTable->move(M_Storage, other.M_Storage);
other.M_VTable = nullptr;
}
}
template<typename F>
function(F f) : M_VTable(vtable_for_type<F>())
{
if constexpr(requires_allocation<F>)
{
M_Storage.dynamic = new F(std::move(f));
}
else
{
new(&M_Storage.stack) F(std::move(f));
}
}
~function()
{
/* if we hold a function */
if (M_VTable != nullptr)
{
M_VTable->destroy(M_Storage);
}
}
function &operator=(function const &other)
{
function(other).swap(*this);
return *this;
}
function &operator=(function &&other)
{
function(std::move(other)).swap(*this);
return *this;
}
function &operator=(std::nullptr_t) noexcept
{
/* destroy functor */
M_VTable->destroy(M_Storage);
return *this;
}
template<typename F>
function &operator=(F &&f)
{
function(std::forward<F>(f)).swap(*this);
return *this;
}
template<typename F>
function &operator=(std::reference_wrapper<F> f) noexcept
{
function(f).swap(*this);
return *this;
}
explicit operator bool() const noexcept
{ return M_VTable != nullptr; }
void swap(function &other)
{
/* if we hold the same functor type */
if (M_VTable == other.M_VTable)
{
if (M_VTable != nullptr)
M_VTable->swap(M_Storage, other.M_Storage);
}
else
{
function tmp_function(std::move(other));
/* move *this to other */
other.M_VTable = M_VTable;
if (other.M_VTable != nullptr)
{
other.M_VTable->move(other.M_Storage, M_Storage);
}
/* move tmp_function(previous other) to *this */
M_VTable = tmp_function.M_VTable;
if (M_VTable != nullptr)
{
M_VTable->move(M_Storage, tmp_function.M_Storage);
tmp_function.M_VTable = nullptr;
(void)(tmp_function.M_VTable);
}
}
}
R operator()(Args... args) const /* why const ? */
{
/* make sure we hold a functor */
if (M_VTable != nullptr)
{
return M_VTable->invoke(M_Storage, std::forward<Args>(args)...);
}
else
{
throw bad_function_call{};
}
}
std::type_info const &target_type() const noexcept
{
return M_VTable != nullptr ? M_VTable->type() : typeid(void);
}
template<typename T>
T *target() noexcept
{
return typeid(T) == M_VTable->type() ? requires_allocation<std::decay_t<T>>
? reinterpret_cast<T *>(M_Storage.dynamic) :
reinterpret_cast<T *>(&M_Storage.stack) : nullptr;
}
template<typename T>
T const *target() const noexcept
{
return typeid(T) == M_VTable->type() ? requires_allocation<std::decay_t<T>>
? reinterpret_cast<const T *>(M_Storage.dynamic) :
reinterpret_cast<const T *>(&M_Storage.stack) : nullptr;
}
private:
mutable storage_union M_Storage;
vtable_t *M_VTable = nullptr;
};
template<typename R, typename... Args>
bool operator==(function<R(Args...)> const &f, std::nullptr_t) noexcept
{
return !static_cast<bool>(f);
}
namespace detail
{
template<typename>
struct function_guide_helper
{ };
template<typename R, typename Class, bool NoExcept, typename... Args>
struct function_guide_helper<
R (Class::*) (Args...) noexcept(NoExcept)
>
{ using type = R(Args...); };
template<typename R, typename Class, bool NoExcept, typename... Args>
struct function_guide_helper<
R (Class::*) (Args...) & noexcept(NoExcept)
>
{ using type = R(Args...); };
template<typename R, typename Class, bool NoExcept, typename... Args>
struct function_guide_helper<
R (Class::*) (Args...) const noexcept(NoExcept)
>
{ using type = R(Args...); };
}
/* deduction guides */
template<typename R, typename... ArgsTypes>
function(R(*)(ArgsTypes...)) -> function<R(ArgsTypes...)>;
template<typename F,
typename FunctionType =
typename detail::function_guide_helper<decltype(&F::operator())>::type>
function(F) -> function<FunctionType>;
}
#endif /* FUNCTIONAL_HH */
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T22:40:02.387",
"Id": "484431",
"Score": "5",
"body": "Do you also have a test driver? Ideally automated unit tests."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T22:47:20.107",
"Id": "484432",
"Score": "0",
"body": "No, I do not have a test driver."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T05:54:20.120",
"Id": "484713",
"Score": "2",
"body": "FYI: I wrote the same thing [last year](https://codereview.stackexchange.com/q/221921/188857); my implementation and the reviews might be of help."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T22:15:00.460",
"Id": "247493",
"Score": "7",
"Tags": [
"c++",
"reinventing-the-wheel"
],
"Title": "c++ std::function implementation"
}
|
247493
|
<p>Purpose. Provides a background task queue so that code can ask for a function to be run at a specified point in the future. They indicate what to run (a closure) and when to run it (also a name just used for tracing). My use case is typically 2-3 items queued at any time, typical items are very fast (think read 100 bytes from a disk). Typically the executions are between 10 and 500ms in the future. It is used for the async IO subsystem in my PDP11 emulator I am porting from c++</p>
<p>The client receives a handle that they can query to see if their task is finished. They can also wait for it to finish.</p>
<p>I posted my first version and got an excellent review and have almost totally recoded it and stolen the notification handle mechanism from the reviewer too. Original Review <a href="https://codereview.stackexchange.com/questions/247327/port-of-my-c-timer-queue-to-rust">port of my c++ timer queue to rust</a></p>
<p>Here is the code</p>
<pre><code>use log::trace;
use std::cmp::Ordering;
use std::collections::BinaryHeap;
use std::sync::mpsc;
use std::sync::mpsc::RecvTimeoutError::{Disconnected, Timeout};
use std::sync::mpsc::{Receiver, Sender};
use std::sync::{Arc, Condvar, Mutex};
use std::thread;
use std::thread::JoinHandle;
use std::time::{Duration, Instant};
pub struct TimerQueue {
jh: Option<JoinHandle<()>>,
tx: Sender<QueueInstruction>,
}
type TQIFunc = fn() -> ();
#[derive(Debug)]
struct TimerQueueItem {
when: Instant, // when it should run
name: String, // for trace only
what: TQIFunc, // what to run
handle: TimerQueueHandle,
}
#[derive(Clone, Debug)]
pub struct TimerQueueHandle {
handle: Arc<(Mutex<bool>, Condvar)>,
}
impl TimerQueueHandle {
fn new() -> Self {
Self {
handle: Arc::new((Mutex::new(false), Condvar::new())),
}
}
pub fn wait(&self) {
let (lock, cv) = &*self.handle;
let mut finished = lock.lock().unwrap();
while !*finished {
finished = cv.wait(finished).unwrap();
}
}
pub fn finished(&self) -> bool {
let (lock, _cv) = &*self.handle;
let finished = lock.lock().unwrap();
*finished
}
fn signal(&self) {
let (lock, cv) = &*self.handle;
let mut finished = lock.lock().unwrap();
*finished = true;
cv.notify_all();
}
}
enum QueueInstruction {
Do(TimerQueueItem),
Stop,
}
// all these Trait impls are required so that binaryheap can sort on due time
// ====================================================
impl Ord for TimerQueueItem {
fn cmp(&self, other: &TimerQueueItem) -> Ordering {
other.when.cmp(&self.when)
}
}
impl PartialOrd for TimerQueueItem {
fn partial_cmp(&self, other: &TimerQueueItem) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for TimerQueueItem {
fn eq(&self, other: &Self) -> bool {
self.when == other.when
}
}
impl Eq for TimerQueueItem {}
// ====================================================
enum GetItemResult {
Timeout,
Stop,
NewItem(TimerQueueItem),
}
// either we got a new tqi, were told to stop or timed out
// timeout indicates that we need to (probably ) run the top of the queue
// called in one of 2 ways - duration == 0 , wait forever, duration != 0, wait that long
// maybe should be an option
fn get_item(rx: &Receiver<QueueInstruction>, wait: Duration) -> GetItemResult {
let mut stop = false;
let mut timeout = false;
let mut qinst = QueueInstruction::Stop; // init to something
if wait == Duration::from_secs(0) {
match rx.recv() {
Ok(qinstx) => qinst = qinstx,
Err(_) => stop = true,
};
} else {
match rx.recv_timeout(wait) {
Ok(qinstx) => qinst = qinstx,
Err(e) => match e {
Timeout => timeout = true,
Disconnected => stop = true,
},
};
}
if stop {
GetItemResult::Stop
} else if timeout {
GetItemResult::Timeout
} else {
match qinst {
QueueInstruction::Do(tqi) => {
trace!(target:"TimerQueue","got item {}", tqi.name);
GetItemResult::NewItem(tqi)
}
QueueInstruction::Stop => {
trace!("got stop request");
GetItemResult::Stop
}
}
}
}
impl TimerQueue {
pub fn new() -> TimerQueue {
let (tx, rx): (Sender<QueueInstruction>, Receiver<QueueInstruction>) = mpsc::channel();
let jh = thread::spawn(move || {
let mut queue: BinaryHeap<TimerQueueItem> = BinaryHeap::new();
let mut stop = false;
loop {
if queue.len() == 0 {
if stop {
break;
}
match get_item(&rx, Duration::from_secs(0)) {
GetItemResult::Stop => {
break; // no work and a request to stop - so stop
}
GetItemResult::NewItem(i) => {
queue.push(i);
}
GetItemResult::Timeout => panic!(), // cannot actually happen here
}
} else {
let now = Instant::now();
let tqi = queue.peek().expect("oops");
let due = tqi.when;
if due > now {
let wait = due - now;
trace!(target:"TimerQueue","sleep for {0}ms", wait.as_millis());
match get_item(&rx, wait) {
GetItemResult::Stop => {
stop = true; // drain the queue first
}
GetItemResult::NewItem(i) => {
queue.push(i);
}
GetItemResult::Timeout => {
continue;
}
}
} else {
trace!(target:"TimerQueue","running {0}", tqi.name);
(tqi.what)();
tqi.handle.signal();
queue.pop().unwrap();
}
}
}
trace!(target:"TimerQueue", "thread completed");
});
TimerQueue { jh: Some(jh), tx }
}
pub fn queue(&self, f: TQIFunc, n: String, when: Instant) -> TimerQueueHandle {
let handle = TimerQueueHandle::new();
trace!(target:"TimerQueue", "queued {0}", &n);
let qi = TimerQueueItem {
what: f,
name: n,
when: when,
handle: handle.clone(),
};
let qinst = QueueInstruction::Do(qi);
self.tx.send(qinst).unwrap();
handle
}
}
impl Drop for TimerQueue {
fn drop(&mut self) {
self.tx.send(QueueInstruction::Stop).unwrap();
match self.jh.take() {
Some(jh) => jh.join().unwrap(),
None => {}
}
}
}
fn main() {
env_logger::init();
let tq = TimerQueue::new();
tq.queue(
|| {
println!("1 sec");
},
String::from("1 sec"),
Instant::now() + Duration::from_millis(1000),
);
let h5 = tq.queue(
|| println!("5 sec"),
String::from("5 sec"),
Instant::now() + Duration::from_millis(5000),
);
tq.queue(
|| {
println!("1 sec");
},
String::from("1 sec"),
Instant::now() + Duration::from_millis(1000),
);
let h3 = tq.queue(
|| {
println!("3 sec");
},
String::from("3 sec"),
Instant::now() + Duration::from_millis(3000),
);
h3.wait();
println!("h3 done");
println!("h5 is finised {}", h5.finished());
h5.wait();
println!("h5 is finised {}", h5.finished());
}
</code></pre>
<p>sorry it fairly long</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T05:20:56.647",
"Id": "484443",
"Score": "0",
"body": "Hello, to better clarify scope of your project you could add a reference link to the previous post your actual question is a follow up."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T06:08:24.600",
"Id": "484447",
"Score": "0",
"body": "@dariosicily here u go https://codereview.stackexchange.com/questions/247327/port-of-my-c-timer-queue-to-rust"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T22:42:45.810",
"Id": "247494",
"Score": "5",
"Tags": [
"rust"
],
"Title": "after initial r*view here is a rewrite of my c++ timerqueue ported to rust"
}
|
247494
|
<p>I am using the library <code>geoip2</code> to get Geolocation of many IP adderesses</p>
<pre class="lang-py prettyprint-override"><code>
"""
input:
str: IP
output ordered list:
[0] str: City, State, Country
[1] tuple: (Lat; Log)
[2] str: Postal
"""
for i in pd.unique(df_to_print['requesterIp']):
res = reader.city(i)
# NOTE: Second snippet is added here
myDict[i] = [res.city.names['en'] + ", " + res.subdivisions[0].names['en'] + ", " + res.country.names['en'],(res.location.latitude, res.location.longitude), res.postal.code]
# output: ['Calgary, Alberta, Canada', (50.9909, -113.9632), 'T2C']
</code></pre>
<p>Sometimes the response, which is in JSON, is missing some fields. This causes a exception.</p>
<p>Here is my proposed "fix", the code works as intended, but looks sinful</p>
<pre class="lang-py prettyprint-override"><code>try:
city = res.city.names['en']
except:
city = "-1"
try:
state = res.subdivisions[0].names['en']
except:
state = "-1"
try:
country = res.country.names['en']
except:
country = "-1"
try:
cord = (res.location.latitude, res.location.longitude)
except:
cord = (-1, -1)
postal = res.postal.code if res.postal.code is not None else -1
print([city + ", " + state + ", " + country, cord, postal])
# output: ['-1, -1, China', (34.7725, 113.7266), -1]
</code></pre>
<p>What can I do to make my code more professional and efficient?</p>
<p>(this will run for apx. 100K unique IPs, several times a hour; DB is local)</p>
|
[] |
[
{
"body": "<p>Some suggestions:</p>\n<ol>\n<li>Don't use <a href=\"https://softwareengineering.stackexchange.com/q/189222/13162\">exceptions for flow control</a> unless you have to for <a href=\"https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use\" rel=\"nofollow noreferrer\">TOCTOU</a> or other reasons. "<a href=\"https://www.martinfowler.com/bliki/TellDontAsk.html\" rel=\"nofollow noreferrer\">Tell, don't ask</a>" is a useful guideline when requesting something from a piece of state the current code has no control over, but it's not a law. In your code there is no chance of <code>res.country.names</code> changing while running <code>res.country.names.get('en', "-1")</code>, and that is much clearer than using exception handling to set a default.</li>\n<li>You almost always want to catch <em>specific</em> exceptions.</li>\n<li>When retrieving values from a <code>dict</code> you can use <code>my_dict.get("key", default)</code> to get a default value if the key does not exist.</li>\n<li>Use <a href=\"https://docs.python.org/3/reference/lexical_analysis.html#f-strings\" rel=\"nofollow noreferrer\">f-strings</a> rather than <code>+</code> to create formatted strings.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T06:02:58.187",
"Id": "484446",
"Score": "3",
"body": "Could you elaborate on the first point ? Exceptions-flow control etc"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T08:52:11.300",
"Id": "484469",
"Score": "2",
"body": "@anki The most common use of exceptions is for handling (or choosing not to handle) errors, failures, or unexpected conditions. If the situation is expected, then it's often better to use some kind of `if` statement, since exceptions have high overhead, and need to be used carefully to avoid catching unrelated errors. That said, there are situations where exception based flow control is the lesser of two evils, and \"asking for forgiveness rather than permission\" is sometimes seen as a good approach, although it's less common than it was."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T12:47:23.947",
"Id": "484502",
"Score": "0",
"body": "@anki the first point is wrong. Using exceptions for control flow is a widely accepted in the python community: even standard and famous libraries are using exceptions for control flow and it's considered to be **pythonic**. This misconception comes from C++/Java/what else programmers, where exceptions have a lot of overhead and are not really efficient."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T12:56:50.497",
"Id": "484507",
"Score": "0",
"body": "@Gsk I agree that exceptions should not be used by beginners if they don't know how to use it properly (and this is not about efficiency at all) See this series https://www.youtube.com/watch?v=W7fIy_54y-w . I just wanted another viewpoint on this by the answerer here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T13:03:35.857",
"Id": "484508",
"Score": "0",
"body": "@anki thanks for the link. Yes, you have to know how to use exceptions and the implementation here is poor. Still, Python uses exceptions even in the [for loop implementation](https://docs.python.org/3/library/exceptions.html#StopIteration)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T13:24:09.487",
"Id": "484511",
"Score": "0",
"body": "@Gsk In this question, point 3 removes the need for exceptions completely. I saw that and my first thought was to find a way to set default values in a better way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T19:50:27.133",
"Id": "484546",
"Score": "0",
"body": "The source for point 1 directly states that exceptions are used for control flow in Python. On the ***first*** line"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T21:54:30.260",
"Id": "484553",
"Score": "2",
"body": "@spyr03 & others, I've updated to explain why exceptions for flow control is a bad idea for this specific code sample."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T23:11:53.223",
"Id": "484558",
"Score": "0",
"body": "Your example for point 1 assumes that res has an attribute country, and that attribute itself has and attribute names, which has a function `get`. If my reading of it is correct, the (API)[https://github.com/maxmind/GeoIP2-python#what-data-is-returned] in question explicitly calls out that not all attributes will be populated. I'm not convinced the code will be better off after accounting for all possible errors and exceptions in this case. How would you write the code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T23:17:56.143",
"Id": "484559",
"Score": "0",
"body": "@spyr03 Why not post an answer yourself?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T23:29:54.580",
"Id": "484560",
"Score": "0",
"body": "Because I don't want to post an answer. How would you write the code without exceptions as control flow, and why is it better?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T23:45:59.873",
"Id": "484561",
"Score": "0",
"body": "@l0b0 Thank you for the most recent edit (expansion to point 1). It provided needed clarification"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-08T22:52:34.300",
"Id": "484879",
"Score": "0",
"body": "\"Generally, the use of exceptions for control flow is an anti-pattern, with many notable situation - and language-specific (see for example Python)\" Isn't the OP's code _Python_? Now I understand EAFP isn't the answer to everything, like the OP's code, but drinking the LBYL kool-aid can be just as bad. Otherwise this is a pretty poor answer cause you've not explained anything except the first point."
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T01:45:58.003",
"Id": "247499",
"ParentId": "247498",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "247499",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T23:39:27.853",
"Id": "247498",
"Score": "6",
"Tags": [
"python",
"performance",
"error-handling",
"exception"
],
"Title": "Handling errors in potentially incomplete responses"
}
|
247498
|
<p>I am trying to extract and save images from a Dicom dataset. It is taking approximate 4-5 hours to process 1000 files. (Also, I am reading and saving files in an external hard drive so there is a time lag due to this factor too)<br>
Is there a way to expedite the program as I have more than 10k files and it'll take me forever to just extract the images.<br>
Also, if there is any other suggestion or improvements, anyone could suggest then it is hugely appreciated as I am not from Computer Science background.<br>
Below is my code -</p>
<pre><code>import pandas as pd
import shutil
import os
import glob
import numpy as np
import pathlib
import torch
import random
import shutil
import pydicom
import matplotlib.pyplot as plt
from skimage.io import imread, imsave,imshow
data_dir = 'Path_to_dicom_files'
files = glob.glob(os.path.join(data_dir,'*.dcm'))
folders = []
counter = 1
Destination_path = 'Path_to_destination_folder_where_images_will_be_saved'
root_dirs = 'Path_from_where_files_are_being_read'
for i in files:
print(i)
dcm = pydicom.dcmread(i)
name = dcm.AccessionNumber
dest = os.path.join(Destination_path,name)
if dcm.Modality == "XC":
if os.path.isdir(dest):
img = dcm.pixel_array
name = dcm.AccessionNumber+'_'+str(counter)+'.png'
counter+=1
#img.save(name)
imsave(name,img)
shutil.move(os.path.join(root_dirs,name),dest)
else:
os.mkdir(dest)
img = dcm.pixel_array
name = dcm.AccessionNumber+'_0.png'
#img.save(name)
imsave(name,img)
shutil.move(os.path.join(root_dirs,name),dest)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T13:59:14.560",
"Id": "484522",
"Score": "0",
"body": "where is `files` defined ? Also add the imports"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T14:11:22.463",
"Id": "484528",
"Score": "0",
"body": "How big are the files?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T14:12:30.843",
"Id": "484529",
"Score": "0",
"body": "@anki Updated the information."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T14:13:32.280",
"Id": "484530",
"Score": "0",
"body": "@CrisLuengo Updated the code. Dicom files are approximately 50-70 MB in size while images are 10-15 MB."
}
] |
[
{
"body": "<p>Big data requires big time. But there might be ways to speed up your processing somewhat. For each DICOM file you:</p>\n<ul>\n<li>open the file</li>\n<li>read metadata</li>\n<li>read an image</li>\n<li>write the image as PNG in the current directory</li>\n<li>move the PNG file to it's final destination</li>\n</ul>\n<p>Some complex file formats benefit from being read and written on a local drive, the software assumes drive access is fast and memory is expensive, so it reads small bits of data scattered around the file instead of reading larger chunks and using only the small bits it needs. These file types can benefit from being copied over in their entirety to a local drive for reading. However, DICOM is not a complex file format, and DICOM files are commonly stored on networked drives, so I don't think this causes any specific problems.</p>\n<p>However, writing PNG files might be a bit faster if done on a local drive. You create the file in the current directory (wherever that is), then move it from <code>root_dirs</code> to <code>Destination_path</code>. So I presume that <code>root_dirs</code> is the current directory? Instead, you could create the file in <a href=\"https://stackoverflow.com/q/847850/7328782\">the temporary directory</a>, then move it to its final destination like you do:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import tempfile\ntemp_dir = tempfile.gettempdir() # expected to be on the local drive\n# ...\nname = dcm.AccessionNumber + '_' + str(counter) + '.png'\nname = os.path.join(temp_dir, name)\nimsave(name, img)\nshutil.move(name,dest)\n</code></pre>\n<p>Next, <code>skimage.io.imsave</code> is very flexible, but <a href=\"https://scikit-image.org/docs/dev/api/skimage.io.html#skimage.io.imsave\" rel=\"nofollow noreferrer\">it just calls functions in other libraries</a>:</p>\n<blockquote>\n<p>By default, the different plugins are tried (starting with imageio) until a suitable candidate is found. If not given and fname is a tiff file, the tifffile plugin will be used.</p>\n</blockquote>\n<p>Note also that imageio further knows <a href=\"https://imageio.readthedocs.io/en/stable/formats.html\" rel=\"nofollow noreferrer\">a lot of formats</a>, including two different PNG implementations. So this writing function again does a lot of logic to find out what format to write the file in. And it might end up using the PIL implementation of PNG, which I hear is not very fast.</p>\n<p>Therefore, it might be a bit more performant to use a different file writer. I would experiment with different ones, even a small difference in timing will accumulate over so many images. For example, with OpenCV you'd do:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import cv2\n# ...\ncv2.imwrite(name, img)\n</code></pre>\n<p>Finally, since <code>dcm.pixel_array</code> is a property, not a function, it is likely that <code>dcm = pydicom.dcmread(i)</code> reads in all the data. If you have files for which <code>dcm.Modality == "XC"</code> is not true, you've read in data unnecessarily. Consider looking for a DICOM reader that can read only the metadata. I don't know anything about pydicom, so can't comment on its speed.</p>\n<hr />\n<p>Since this is Code Review, I'll give you some pointers towards better code:</p>\n<p>Python people have strict rules they follow for code style (encoded in <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a>). You break some of these rules, but I won't go into that, I think code style is personal and as long as you're consistent, you're OK.</p>\n<p>Repeating code is bad though. It is easy to fix a bug in one place, and then forget it needs fixing in the other copy too. It causes there to be more code to read, making the code harder to understand. And it makes you type more, giving you more possibilities to make errors. The following bit of code is repeated, with only a trivial change:</p>\n<pre class=\"lang-py prettyprint-override\"><code>counter = 1\n# ...\n if os.path.isdir(dest):\n img = dcm.pixel_array \n name = dcm.AccessionNumber+'_'+str(counter)+'.png'\n counter+=1\n imsave(name,img)\n shutil.move(os.path.join(root_dirs,name),dest)\n else:\n os.mkdir(dest)\n img = dcm.pixel_array\n name = dcm.AccessionNumber+'_0.png'\n imsave(name,img)\n shutil.move(os.path.join(root_dirs,name),dest)\n</code></pre>\n<p>Instead, write:</p>\n<pre class=\"lang-py prettyprint-override\"><code>counter = 0\n# ...\n if !os.path.isdir(dest):\n os.mkdir(dest)\n img = dcm.pixel_array \n name = dcm.AccessionNumber+'_'+str(counter)+'.png'\n counter+=1\n imsave(name,img)\n shutil.move(os.path.join(root_dirs,name),dest)\n</code></pre>\n<p>You could also put the <code>os.mkdir(dest)</code> call outside the loop. Having less code inside the loop makes the loop faster.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T00:30:42.027",
"Id": "484698",
"Score": "0",
"body": "Thank You, this was really comprehensive. Highly appreciate it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T15:42:08.790",
"Id": "247571",
"ParentId": "247501",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "247571",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T03:34:51.263",
"Id": "247501",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"image"
],
"Title": "Extract the data from Dicom files in an time efficient way"
}
|
247501
|
<h1>Client</h1>
<p>From a POST request I get a mixed structure of an array and JSON. To handle multiple type of elements I am using <code>var_dump</code> to get the passes. For <code>$_POST</code> I get this:</p>
<pre class="lang-none prettyprint-override"><code>array(2) {
["json_data"]=>
string(677) "[{"firstname":""},{"lastname":""},{"email":""},{"countryCode":""},{"phone":""},{"i_signup_password":""},{"i_signup_password_rep":""},{"email":""},{"i_signin_password":""},{"form":"d-sys-login"},{"process":"e-signin"},{"form":"d-sys-login"},{"process":"e-signin"},{"form":"d-sys-login"},{"process":"e-signin"},{"form":"d-sys-login"},{"process":"e-signin"},{"form":"d-sys-login"},{"process":"e-signin"},{"form":"d-sys-login"},{"process":"e-signin"},{"form":"d-sys-login"},{"process":"e-signin"},{"form":"d-sys-login"},{"process":"e-signin"},{"form":"d-sys-login"},{"process":"e-signin"},{"form":"d-sys-login"},{"process":"e-signin"},{"form":"d-sys-login"},{"process":"e-signin"}]",
["other_data"]=>
string(11) "Other_Data"
}
</code></pre>
<h1>Server</h1>
<p>In PHP server side I am executing a function that reduce this <code>$_POST</code> to this array:</p>
<pre class="lang-none prettyprint-override"><code>array(2) {
["JsonData"]=>
array(10) {
["firstname"]=>
string(0) ""
["lastname"]=>
string(0) ""
["email"]=>
string(0) ""
["countryCode"]=>
string(0) ""
["phone"]=>
string(0) ""
["i_signup_password"]=>
string(0) ""
["i_signup_password_rep"]=>
string(0) ""
["i_signin_password"]=>
string(0) ""
["form"]=>
string(11) "d-sys-login"
["process"]=>
string(8) "e-signin"
}
["otherdata"]=>
string(9) "otherdata"
}
</code></pre>
<h1>Code</h1>
<p>You can see this <a href="http://sandbox.onlinephpfunctions.com/code/415ba98a71e1c27300cc2946eaf803f9b8f15867" rel="nofollow noreferrer">runs online</a>.</p>
<p>Can someone help me simplify or improve the script?</p>
<ul>
<li>Application of best practices and design pattern usage</li>
<li>Potential security issues</li>
<li>Performance</li>
<li>Correctness in unanticipated cases</li>
</ul>
<p>The script used to meet this output is this:</p>
<pre><code><?php
function buildVirtualData($data)
{
if (is_array($data)) { //check if is an array Walk trough to rebuild
$temp = [];
foreach ($data as $key => $value) {
$temp[$key] = buildVirtualData($value);
}
return reduArray($temp);
} elseif (valJson($data)) { //check if is an JSON, Walk through to rebuild as an array
$json_obj = json_decode($data, true);
foreach ($json_obj as $key1 => $json_sub_obj) {
foreach ($json_sub_obj as $key2 => $value2) {
if (is_array($value2)) {
$temp = [];
foreach ($value2 as $keyof => $valueof) {
$temp[$keyof] = buildVirtualData($valueof);
}
$json_obj[$key1][$key2] = $temp;
} else {
if ('true' === $value2 || true === $value2) {
$json_obj[$key1][$key2] = true;
} elseif ('false' === $value2 || false === $value2) {
$json_obj[$key1][$key2] = false;
} else {
$json_obj[$key1][$key2] = $value2;
}
}
}
return reduArray($json_obj);
}
} else { // if it is not an array or a JSON; evaluate the type if it is text and meets possible boolean values
if ('true' === $data || true === $data) {
$data = true;
} elseif ('false' === $data || false === $data) {
$data = false;
}
return $data;
}
}
function valJson($var) //JSON Validator
{
if (!is_array($var)) {
return ((json_decode($var) != null) &&
(is_object(json_decode($var)) || is_array(json_decode($var)))) ? true : false;
} else {
return false;
}
}
function reduArray($array) //array Reductor
{
$result = $array;
if (is_array($array)) {
$check = true;
foreach ($array as $key => $value) {
if (!is_array($value)) {
$check = false;
break;
}
}
if ($check) {
$result = array_reduce($array, 'array_merge', []);
}
}
return $result;
}
//Example Data
$_POST=[];
$_POST['JsonData']='[{"firstname":""},{"lastname":""},{"email":""},{"countryCode":""},{"phone":""},{"i_signup_password":""},{"i_signup_password_rep":""},{"email":""},{"i_signin_password":""},{"form":"d-sys-login"},{"process":"e-signin"},{"form":"d-sys-login"},{"process":"e-signin"},{"form":"d-sys-login"},{"process":"e-signin"},{"form":"d-sys-login"},{"process":"e-signin"},{"form":"d-sys-login"},{"process":"e-signin"},{"form":"d-sys-login"},{"process":"e-signin"},{"form":"d-sys-login"},{"process":"e-signin"},{"form":"d-sys-login"},{"process":"e-signin"},{"form":"d-sys-login"},{"process":"e-signin"},{"form":"d-sys-login"},{"process":"e-signin"},{"form":"d-sys-login"},{"process":"e-signin"}]';
$_POST['otherdata']='otherdata';
//Execution of Function hover $_POST Variable.
$_POST=buildVirtualData($_POST);
$_POST=reduArray($_POST);
echo var_dump($_POST);
</code></pre>
<h1>Examples and Explanation:</h1>
<p>Main function is <code>buildVirtualData</code></p>
<p>This function tries to parse the <code>$_POST</code> variable; and seeks to reduce it; eliminating the excess of levels in the resulting arrays.</p>
<p>if you check the examples for this variable (arrays plus JSON) 2 arrays + JSON String:</p>
<pre><code> $_POST=[];
$_POST['JsonData']='[{"firstname":""},{"lastname":""},{"email":""},{"countryCode":""},{"phone":""},{"i_signup_password":""},{"i_signup_password_rep":""},{"email":""},{"i_signin_password":""},{"form":"d-sys-login"},{"process":"e-signin"},{"form":"d-sys-login"},{"process":"e-signin"},{"form":"d-sys-login"},{"process":"e-signin"},{"form":"d-sys-login"},{"process":"e-signin"},{"form":"d-sys-login"},{"process":"e-signin"},{"form":"d-sys-login"},{"process":"e-signin"},{"form":"d-sys-login"},{"process":"e-signin"},{"form":"d-sys-login"},{"process":"e-signin"},{"form":"d-sys-login"},{"process":"e-signin"},{"form":"d-sys-login"},{"process":"e-signin"},{"form":"d-sys-login"},{"process":"e-signin"}]';
$_POST['otherdata']='otherdata';
</code></pre>
<p>the output, Check that this include 2 Main <code>array</code> :: <code>JsonData</code>and <code>otherdata</code>:</p>
<pre><code>array(2) {
["JsonData"]=>
array(10) {
["firstname"]=>
string(0) ""
["lastname"]=>
string(0) ""
["email"]=>
string(0) ""
["countryCode"]=>
string(0) ""
["phone"]=>
string(0) ""
["i_signup_password"]=>
string(0) ""
["i_signup_password_rep"]=>
string(0) ""
["i_signin_password"]=>
string(0) ""
["form"]=>
string(11) "d-sys-login"
["process"]=>
string(8) "e-signin"
}
["otherdata"]=>
string(9) "otherdata"
}
</code></pre>
<p>While for this other variable (Only one <code>array</code> with <code>JSON</code> String):</p>
<pre><code> $_POST=[];
$_POST['JsonData']='[{"firstname":""},{"lastname":""},{"email":""},{"countryCode":""},{"phone":""},{"i_signup_password":""},{"i_signup_password_rep":""},{"email":""},{"i_signin_password":""},{"form":"d-sys-login"},{"process":"e-signin"},{"form":"d-sys-login"},{"process":"e-signin"},{"form":"d-sys-login"},{"process":"e-signin"},{"form":"d-sys-login"},{"process":"e-signin"},{"form":"d-sys-login"},{"process":"e-signin"},{"form":"d-sys-login"},{"process":"e-signin"},{"form":"d-sys-login"},{"process":"e-signin"},{"form":"d-sys-login"},{"process":"e-signin"},{"form":"d-sys-login"},{"process":"e-signin"},{"form":"d-sys-login"},{"process":"e-signin"},{"form":"d-sys-login"},{"process":"e-signin"}]';
</code></pre>
<p>the result is one less array level in this case (removing the <code>JsonData</code> index which is unnecessary in this scope):</p>
<pre><code>array(10) {
["firstname"]=>
string(0) ""
["lastname"]=>
string(0) ""
["email"]=>
string(0) ""
["countryCode"]=>
string(0) ""
["phone"]=>
string(0) ""
["i_signup_password"]=>
string(0) ""
["i_signup_password_rep"]=>
string(0) ""
["i_signin_password"]=>
string(0) ""
["form"]=>
string(11) "d-sys-login"
["process"]=>
string(8) "e-signin"
}
</code></pre>
<p><strong>the other 2 Function used:</strong></p>
<p><code>valJson</code> is to validate if value is an <code>JSON String</code> and can be used as <code>Object</code> or <code>Array</code>.</p>
<p><code>reduArray</code> is the function that performs a reduction of each <code>Array</code>.</p>
<p><strong>Why a function that does all this?</strong></p>
<p>I don't have control of the javascript code, I can only offer solutions in php code; What I can do is verify each scenario of what the server receives and this is the slightly more complex script I have.</p>
<p>in fact the <code>JsonData</code> index is not relevant take care of this: according to the documentation, everything that comes inside <code>JsonData</code> (the String Json) will be the inputs filled in a form and their value associated, so in reality the string is more important; and that the indexes and string values become <code>indexes</code> of <code>$_POST</code> ...</p>
<p>for example: there is a form with multiple checkboxes, they can be around 600 in total! Let's say they are to manage the permissions of the process screen and each process screen has 10 possible permission buttons, which are defined according to whether the checkbox is checked or not; There is no way that the server supports sending 600+ inputs in a single request without manipulating the server...</p>
<p>so the ingenious javascript programmer decided to put the 600 input and their filled values (formatted as string) inside a <code>JSON</code> variable (<code>JsonData</code> index / array) to be able to pass them to the server. I assure you, I do not share this idea; but need work around this.</p>
<p><strong>These results are correct, but I am looking to improve the code based on the objectives of this community.</strong></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T21:07:06.800",
"Id": "484550",
"Score": "1",
"body": "So how convoluted might your incoming data be? Do you _actually_ need to have recursion while converting arrays of arrays to associative arrays? or will your data only have a maximum depth of 2? Knowing the business requirements will go a long way in lightening the load of the code logic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T21:20:39.350",
"Id": "484551",
"Score": "1",
"body": "I need to be more sure about your incoming data and your requirements. Will this simple handling suffice? https://3v4l.org/4ms0W If so, I can post an educational explanation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T02:45:46.780",
"Id": "484569",
"Score": "0",
"body": "for your first comment: I don't know how deep the arrays are, even knowing this point as a dynamic part I resorted to recursion for ... this is possible for arrays, I don't know if JSON string can be nested."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T02:46:36.207",
"Id": "484570",
"Score": "0",
"body": "for your second comment: I have verified your script but the last 2 array fixes lost the index, and this is not one of the goals. Although it looks quite simple, but I also see that it does not evaluate Booleans, this is one of the points to achieve."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T02:48:31.133",
"Id": "484571",
"Score": "0",
"body": "@mickmackusa as I comment in the post; the script output is correct; the improvement I'm looking for is in the script."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T02:51:30.707",
"Id": "484572",
"Score": "1",
"body": "\"the last 2 array fixes lost the index\" ... no they didn't, I just wasn't printing them. See this change: https://3v4l.org/g5TVf Perhaps provide a battery of sample inputs that isolate all of the behaviours of your script. Some booleans, some mixed data, some multi-dimensional data -- then we can run your script and see what output is expected."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T02:56:26.377",
"Id": "484575",
"Score": "0",
"body": "@mickmackusa ok this example preserves the index of the second and third perfect; but if the array has a unique JSON string in a single array, it also keeps the first index which is not correct, for this scenario the script is expected to reduce the array and drop the first index, check Example 2 of output an your version script ouput : https://3v4l.org/KWPn8"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T03:02:02.540",
"Id": "484576",
"Score": "1",
"body": "Then you are developing a \"lossy\" data flattener. You are asking for the script to kill an associative key -- which should be, by definition, \"valuable data\". I do not have time to discuss right now, please edit your question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T03:07:05.277",
"Id": "484577",
"Score": "0",
"body": "in fact the `JsonData` index is not relevant: according to the documentation, everything that comes inside `JsonData` (the String Json) will be the `inputs` filled in a form and their `value` associated, so in reality the `string` is more important; and that the indexes and string values become indexes of `$_POST` ..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T03:14:18.923",
"Id": "484579",
"Score": "0",
"body": "for example: there is a form with multiple checkboxes, they can be around 600 in total! Let's say they are to manage the permissions of the process screen and each process screen has 10 possible permission buttons, which are defined according to whether the checkbox is checked or not; There is no way that the server supports sending 600+ inputs in a single request without manipulating the server;"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T03:14:27.747",
"Id": "484580",
"Score": "0",
"body": "so the ingenious javascript programmer decided to put the 600 input and their filled values (formatted as string) inside a JSON variable (JsonData index / array) to be able to pass them to the server. I assure you, I do not share this idea."
}
] |
[
{
"body": "<p>The way I see it, virtually all of that over-engineered convolution can be scrapped.</p>\n<p>You only need to take special action when you process the <code>JsonData</code> value.</p>\n<p>It needs to be decoded, flattened, and merged with the other non-encoded data.</p>\n<p>Simply use something like this: (<a href=\"https://3v4l.org/Ku53H\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n<pre><code>$post = [];\nforeach ($_POST as $key => $value) {\n if ($key !== 'JsonData') {\n $post[$key] = $value;\n } else {\n $post = array_merge($post, ...json_decode($value, true));\n }\n}\nvar_export($post);\n</code></pre>\n<p>If you are concerned about redundant subarray keys (that were previously json encoded), then that is more of a problem with the incoming data rather than a problem with this process (my script provides the same handling as in your posted script).</p>\n<p>Now that you can see how simply the data can be unpacked, you won't need to bag so hard on the other developer.</p>\n<hr />\n<p>I don't think I endorse the practice of key-ignorant json decoding <code>true</code>/<code>false</code> strings to booleans because it will potentially convert strings that shouldn't be converted.</p>\n<p>Amyhow, here's one way of handling the conditional boolean conversion (<a href=\"https://3v4l.org/DLiqu\" rel=\"nofollow noreferrer\">Demo</a>):</p>\n<pre><code>function mergeAndBoolify($posted) {\n $result = [];\n foreach ($posted as $key1 => $value1) {\n if ($key1 === 'JsonData') {\n foreach (json_decode($value1, true) as $item) {\n foreach ($item as $key2 => $value2) {\n if (in_array($value2, ['true', 'false'])) {\n $value2 = json_decode($value2);\n }\n $result[$key2] = $value2;\n }\n }\n } else {\n $result[$key1] = $value1;\n }\n }\n return $result;\n}\n\n$_POST = [\n 'JsonData' => '[{"firstname":"false"},{"lastname":"true"},{"email":""}]',\n 'otherdata' => 'otherdata'\n];\n\nvar_export(mergeAndBoolify($_POST));\n</code></pre>\n<p>Output:</p>\n<pre><code>array (\n 'firstname' => false,\n 'lastname' => true,\n 'email' => '',\n 'otherdata' => 'otherdata',\n)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-08T08:54:16.340",
"Id": "484852",
"Score": "0",
"body": "ok but how i can get it with every value evaluated is a bolean (true, false), including string like 'true', 'false'..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-08T12:44:28.273",
"Id": "484863",
"Score": "1",
"body": "Please provide sample data for this case and your exact required result. I can only understand the variability of the data based on what you provide."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-09T04:10:41.930",
"Id": "484886",
"Score": "0",
"body": "@walter, I have updated my answer to covert boolean strings within the jsondata to boolean type."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-10T21:43:46.070",
"Id": "485073",
"Score": "0",
"body": "thank ypur for the great help."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-08T06:09:29.117",
"Id": "247643",
"ParentId": "247502",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "247643",
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T04:05:35.330",
"Id": "247502",
"Score": "2",
"Tags": [
"performance",
"php",
"array",
"json"
],
"Title": "Request mixed with JSON strings and array fields, in custom function for reduction need Simplify/Refactory"
}
|
247502
|
<p>I have a set of connections and protocols for which I am writing unit tests. Their purpose is to assess 2 vectors for validity and consistency; that is there must be not any elements that have been lost, received out of order or are invalid.</p>
<p><strong>Vector to send is always sorted</strong>.</p>
<p>I came up with a naive function to make such an analysis, but I do not think it is efficient at all (for relatively small amounts of data it is ok).</p>
<p>So, my questions basically are:</p>
<ol>
<li>How can it be improved?</li>
<li>What additional analysis may be required to compare sent and received vectors? Are there any cases I have missed?</li>
</ol>
<pre><code>template <typename DataType>
struct io_arrays_compared
{
std::vector<DataType> sent,
received,
validElems;
size_t invalidOrderElems = 0;
int verbosityLevel = 0;
size_t invalid_elems() const
{
return received.size() - validElems.size();
}
// may be negative
int elems_lost() const
{
return (int)sent.size() - (int)received.size();
}
size_t out_of_order() const
{
return invalidOrderElems;
}
bool Success() const
{
return !invalid_elems() &&
!elems_lost() &&
!out_of_order();
}
operator bool() const
{
return Success();
}
template<typename Char>
friend std::basic_ostream<Char> &operator<<(std::basic_ostream<Char> &os,
io_arrays_compared<DataType> ioResult)
{
size_t bytesReceived = ioResult.received.size() * sizeof(DataType);
os << "Transferred: bytes " << bytesReceived <<
'/' << ioResult.sent.size() * sizeof(DataType) << ", elements " <<
ioResult.received.size() << '/' << ioResult.sent.size() <<
"\nLost: " << ioResult.elems_lost() <<
"\nInvalid: " << ioResult.invalid_elems() <<
"\nOut of order: " << ioResult.out_of_order() << std::endl;
// TODO: element by element comparison if verbosity level is not 0
return os;
}
};
template <typename DataType, typename CmpLess = std::less<DataType>>
io_arrays_compared<DataType> make_io_arrays_compare(std::vector<DataType> sent,
std::vector<DataType> received,
CmpLess cmpLess = CmpLess())
{
auto cmpEqual = [&](const DataType &d1, const DataType &d2)
{
return !cmpLess(d1, d2) && !cmpLess(d2, d1);
};
io_arrays_compared<DataType> res;
res.sent = std::forward<std::vector<DataType>>(sent);
res.received = std::forward<std::vector<DataType>>(received);
std::vector<DataType> sortedReceived{res.received.cbegin(), res.received.cend()};
std::sort(sortedReceived.begin(), sortedReceived.end(), cmpLess);
// valid elems
std::set_intersection(sortedReceived.cbegin(), sortedReceived.cend(),
res.sent.cbegin(), res.sent.cend(),
std::back_inserter(res.validElems),
cmpLess);
res.invalidOrderElems = 0;
for (size_t i = 0; i != res.sent.size() && i != res.received.size(); ++i)
{
if (cmpEqual(res.sent[i], res.received[i]))
continue;
// is received element valid?
auto found = std::find_if(res.validElems.cbegin(), res.validElems.cend(),
[&](const DataType& d)
{
return cmpEqual(d, res.sent[i]);
});
// element is valid, but not equal to ith sent, therefore is out of order
if (found != res.validElems.cend())
++res.invalidOrderElems;
}
return res;
}
</code></pre>
<p>Basic unit test for comparison function which is passed:</p>
<pre><code>int main(int argc, const char **argv)
{
std::vector<int> out{0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
in{0, 1, 2, 5, 6, 12, 3, 4, 8, 9};
auto result = make_io_arrays_compare(std::move(out), std::move(in));
std::cout << result;
if (result.elems_lost() == 0 &&
result.out_of_order() == 4 &&
result.invalid_elems() == 1)
return 0;
return -1;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T08:48:24.793",
"Id": "484468",
"Score": "0",
"body": "Are you sure the vectors have to be moved to the result structure? Shouldn't it just work with const references? Or even better let the make function only work with const references and let the structure only contain the sizes and other numbers that are product of the analysis? The structure has no need to contain the entire vectors..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T08:52:26.090",
"Id": "484470",
"Score": "0",
"body": "@slepic the result structure stores vector in order to print report with element by element comparison (to file or to the console), though this feature is not yet implemented (hence there is a TODO: comment). So I use forwarding in order to move vectors if I want to or copy them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T08:57:46.027",
"Id": "484473",
"Score": "0",
"body": "Oh i see. You should use const references then. Moving the vectors to the result leaves the original vectors in an undefined state. Since this is only analysis i would assume the originals are to be consumed somewhere else. Which they cannot if they have been moved."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T09:01:52.753",
"Id": "484474",
"Score": "0",
"body": "@slepic they are not needed elsewhere in this particular case, so I use move. But the function to analyze uses forwarding (that is I expect, I hope I did it right), so I do not need to use const reference as argument (otherwise I won't be able to use move)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T09:28:00.050",
"Id": "484479",
"Score": "0",
"body": "I mean the properties of the struct to be const references (well of course the make function arguments too). You will have to pass those references in constructor. But I dont see a reason to move them, they are treated as constant..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T09:33:55.623",
"Id": "484480",
"Score": "0",
"body": "@slepic well that makes sence"
}
] |
[
{
"body": "<h1>Naming</h1>\n<p>Your names are inconsistent. First, there is a mix of camelCase, PascalCase and snake_case. Pick one style and stick with it. You can make an exception for template type names, typically you would write <code>T</code> for the data type, and <code>Compare</code> for the comparison object.</p>\n<p>Second, the three getter functions in <code>io_arrays_compared</code> are named <code>invalid_elems()</code>, <code>elems_lost()</code> and <code>out_of_order()</code>. Two have <code>elems</code> in the name, but one has it in front, the other at the back. Try to be consistent. Is it necessary to have "elems" in the name or is it clear from the context? If it's clear, then just write <code>invalid()</code>, <code>lost()</code> and <code>out_of_order()</code>. To make it clear that this returns a count, and not a boolean or a vector with the affected elements, I would prefix them all with <code>n_</code>, as that typically means "number of": <code>n_invalid()</code>, <code>n_lost()</code>, <code>n_out_of_order()</code>.</p>\n<p>The class and function names could be improved too:</p>\n<ul>\n<li><code>io_arrays_compared</code> -> <code>io_array_comparison_result</code></li>\n<li><code>make_io_arrays_compare()</code> -> <code>compare_io_arrays()</code></li>\n</ul>\n<h1>The result class should not hold unnecessary data</h1>\n<p>The result class should just contain four member variables:</p>\n<pre><code>const size_t n_sent;\nconst size_t n_invalid;\nconst size_t n_lost;\nconst size_t n_out_of_order;\n</code></pre>\n<p>If you make them <code>const</code>, you can then make them <code>public</code> and don't need any getter functions for them. You can still have the convenience functions such as <code>bool Success()</code>, <code>operator bool()</code> and <code>operator<<()</code>.</p>\n<p>You shouldn't keep a copy of the sent and received data, because the caller of <code>compare_io_arrays()</code> already has that data. Furthermore, <code>validElems</code> is just a temporary vector used in <code>compare_io_arrays()</code>, so that should just be declared locally in that function.</p>\n<p>Even if you plan to make use of the extra data in the future, it is best not to add currently unused member variables. Plans might never be turned into action, or they might change. The <a href=\"https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it\" rel=\"nofollow noreferrer\">YAGNI principle</a> applies here. It also makes it harder for code reviewers to know what to ignore.</p>\n<h1>Avoid copying the input vectors</h1>\n<p>It's usually good practice to take <code>const</code> references to large parameters such as the <code>sent</code> and <code>received</code> vectors, so you avoid making unnecessary copies, so write:</p>\n<pre><code>template <typename T, typename Compare = std::less<T>>\nio_array_comparison_result<T> compare_io_arrays(const std::vector<T> &sent,\n const std::vector<T> &received,\n Compare comp = Compare())\n{\n ...\n</code></pre>\n<p>If you want to use <code>std::set_intersection()</code>, you still need to make a copy of the received data though:</p>\n<pre><code>auto received_sorted = received;\nstd::sort(received_sorted.begin(), received_sorted.end(), comp);\n</code></pre>\n<p>But that might not be necessary:</p>\n<h1>Avoiding sorting the received data</h1>\n<p>It's possible to avoid sorting the received data, which can improve performance if there are only few packets that are reordered. Since the <code>sent</code> vector is already sorted, you can check for each element in <code>received</code> if it was present in <code>sent</code> using <a href=\"https://en.cppreference.com/w/cpp/algorithm/binary_search\" rel=\"nofollow noreferrer\"><code>std::binary_search()</code></a>. This has complexity O(N log N), which is the same as first sorting the input and then using <code>std::set_intersection()</code>. But you can do better, since you can scan linearly through <code>sent</code> and <code>received</code> as long as their elements match, and when they don't you can start doing the binary search, until they start matching up again.</p>\n<h1>How to count out of order elements</h1>\n<p>Your method of checking whether elements are received in the same order as they are sent is too naive. It just checks whether elements at the same index in both vectors are equal. But what if one element is lost?</p>\n<pre><code>std::vector<int> out{0, 1, 2, 3, 4, 5};\nstd::vector<int> in {0, 1, 3, 4, 5};\n</code></pre>\n<p>In this case, it will report that three elements are out of order. A better approach would be to just scan <code>received</code> and check whether successive elements are ordered as expected. For example:</p>\n<pre><code>std::vector<int> out{0, 1, 2, 3, 4, 5};\nstd::vector<int> in {0, 2, 3, 4, 1, 5};\n</code></pre>\n<p>Only the pair <code>4, 1</code> is not in the right order, since <code>4 < 1 == false</code>. And that makes sense, since it's just the element <code>1</code> that has skipped three places ahead.</p>\n<h1>Additional analysis</h1>\n<p>What I am missing is a check for duplicated elements. This is not an uncommon issue in networks.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T06:18:06.950",
"Id": "484586",
"Score": "0",
"body": "Thank you for your answer. I have mentioned in the comments to my question the reason why I hold vectors instead of just numbers of elements. That is for report printing which will show element by element comparison, marking rows with lost or corrupt elements. I was suggested to store const reference in the result structure."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T06:20:22.010",
"Id": "484587",
"Score": "0",
"body": "I know that using `std::endl` is considerably slower, and I use it here only once - at the end to explicitly flush the buffer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T08:16:38.500",
"Id": "484596",
"Score": "2",
"body": "@Emma: yes, there is no law against mixing different styles, and indeed some style guides advocate using one style for types, another for function names, so they are easy to distinguish. Google's style guide is just one of many, there is not a single authority. But indeed all of them want you to be conistent :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T08:20:26.680",
"Id": "484599",
"Score": "1",
"body": "@SergeyKolesnik: the [YAGNI principle](https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it) applies to the vectors you stored. About using `std::endl` only once: why do you need it at all? When printing to a console or terminal window, it will automatically flush after a newline character, there is no need for an explicit flush."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T10:12:40.900",
"Id": "484612",
"Score": "0",
"body": "@G.Sliepen CLion does not show any output until flush is called explicitly or `std::endl` is passed. And I do need that report, I just haven't implemented it yet"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T12:41:24.507",
"Id": "484624",
"Score": "1",
"body": "@SergeyKolesnik Ah, if your environment needs the explicit flush, then indeed keep it. But about the unimplemented report: you still should avoid including things that you are not currently needing. It also makes code reviews easier if we don't have to keep track of what unnecessary things were meant for future features."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-10T06:25:39.393",
"Id": "484997",
"Score": "0",
"body": "About checking the received array for order: successive element being larger then current does bot mean it is in right order. `0 1 15 16 2 3 4 5...`. And there is only `operator<` available. So how can you deal with it? Moreover, if received array has duplicates, what is the right way to get rid of them in order to assess the order in a proper way?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-10T10:06:10.500",
"Id": "485016",
"Score": "0",
"body": "If it's not in the right order then there will be at least one element in the received array which is smaller than the previous element. In your example, 2 is less than 16. As for duplicates, you can create a `std::set`, and first check if a received item is already in this set. If so, it's a duplicate, otherwise you insert it in the set."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T22:29:30.320",
"Id": "247546",
"ParentId": "247504",
"Score": "4"
}
},
{
"body": "<p>This is just a short review to complement the nice one already posted by G. Sliepen.</p>\n<h2>Use only the allowed forms of <code>main</code></h2>\n<p>The code currently includes this line:</p>\n<pre><code>int main(int argc, const char **argv)\n</code></pre>\n<p>However, there are only two forms of <code>main</code> allowed by the standard:</p>\n<pre><code>int main(int argc, char *argv[]) // note no const!\nint main()\n</code></pre>\n<h2>Consider calculating a Levenshtein distance</h2>\n<p>A <a href=\"https://en.wikipedia.org/wiki/Levenshtein_distance\" rel=\"nofollow noreferrer\">Levenstein distance</a> calculation would probably yield a much more concise way to express what went wrong. By calculating and then traversing a Wagner-Fisher matrix, you can very concisely describe the minimum number of insertions, deletions and substitutions that could have transpired to produce the observed result.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T21:41:35.810",
"Id": "247591",
"ParentId": "247504",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "247546",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T05:35:20.107",
"Id": "247504",
"Score": "9",
"Tags": [
"c++"
],
"Title": "Compare and analyze sent and received vectors"
}
|
247504
|
<pre><code>from enum import Enum
from fastapi import FastAPI
app = FastAPI()
</code></pre>
<p>Hi Defined a route and a Enum Class for the same but the Enum Class looks ugly.</p>
<pre><code>class Subjects(str, Enum):
path1="AcceptedEventRelation"
path2="Account"
path3="AccountChangeEvent"
path4="AccountCleanInfo"
path5="AccountContactRole"
...
...
path100
@app.get("/subjects/{sobjectname:str}")
async def process_subjects(sobjectname:Subjects):
endpoint_subjects = "/services/data/v49.0/sobjects"
url_to_request = endpoint_subjects + "/" + sobjectname
return {
"subject" : sobjectname,
"url_to_request": url_to_request
}
</code></pre>
<p>Is there a better way to implement the Subjects Class. Thanks</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T06:45:48.853",
"Id": "484448",
"Score": "0",
"body": "The fact is that you need the LHS and RHS somewhere in your code, in some form. It can be a `list`, or `dict`, or in some other forms."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T09:13:52.790",
"Id": "484477",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] |
[
{
"body": "<p>The fact is that you need the LHS and RHS somewhere in your code, in some form. It can be a <code>list</code>, or <code>dict</code>, or in some other forms.</p>\n<p>For example:</p>\n<pre><code>from enum import Enum\nfrom fastapi import FastAPI\n\napp = FastAPI()\nsome_dict = dict(\n path1="AcceptedEventRelation",\n path2="Account",\n path3="AccountChangeEvent",\n path4="AccountCleanInfo",\n path5="AccountContactRole"\n)\n\nSubjects = Enum('Subjects', some_dict)\n\n\n@app.get("/subjects/{sobjectname}")\nasync def process_subjects(sobjectname: Subjects):\n endpoint_subjects = "/services/data/v49.0/sobjects"\n url_to_request = endpoint_subjects + "/" + sobjectname.value\n return {\n "subject": sobjectname,\n "url_to_request": url_to_request\n }\n</code></pre>\n<p>Here, the <strong><code>some_dict</code></strong> is the variable you need to <em><strong>generate</strong></em>, which also looks ugly if there is a <em>100</em> items in it as the way you feel for the <code>Enum</code> class.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T07:39:33.507",
"Id": "484453",
"Score": "0",
"body": "what is `MyDynamicEnum` referes to ? .. when I call the endpoint I get, `TypeError: can only concatenate str (not \"MyDynamicEnum\") to str\n`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T07:47:28.700",
"Id": "484454",
"Score": "0",
"body": "`MyDynamicEnum` is the class name"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T08:15:45.280",
"Id": "484462",
"Score": "0",
"body": "ok but how canI fix the above error"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T08:20:48.953",
"Id": "484463",
"Score": "0",
"body": "probably you should show the error traceback"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T08:29:12.777",
"Id": "484467",
"Score": "0",
"body": "error traceback added in the question, pls check"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T13:22:11.770",
"Id": "484510",
"Score": "0",
"body": "can you test my code once with your solution"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T06:24:07.973",
"Id": "484588",
"Score": "0",
"body": "updated the codebase."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T06:50:48.717",
"Id": "247509",
"ParentId": "247505",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T06:35:05.260",
"Id": "247505",
"Score": "2",
"Tags": [
"python",
"api",
"enum"
],
"Title": "Fast API path parameters from Enum Class"
}
|
247505
|
<p>This question is abut coding style. I'd like to see how would you improve this code look considering readability as well. Feel free to upvote others solutions you find good.</p>
<p>#1 Initial version:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT greatest(
0,
least(
500,
(SELECT g.c_daily_limit * (
SELECT count(*)
FROM rivals.t_rival_group_auth a
WHERE a.id_group = g.id) - (
SELECT count(*)
FROM rivals.t_order_results rs
JOIN rivals.t_rivals r ON r.id = rs.id_rival
WHERE r.id_group = g.id
AND rs.c_date_order::date = utils.getdate()::date
AND (rs.c_price IS NOT NULL OR rs.c_failed IS NOT NULL))
FROM rivals.t_rival_group g
WHERE g.c_code = _code)
)
);
</code></pre>
<p>#2 An alternative version, should improve readability of nested parameters:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT greatest(
0,
least(
500,
(
SELECT g.c_daily_limit * (
SELECT count(*)
FROM rivals.t_rival_group_auth a
WHERE a.id_group = g.id
) - (
SELECT count(*)
FROM rivals.t_order_results rs
JOIN rivals.t_rivals r ON r.id = rs.id_rival
WHERE r.id_group = g.id
AND rs.c_date_order::date = utils.getDate()::date
AND (rs.c_price IS NOT NULL OR rs.c_failed IS NOT NULL)
)
FROM rivals.t_rival_group g
WHERE g.c_code = _code
)
)
);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T06:49:28.810",
"Id": "484450",
"Score": "2",
"body": "Welcome to Code Review! It appears that you are trying to do a [comparative-review](https://codereview.stackexchange.com/tags/comparative-review/info). Please add the solutions contained in the answers to your question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T08:53:00.453",
"Id": "484471",
"Score": "1",
"body": "Also please tag the question with appropriate SQL dialect. Is this MS SQL Server?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T16:33:19.703",
"Id": "484539",
"Score": "2",
"body": "Can't test right now but I would look into making this a [**CTE**](https://www.postgresql.org/docs/9.1/queries-with.html). If you add table structure + some data and post on Dbfiddle for example, then it will be possible to test something."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T09:20:42.360",
"Id": "484603",
"Score": "2",
"body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T09:22:33.753",
"Id": "484604",
"Score": "2",
"body": "You should provide context for your query, i.e. what does it do. Also, you should post the code to create the relevant tables. Please [**follow the tour**](https://CodeReview.StackExchange.com/tour), and read [**\"What topics can I ask about here?\"**](https://CodeReview.StackExchange.com/help/on-topic), [**\"How do I ask a good question?\"**](https://CodeReview.StackExchange.com/help/how-to-ask) and [**\"What types of questions should I avoid asking?\"**](https://CodeReview.StackExchange.com/help/dont-ask)."
}
] |
[
{
"body": "<p>The following are a few suggestions on how I'd write the SQL.</p>\n<p><strong>Source Control</strong></p>\n<p>If you don't already have a <a href=\"https://docs.microsoft.com/en-us/previous-versions/sql/sql-server-data-tools/hh272677(v=vs.103)\" rel=\"nofollow noreferrer\">database project</a>, create one in <a href=\"https://visualstudio.microsoft.com/\" rel=\"nofollow noreferrer\">Visual Studio</a>. Then check it in to source control. <a href=\"https://azure.microsoft.com/en-au/services/devops/\" rel=\"nofollow noreferrer\">Microsoft Azure DevOps Services</a> is free & private for teams of 5 or less (this is per project, so 5 developers per project). Then you'll be able to track changes you make to your stored procedures, views, tables, etc.</p>\n<p><strong>Formatting</strong></p>\n<p>I use the following tools for SSMS and Visual Studio, <a href=\"https://www.apexsql.com/sql-tools-refactor.aspx\" rel=\"nofollow noreferrer\">ApexSQL Refactor</a> and <a href=\"https://marketplace.visualstudio.com/items?itemName=TaoKlerks.PoorMansT-SqlFormatterSSMSVSExtension\" rel=\"nofollow noreferrer\">Poor Man's T-Sql Formatter</a>. I use it when I have to edit other developer's code. It's a great way to standardize your SQL. I find it does most of the formatting for me, but I'll still make a few changes after.</p>\n<p><strong>Copy & Paste</strong></p>\n<p>If you find yourself copying and pasting the same string or number over and over in your query, then you should define it as a variable. <a href=\"https://en.wikipedia.org/wiki/David_Parnas\" rel=\"nofollow noreferrer\"><em>Copy and paste is a design error ~ David Parnas</em></a></p>\n<p><strong>Commas</strong></p>\n<p>I would put the commas in front to clearly define new columns. Versus code wrapped in multiple lines. It also makes trouble-shooting code easier.</p>\n<p><strong>Where Clause</strong></p>\n<p>If you put <code>1=1</code> at the top of a <code>WHERE</code> condition, it enables you to freely change the rest of the conditions when debugging a query. The SQL query engine will end up ignoring the <code>1=1</code> so it should have no performance impact. <a href=\"https://stackoverflow.com/q/242822/9059424\">Reference</a></p>\n<p><strong>Common Table Expressions (CTE)</strong></p>\n<p><a href=\"https://docs.microsoft.com/en-us/sql/t-sql/queries/with-common-table-expression-transact-sql?view=sql-server-2017\" rel=\"nofollow noreferrer\">CTE's</a> in your SQL help with documentation. The expression name can then let other developers know why you used that expression e.g. <code>number_of_group_auth</code> or <code>number_of_order_results</code>.</p>\n<p><strong>Schema Names</strong></p>\n<p>Always reference the schema when selecting an object e.g. <code>[dbo].[Sales]</code>.</p>\n<ul>\n<li>Also check out the book <a href=\"https://rads.stackoverflow.com/amzn/click/0132350882\" rel=\"nofollow noreferrer\"><em>Clean Code</em></a>. It will change the way you think about naming conventions.</li>\n</ul>\n<hr />\n<p><strong>Revised SQL</strong></p>\n<p>Without table definitions and sample records I was unable to test this, but it should give you a good start.</p>\n<pre><code>WITH\nnumber_of_group_auth -- table expression names should tell you what they're doing so you don't need to use comments\nAS\n(\n SELECT \n [group_count] = COUNT(*)\n , [a].[id_group]\n FROM \n [rivals].[t_rival_group_auth] AS [a]\n)\n,\nnumber_of_order_results\nAS\n(\n SELECT \n [group_count] = COUNT(*)\n , [r].[id_group]\n FROM\n [rivals].[t_order_results] AS [rs]\n INNER JOIN [rivals].[t_rivals] AS [r] ON [r].[id] = [rs].[id_rival]\n WHERE\n 1=1\n AND [rs].[c_date_order]::date = utils.getdate() ::date\n AND\n (\n [rs].[c_price] IS NOT NULL\n OR [rs].[c_failed] IS NOT NULL\n )\n)\nSELECT\n greatest\n (0, least \n (500,\n (\n SELECT\n [g].[c_daily_limit] * [number_of_group_auth].[group_count] - [number_of_order_results].[group_count]\n FROM \n [rivals].[t_rival_group] AS [g]\n LEFT JOIN [number_of_group_auth] AS [a] ON [a].[id_group] = [g].[id]\n LEFT JOIN [number_of_order_results] AS [r] ON [r].[id_group] = [g].[id]\n WHERE \n [g].[c_code] = [_code]\n )\n )\n );\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-06T03:36:17.680",
"Id": "251686",
"ParentId": "247506",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T06:39:25.903",
"Id": "247506",
"Score": "2",
"Tags": [
"sql",
"comparative-review",
"postgresql"
],
"Title": "Any ideas how do I prettify this SQL query?"
}
|
247506
|
<p>I have a React functional component where users can add a movie from a list to their dashboard. I'm displaying a toast (Material UI Snackbar) to show the result. The result can be good: movie has been added, or bad: movie is already added to your watchlist.</p>
<pre><code>const addMovie = (movie: IMovie) => {
const isMovieDuplicate = !checkForDuplicate(movies, movie);
if (isMovieDuplicate) {
movies.push(movie);
const sortedMovieList = sortMovieList(movies);
setMovies(sortedMovieList);
addMovieToLocalStorage(sortedMovieList);
}
const message = isMovieDuplicate ?
movie.original_title + ' has been added to your watchlist.' :
movie.original_title + ' is already added to your watchlist.';
const variant = isMovieDuplicate ? {variant: 'success'} : {variant: 'warning'};
displaySnackbar(message, variant);
};
const displaySnackbar = (message: string, type: any) => {
enqueueSnackbar(message, type);
};
const sortMovieList = (movies: IMovie[]) => {
return orderBy(movies, [(movie: IMovie) =>
returnSortType(movie, sortConfig.selectedSortType)], [sortConfig.orderType ? 'asc' : 'desc'],
);
};
</code></pre>
<p>First I call a function that checks the if the current movie already exists in the movieList array. If so it returns a true. The <code>isMovieDuplicate</code> takes the opposite value, so in case of there being a duplicate it will be false so that the if statement is not executed.</p>
<p>In the <code>if</code> statement I push the movie object in the movies array. Then I use a function to return an sorted array. Users can specify how they want to sort the list based on title, release date.</p>
<p>I use the <code>sortedMovieList</code> value to call my React hook <code>setMovies</code> and put he array in the React state. Then I use that same array and put the data in my local storage. At some point this local storage will be replaced with an actual database.</p>
<p>When the if statement is completed I want to show the result in a snackbar (toast). Based on the <code>isMovieDuplicate</code> variable I create the context for the toast and pass that to the <code>displaySnackbar</code> function which renders it on the page.</p>
<p>This all works, but it doesn't feel "clean". There's quite some code, maybe I could move the code for creating the message into the <code>displaySnackbar</code> method?</p>
|
[] |
[
{
"body": "<p>Not as clean as it could be, some code duplication, and there's also some state mutation in your <code>addMovie</code> function.</p>\n<h1>Issues</h1>\n<ol>\n<li><code>movies.push(movie);</code> mutates the current state object.</li>\n<li><code>checkForDuplicate</code> isn't a clear name, i.e. checking for duplicates is clear, but what is the return value?</li>\n<li>Using <code>isMovieDuplicate</code> as the negation of the result from <code>checkForDuplicate</code> is completely counter-intuitive and confusing.</li>\n<li>When adding data to current state and computing the next state, a functional state update should really be used.</li>\n<li>Ternary logic could be reduced/simplified.</li>\n<li>Handle side-effect of persisting to local storage in the component as an "effect" of updating the <code>movies</code> state.</li>\n</ol>\n<h1>Suggestions</h1>\n<ol>\n<li>Use a functional state update and shallow copy of current state in order to not mutate current state and correctly enqueue state updates.</li>\n<li>Change <code>checkForDuplicate</code> to <code>checkIsDuplicate</code> to make it more clear the return value is likely a boolean (by <code>isXXX</code> naming convention) and will be true if it is a duplicate.</li>\n<li>Remove <code>isMovieDuplicate</code> and use <code>checkIsDuplicate</code> directly in conditional test.</li>\n<li>Remove the ternary. Assume duplicate failure, only update if not a duplicate and adding to movie array.</li>\n<li>Use an <code>useEffect</code> hook to persist to localStorage (and eventually to DB).</li>\n</ol>\n<p>Code</p>\n<pre><code>const addMovie = (movie: IMovie) => {\n let message = 'is already added to your watchlist.';\n let variant = 'warning';\n\n if (!checkIsDuplicate(movies, movie)) {\n setMovies(movies => sortMovieList([...movies, movie]));\n message = 'has been added to your watchlist.';\n variant = 'success';\n }\n\n displaySnackbar(`${movie.original_title} ${message}`, { variant });\n};\n\nuseEffect(() => {\n addMovieToLocalStorage(movies);\n}, [movies]);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T10:14:20.963",
"Id": "484613",
"Score": "0",
"body": "Thanks again Drew. I love this line `setMovies((movies) => sortMovieList([...movies, movie]));` very clear and concise. I also like the removal of the ternary statement and make the snackBar output part of the code. Makes it much more readable. 2 questions, if you don't mind: 1. why prefer the `useEffect` to put the movie in localStorage over the `addMovie` function. 2. It feels duplicate, placing a movie object in the `movies` state and also in the local storage. I have 2 places where movies are stored, is there a method where the localStorage acts as the point of truth?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T15:23:54.980",
"Id": "484631",
"Score": "0",
"body": "@PeterBoomsma Thank you. (1) Separating the state persistence to localStorage is an *effect* of updating state, i.e. state updated -> persist to longer-term storage. I'm a fan of the [Single Responsibility Principle](https://en.wikipedia.org/wiki/Single-responsibility_principle) where basically each module/class/function is responsible for a single aspect of the overall functionality of the program. In a bigger system like redux I'd just have a piece of middleware or handler that simply every second or so writes app state to local storage, removing the responsibility from the UI code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T15:26:27.300",
"Id": "484632",
"Score": "0",
"body": "@PeterBoomsma (2) Yes, when your application loads (page refresh or native app opens) it can read the persisted app state from local storage and populate the application state. Here your app state is acting as cache."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T21:37:33.340",
"Id": "247543",
"ParentId": "247512",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "247543",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T08:45:04.733",
"Id": "247512",
"Score": "3",
"Tags": [
"react.js",
"typescript"
],
"Title": "Display toast after action"
}
|
247512
|
<p>Microcontroller receive data on uart and call parser_i2c function when user presses enter
e.g. parser_i2c(I2C scan)</p>
<p>I want to parse following input from user communicated through uart</p>
<p>I2C scan</p>
<p>I2C read read_adress</p>
<p>I2C Write Write_address data</p>
<p>I have wrote following code</p>
<pre><code> void parser_i2c(unsigned char str[20])
{
//unsigned char str[20]
unsigned char s[2] = " ";
unsigned char *token;
unsigned char output[10][10] ;
U8 i_i2c=0;
/* get the first token */
token = strtok(str, s);
/* walk through other tokens */
while( token != NULL ) {
// printf( " %s\n", token );
strcpy(output[i_i2c],token);
i_i2c++ ;
token = strtok(NULL, s);
}
if(!(strcmp(output[0],"I2C")))
{
if(!(strcmp(output[1],"READ")))
{
if(*output[2]!='\0')
{
i2c_read(output[2]) ;
}
else{
printf(COLOR_RED "Bad command" COLOR_RESET);
}
}
else if(!(strcmp(output[1],"WRITE")))
{
if(((*output[2])||(*output[3]))!='\0')
{
i2c_write(output[2],output[3]);
}
else{
printf(COLOR_RED "Bad Command" COLOR_RESET);
}
}
else if(!(strcmp(output[1],"SCAN")))
{
i2c_scan();
}
else{
printf(COLOR_RED "Bad Command" COLOR_RESET);
}
}
else {
printf(COLOR_RED "Bad Command" COLOR_RESET);
}
memset(output, '\0', 10*sizeof(arr[0]));
}
</code></pre>
<p>How to improve it ? in terms of reducing code lines and code size and memory utilization ? or any other way to parse ? Is there any basic library available ?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T19:13:38.393",
"Id": "484543",
"Score": "2",
"body": "Is the indentation of your code the same as shown on this page as it is in your editor on your own machine?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T22:34:02.197",
"Id": "484555",
"Score": "1",
"body": "@AustinHastings please leave the indentation as is- changing it would invalidate the answer. For more context, please see [this meta answer](https://codereview.meta.stackexchange.com/a/5946/120114)."
}
] |
[
{
"body": "<p>Here are some things that may help you improve your program.</p>\n<h2>Use consistent formatting</h2>\n<p>The code as posted has inconsistent indentation which makes it hard to read and understand. Pick a style and apply it consistently.</p>\n<h2>Provide complete code to reviewers</h2>\n<p>This is not so much a change to the code as a change in how you present it to other people. Without the full context of the code and an example of how to use it, it takes more effort for other people to understand your code. This affects not only code reviews, but also maintenance of the code in the future, by you or by others. One good way to address that is by the use of comments. Another good technique is to include test code showing how your code is intended to be used.</p>\n<h2>Use <code>const</code> where practical</h2>\n<p>The <code>s</code> string is set and never altered, so it could be <code>const</code> or even better in this case, <code>static const</code>.</p>\n<h2>Consider re-entrancy</h2>\n<p>In an embedded system, there are often many things happening at once. The usual case is that many events are <em>event-driven</em> and so the order in which parts of code are executed is uncertain. For that reason, you should be wary about using non-reentrant calls such as <code>strtok</code>. Also, we don't have the complete context, but it may be worth making a copy of a buffered line of data so that subesequent data the comes in does not overwrite a line as it is being parsed.</p>\n<h2>Consider passing a length</h2>\n<p>This code makes the tacit assumption that the passed array is a <code>'\\0'</code>-terminated text string. If you can guarantee that is always the case, then the code is fine as it is, but a more robust system might be to explicitly pass both a pointer and a length.</p>\n<h2>Understand system variations</h2>\n<p>It is implementation-defined whether <code>char</code> is signed or unsigned. If it happens to be signed on your platform, you will get warnings about sign mismatches for parameters passed to <code>strtok</code> and <code>strcpy</code>. If you system uses unsigned chars by default, you will get no such warning, but you should be aware that this is at least a portability concern.</p>\n<h2>Simplify your algorithm</h2>\n<p>This could be simpler and more maintainble in the future if it used a state machine for parsing. For this simple grammar we have the following valid sentences:</p>\n<ol>\n<li>I2C SCAN</li>\n<li>I2C READ n</li>\n<li>I2C WRITE n n</li>\n</ol>\n<p>I am assuming the <code>n</code> is a numeric value, but it's not clear from the context. Here's the corresponding state machine:</p>\n<p><a href=\"https://i.stack.imgur.com/n5i42.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/n5i42.png\" alt=\"simple state machine\" /></a>\nHere's one way to code that:</p>\n<pre><code>void parser_i2c(mychar str[20])\n{\n static const mychar s[2] = " ";\n enum { start, i2c, r1, w1, w2, error, done } state = start;\n mychar *n1 = NULL;\n for (mychar *token = strtok(str, s); state != done; token = strtok(NULL, s)) {\n switch (state) {\n case start:\n if (strcmp(token, "I2C") == 0) {\n state = i2c;\n } else {\n state = error;\n }\n break;\n case i2c:\n if (strcmp(token, "READ") == 0) {\n state = r1;\n } else if (strcmp(token, "WRITE") == 0) {\n state = w1;\n } else if (strcmp(token, "SCAN") == 0) {\n i2c_scan();\n state = done;\n } else {\n state = error;\n }\n break;\n case r1:\n /* check for number? */\n i2c_read(token);\n state = done;\n break;\n case w1:\n /* check for number? */\n n1 = token;\n state = w2;\n break;\n case w2:\n /* check for number? */\n i2c_write(n1, token);\n state = done;\n break;\n default:\n printf(COLOR_RED "Illegal state" COLOR_RESET);\n state = done;\n }\n if (state == error) {\n printf(COLOR_RED "Bad Command" COLOR_RESET);\n state = done;\n }\n }\n}\n</code></pre>\n<p>I've use <code>mychar</code> as a <code>typedef</code> for <code>char</code> on my machine. On yours, it looks like you could use <code>unsigned char</code> instead.</p>\n<p>Note that now, the flow is very easy to follow and it would not be at all difficult to make an alteration to the grammar to accommodate some other command. Because the tokens are handled as they're parsed, there's no need to store any except the first parsed number which we need for <code>i2c_write()</code>. If it gets any more complex than this, one could use a more sophisticated parser or use a tool like <code>flex</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T04:13:00.843",
"Id": "484582",
"Score": "0",
"body": "The sample input in the question is mixed case, but the code only checks for upper case commands."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T07:55:05.637",
"Id": "484592",
"Score": "0",
"body": "The original code also only checks for uppercase. If it works, so does this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T16:26:20.790",
"Id": "484638",
"Score": "0",
"body": "Interesting one liner `enum { start, i2c, r1, w1, w2, error, done } state = start;`. Hmmm."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T20:23:35.613",
"Id": "247538",
"ParentId": "247517",
"Score": "8"
}
},
{
"body": "<p>Some important remarks regarding performance:</p>\n<ul>\n<li><p>Calling <code>strcmp</code> repeatedly on the same data in some <code>if - else if</code> listing is naive and very inefficient. This will kill significant amounts of execution time, particularly on low-end microcontrollers.</p>\n<p>Instead you should have all valid strings stored in a sorted look-up table. Then use binary search on that table instead. You can use standard C <code>bsearch</code> or implement it yourself - it's not hard to do.</p>\n</li>\n<li><p>You probably don't want to use <code>strtok</code> since it destroys the data passed, which in turn means that you'll have to make additional hard copies of it in advance, which is inefficient. A simple <code>while(*ptr == ' ' && *ptr != '\\0') {}</code> could be used instead.</p>\n</li>\n<li><p>In general, you shouldn't need to make any calls to <code>strcpy</code> once you have copied the data from the I2C hardware buffers into RAM variables. Instead of shovelling whole data strings around, copy pointers if needed. Similarly, there should be no need to <code>memset</code> anything to zero.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-11T09:46:28.493",
"Id": "485139",
"Score": "0",
"body": "is there any example , cause for using bsearch i need to use strcmp or any other comparison method ,and strcmp will be used same number of time as using if(strcmp ..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-11T09:53:51.627",
"Id": "485141",
"Score": "0",
"body": "@G.ONE If rolling out the binary search manually, you don't need strcmp, which has the disadvantage of starting over from the first letter each time. Another alternative is a hash table, but that's mainly effective for larger amounts of strings."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-11T10:05:32.847",
"Id": "485143",
"Score": "0",
"body": "What do you mean by manually rolling it,bsearch function requires a comparison function itself ?Please provide an example"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-11T10:07:20.357",
"Id": "485144",
"Score": "0",
"body": "@G.ONE Manually implementing binary search, by keeping track of low/high/mid indices in a loop."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-11T08:48:50.317",
"Id": "247763",
"ParentId": "247517",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T10:15:04.820",
"Id": "247517",
"Score": "8",
"Tags": [
"c",
"parsing",
"embedded"
],
"Title": "Text Parsing in C on a microcontroller"
}
|
247517
|
<p>I am working on script to a upload image files Securely. can anyone please review my code and suggest improvements on security.</p>
<p><code><input type="file" name="images[]" id="image" multiple="multiple"></code></p>
<p>check if request method is POST and request was made from same domain and form was submitted with submit btn</p>
<pre><code>if (is_post_request() && is_request_same_domain() && isset($_POST['add-list-submit'])) {
</code></pre>
<p>Convert the $_FILES array to a cleaner version</p>
<pre><code>$images = rearrange_files_array($_FILES['images']);
function rearrange_files_array($file)
{
$file_array = [];
$file_count = count($file['name']);
$file_keys = array_keys($file);
for ($i = 0; $i < $file_count; $i++) {
foreach ($file_keys as $key) {
$file_array[$i][$key] = $file[$key][$i];
}
}
return $file_array;
}
</code></pre>
<p>Loop through the images</p>
<pre><code>foreach ($images as $image) {
</code></pre>
<p>Check if image was upload, image mime type, extension, and size</p>
<pre><code>if (!isset($image) || $image['error'] !== UPLOAD_ERR_OK) {
$errors['form'] = 'Please upload the images.';
} else {
if (!is_file_valid_image($image) || !has_valid_file_extension($image, ['jpeg', 'png', 'jpg'])) {
$errors['form'] = 'Only PNG and JPG file formats are allowed.';
}
if (has_max_file_size($image)) {
$errors['form'] = 'Max file size is 2.5 MB.';
}
}
function has_valid_file_extension($file, $allowed_file_extensions)
{
$file_extension = pathinfo($file['name'], PATHINFO_EXTENSION);
return in_array($file_extension, $allowed_file_extensions);
}
function is_file_valid_image($file)
{
$imageTypes = [IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_SWF, IMAGETYPE_PSD, IMAGETYPE_BMP, IMAGETYPE_TIFF_II, IMAGETYPE_TIFF_MM, IMAGETYPE_JPC, IMAGETYPE_JP2, IMAGETYPE_JPX, IMAGETYPE_JB2, IMAGETYPE_SWC, IMAGETYPE_IFF, IMAGETYPE_WBMP, IMAGETYPE_XBM, IMAGETYPE_ICO];
$info = getimagesize($file['tmp_name']);
$width = $info[0];
$height = $info[1];
$type = $info[2];
$bits = $info['bits'];
$mime = $info['mime'];
if (!in_array($type, $imageTypes)) {
return false; // Invalid Image Type
} else if ($width <= 1 && $height <= 1) {
return false; // Invalid Image Size
} else if ($bits === 1) {
return false; // One Bit Image
} else if ($mime !== 'image/gif' || $mime !== 'image/jpg' || $mime !== 'image/jpeg' || $mime !== 'image/png') {
return false; // Invalid Image Type
} else {
return true;
}
}
function has_max_file_size($file)
{
return $file['size'] > 2500000; // 2.5 MB
}
</code></pre>
<p>If there are no errors move the image to the uploads directory</p>
<pre><code>$filename = bin2hex(random_bytes(12));
$file_ext = pathinfo($image['name'])['extension'];
$upload_path = UPLOAD_DIRECTORY . '/' . $filename . '.' . $file_ext;
move_uploaded_file($image['tmp_name'], $upload_path);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T22:23:48.597",
"Id": "485546",
"Score": "0",
"body": "I am wondering: `} else if ($width <= 1 && $height <= 1) {`. Obviously an image cannot be less than 1x1 px but then why do you care since an image size of at least 2x2 px will pass your test ? This test is not useful."
}
] |
[
{
"body": "<p>If you are talking about a "secure" version then please state what you mean with it. What are you protecting against and which security requirements do you have extracted?</p>\n<pre><code>if (is_post_request() && is_request_same_domain() && isset($_POST['add-list-submit'])) {\n</code></pre>\n<p>This only indicates what it is doing. But it is doing too much on a line. If this is some particular check then please implement it in a well named function.</p>\n<blockquote>\n<p>Convert the $_FILES array to a cleaner version</p>\n</blockquote>\n<p>What does that even mean, a "cleaner version"?</p>\n<pre><code>function rearrange_files_array($file)\n</code></pre>\n<p>So it is apparently a rearranged array, but why? Please document your functions if it is not clear what they are doing. Furthermore, here even the "how" is missing: <strong>how</strong> is the array rearranged?</p>\n<pre><code>$errors['form'] = 'Please upload the images.';\n</code></pre>\n<p>Is this something that a user could do? I just select the images. If they don't get loaded into variables then I cannot fix that myself.</p>\n<pre><code>$errors['form'] = 'Only PNG and JPG file formats are allowed.';\n...\n$errors['form'] = 'Max file size is 2.5 MB.';\n</code></pre>\n<p>You have run into a common problem: putting all possible information in the error message while keeping the parameters generic. Please fix the error message so that the extensions and max file size are dynamic. Currently you would have to adjust both the function <em>and</em> the content of the error message separately to achieve one thing.</p>\n<p>You did let the extensions be the 2nd parameter of the <code>has_valid_file_extension</code> method. That's a good thing and you should perform the same for checking the file size. It will also bring the error and value of the file size closer together.</p>\n<p>It seems that you fall through the <code>if</code> statements when error checking; I'd expect the script to perform some kind of action, right? Currently only an error is set, but the script seems to continue.</p>\n<pre><code>$imageTypes = [IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_SWF, IMAGETYPE_PSD, IMAGETYPE_BMP, IMAGETYPE_TIFF_II, IMAGETYPE_TIFF_MM, IMAGETYPE_JPC, IMAGETYPE_JP2, IMAGETYPE_JPX, IMAGETYPE_JB2, IMAGETYPE_SWC, IMAGETYPE_IFF, IMAGETYPE_WBMP, IMAGETYPE_XBM, IMAGETYPE_ICO];\n</code></pre>\n<p>That's strange, I thought only JPEG and PNG were allowed. This is probably a more generic method. But even in that case: <strong>check the file extension first</strong> before running this method. You don't want to be checking some exotic file type only to find out that it is not allowed anyway; <em>always bring down the number of options / states of a program as soon as possible</em>.</p>\n<p>You may also wan to check that the extension is correct for the given image type, I don't see that happening.</p>\n<p>As an aside: <em>Obviously the method <code>getimagesize</code> is named terribly badly as it returns all kinds of information, but that's something to blame on PHP, not your script.</em></p>\n<pre><code>return false; // Invalid Image Type\n</code></pre>\n<p>This wipes out the actual error message, which means it will be impossible to inform the user correctly. You'd better return result which contains an error string or use a similar construct. I applaud you for at least including a comment, but if you have to type such comments then the code itself is often not verbose enough.</p>\n<pre><code>return false; // One Bit Image\n</code></pre>\n<p>Huh? No, that seems to be the bit <strong>depth</strong>. So it would be B/W or rather monochrome image.</p>\n<pre><code>else {\n return true;\n}\n</code></pre>\n<p>Just <code>return true</code> is enough here, the application has nowhere to go after all.</p>\n<hr />\n<p>All in all, it's not a bad attempt to me, but a few repairs and a lot of polishing seems in order.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T10:48:35.030",
"Id": "485484",
"Score": "0",
"body": "To be honest: failing to understand `rearrange_files_array` may well have caused this question to go without answer for a long time. I therefore simply put it down as \"unclear\"."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T10:43:28.980",
"Id": "247893",
"ParentId": "247520",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T11:39:36.150",
"Id": "247520",
"Score": "3",
"Tags": [
"php",
"security"
],
"Title": "Securely upload multiple image files with PHP"
}
|
247520
|
<p>I have implemented a LinkedList removal fo duplicates class by using HashMap.</p>
<p>Looking forward to your reviews.</p>
<p>Thanks.</p>
<pre><code>package test;
import main.algorithms.LinkedListRemoveDuplicates;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class LinkedListRemoveDuplicatesTest {
LinkedListRemoveDuplicates linkedListRemoveDuplicates;
@Before
public void setUp(){
linkedListRemoveDuplicates = new LinkedListRemoveDuplicates();
}
@Test
public void testRemoveDuplicates(){
linkedListRemoveDuplicates.addBack(5);
linkedListRemoveDuplicates.addBack(5);
linkedListRemoveDuplicates.addBack(5);
linkedListRemoveDuplicates.addBack(5);
linkedListRemoveDuplicates.addBack(5);
Assert.assertEquals(5, linkedListRemoveDuplicates.size());
linkedListRemoveDuplicates.removeDuplicates();
Assert.assertEquals(1, linkedListRemoveDuplicates.size());
}
}
package main.algorithms;
import java.util.HashMap;
public class LinkedListRemoveDuplicates {
Node head;
int size;
public void removeDuplicates() {
HashMap<Integer,Integer> duplicatesList = new HashMap<>();
Node currentNode = head;
if(size==1){
return;
}
// 2 1 3 1 2
while(currentNode != null ){
if(!duplicatesList.containsKey(currentNode.value)){
duplicatesList.put(currentNode.value,1);
}
currentNode = currentNode.next;
continue;
}
size = duplicatesList.size();
}
class Node{
int value;
Node next;
public Node(int value){
this.value = value;
}
}
public void addBack(int i) {
Node newNode = new Node(i);
if(head == null) {
head = newNode;
}else{
Node currentNode = head;
while(currentNode.next != null){
currentNode = currentNode.next;
}
currentNode.next = newNode;
}
size++;
}
public int size() {
return size;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T16:26:26.187",
"Id": "484538",
"Score": "1",
"body": "It doesn't remove the duplicates. It counts the unique elements."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T12:51:31.460",
"Id": "247522",
"Score": "2",
"Tags": [
"java",
"linked-list",
"hash-map"
],
"Title": "Linkedlist & hashmap _duplicates removal"
}
|
247522
|
<p>This is my first proper-ish project I've made. This was my first time using classes as well. I know that I made really stupid decisions, this is extremely far from being anywhere close to optimal, and probably made my future life hell if I decide to add things to this one day, but that's why I'm asking for help. I started coding again about 2 days ago and made this in a few hours:</p>
<pre><code>from random import random, randint
import time
print('Type "help" for a list of commands\n')
class normal_enemy:
enemy_count = 0
enemies = []
def __init__(self, name, health, damage_minmax, description):
self.name = name
self.health = health
self.damage_minmax = damage_minmax
self.description = description
__class__.enemies.append(self)
normal_enemy.enemy_count += 1
def observe(self):
print("\n\nIt's a " + self.name, "with " + str(self.health), "health, an accuracy of " + str(self.damage_minmax[0]), "and " + str(self.damage_minmax[1]), "strength!\n",\
"Description:", self.description)
return
dummy = normal_enemy("Dummy", 10, damage_minmax = (0, 0), description = "It's a dummy, dummy.")
skeleton = normal_enemy("Skeleton", 25, damage_minmax = (3, 5), description = "A bony creature, usually found wondering about in the woods or during the night. They aren't very strong, \
but their ability to stand is impressive, considering their significant lack of muscle tissue")
zombie = normal_enemy("Zombie", 40, damage_minmax = (1,14), description = "A dead creature risen from the land of the forgotten. It is extremely unpredictable seeing as their brain has rot quite significantly")
command_list = ['atk', 'attack', 'fight', 'pass', 'sleep', 'help', 'observe', 'block', 'defend', 'status']
help_text = "\nList of commands:\n\natk or attack: Attacks your opponent, dealing a random amount of damage\nfight: Enter a fight with a random opponent\npass or sleep: Pass your turn\nobserve: Observe your current opponent\nblock or defend: Halves your damage taken, but ends your turn. Always rounded down\nstatus: Displays your current health, as well as your opponent's\ndummy: dummy"
score = 0
enemy_hitpoints = 0
hitpoints = 100
maxhitpoints = 100
max_passes = 5
damage_minmax = 1, 10
misspercent = [5, 0]
misspercent[1] = misspercent[0]*12
in_fight = False
def status():
global in_fight
if hitpoints <= 0:
in_fight = False
print('\nYou lost\n')
time.sleep(0.5)
exit()
print("\nYou have", hitpoints, "out of", maxhitpoints, "hp remaining")
if in_fight == True:
print("\nYour opponent has", enemy_hitpoints, "out of", active_enemy.health, "hp remaining")
if u_input in command_list[9]:
print("\nYour probability of missing is", misspercent[0],"out of 100. Your accuracy is", damage_minmax[0], "and you have", damage_minmax[1], "strength\n\nYour current score is", score)
#Preparations and pre-maingame events above this
#Main gameplay loop bellow this
while True:
pass_counter = 0
while in_fight == False:
u_input = input('What would you like to do? >>> ').lower()
if u_input in command_list[5] or u_input in command_list[9]:
if u_input in command_list[9]:
status()
elif u_input in command_list[5]:
print(help_text)
else:
if u_input in command_list[2] and in_fight == False:
active_enemy = normal_enemy.enemies[randint (1, normal_enemy.enemy_count - 1)]
print('You encounter a wild', active_enemy.name + '!')
in_fight = True
elif in_fight == False and u_input not in command_list:
if u_input == 'dummy':
active_enemy = normal_enemy.enemies[0]
in_fight = True
else:
print('unknown command. Be sure to type "help" into the console for a list of commands')
elif in_fight == False:
print("You can't", u_input, "while outside of battle")
pass_dialogue = ["\nI'd recommend doing something while a " + active_enemy.name + ' is trying to murder you, but sure', \
"\nReally? Look. I won't stop you, but I am really questioning your strategical abilities right now...", \
"\nHave you considered attacking by any chance? Hell, you could just block dude. Did you even know that was a mechanic? Have you even read the help page?", \
"\n Here, since you just won't get the hint: " + '\n ' + help_text + '\n ' \
"\n \n Ok. That's it. I'm not letting you pass any more \n " \
""]
if in_fight == True:
enemy_hitpoints = active_enemy.health
while in_fight == True:
if active_enemy == normal_enemy.enemies[0]:
print('dummy')
turn_end = False
is_blocking = False
damage_dealt = 0
damage_taken = 0
u_input = input("What would you like to do? >>> ").lower()
if u_input in command_list:
if u_input in command_list[0:2]:
turn_end = True
damage_dealt = randint(damage_minmax[0], damage_minmax[1])
if randint(1, 100) <= misspercent[0]:
print('\nYou missed!')
else:
print('\nYou dealt ' + str(damage_dealt), 'damage!')
enemy_hitpoints -= damage_dealt
if u_input in command_list[5]:
print(help_text)
if u_input in command_list[3:5] and pass_counter < max_passes - 1:
print(pass_dialogue[pass_counter])
pass_counter += 1
turn_end = True
elif u_input in command_list[3:5]:
print ('no.')
if u_input in command_list[6]:
active_enemy.observe()
if u_input in command_list[7:9]:
is_blocking = True
turn_end = True
if u_input in command_list[9]:
status()
else:
print('unknown command. Be sure to type "help" into the console for a list of commands')
if turn_end == True:
if enemy_hitpoints <= 0:
print("\nVictory!\n")
score += 1
print('You return to your adventurey duties', '\n\ntype "help" into the console for a list of commands')
in_fight = False
active_enemy = ""
else:
damage_taken = randint(active_enemy.damage_minmax[0], active_enemy.damage_minmax[1])
print('\nYour turn has ended\n')
if is_blocking == True:
damage_taken /= 2
print('\nYou blocked half of the dealt damage!\n')
print(active_enemy.name, "dealt", int(damage_taken), "damage!")
hitpoints -= int(damage_taken)
status()
</code></pre>
<p>Any and all feedback is appreciated</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T00:56:11.007",
"Id": "484700",
"Score": "2",
"body": "_this is extremely far from being anywhere close to optimal, and probably made my future life hell if I decide to add things to this one day_ - Welcome to every programming project ;-)"
}
] |
[
{
"body": "<p>First of all, welcome to Coding. This is pretty advanced for a person who just started to code.</p>\n<p>Here are some tips:</p>\n<ul>\n<li><h3>Avoid importing stuff that you don't need:</h3>\n</li>\n</ul>\n<p>I see you have imported <code>random</code> from <code>random</code> but you did not use that, try to avoid doing that because it complicates things</p>\n<pre class=\"lang-py prettyprint-override\"><code>from random import randint # is better than from random import random, randint\n</code></pre>\n<ul>\n<li><h3>Use F-Strings</h3>\n</li>\n</ul>\n<p>F strings are a better (and more readable) way to incorporate values into a string.\nThis:</p>\n<pre class=\"lang-py prettyprint-override\"><code>print("\\n\\nIt's a " + self.name, "with " + str(self.health), "health, an accuracy of " + str(self.damage_minmax[0]), "and " + str(self.damage_minmax[1]), "strength!\\n",\\\n "Description:", self.description)\n</code></pre>\n<p>Can be replaced with this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>print(f"\\n\\nIt's a {self.name} with {self.health} health, an accuracy of {self.damage_minmax[0]} and {self.damage_minmax[1]} strength!\\n")\nprint(f" Description: {self.description}")\n</code></pre>\n<ul>\n<li><h3>Avoid unnecessary lines</h3>\n</li>\n</ul>\n<p>Adding a <code>return</code> at the end of a function when it does not return any values is an extra line of code that is not needed.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def someFunc():\n # Some code\n return # <-- This is an unnecessary line of code\n</code></pre>\n<ul>\n<li><h3>Avoid Global Variables</h3>\n</li>\n</ul>\n<p>Global Variables are the Zombies, You are a human. Zombies are bad for humans. In all seriousness, avoid global variables because the tend to complicate things.</p>\n<ul>\n<li><h3>Comment As Much As Possible</h3>\n</li>\n</ul>\n<p>Comments, Comments, Comments, Comments. Comment your code whenever possible, and write concise, descriptive comments. I see you have very little comments, please comment as much as possible, the person it helps the most is you.</p>\n<pre class=\"lang-py prettyprint-override\"><code># Uncommented\ndef observe(self):\n print(f"\\n\\nIt's a {self.name} with {self.health} health, an accuracy of {self.damage_minmax[0]} and {self.damage_minmax[1]} strength!\\n")\n print(f" Description: {self.description}")\n</code></pre>\n<p>With Comments:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def observe(self):\n """\n Prints the statistics and description of the normal enemy\n Takes No Arguments\n Returns Nothing\n """\n print(f"\\n\\nIt's a {self.name} with {self.health} health, an accuracy of {self.damage_minmax[0]} and {self.damage_minmax[1]} strength!\\n")\n print(f" Description: {self.description}")\n</code></pre>\n<p>I think that is it. Anyway, Nice Job with this being one of your first projects. It is a very solid project.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-28T21:25:06.763",
"Id": "251271",
"ParentId": "247525",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "251271",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T14:53:27.953",
"Id": "247525",
"Score": "4",
"Tags": [
"python",
"beginner",
"python-3.x"
],
"Title": "Text only turn based battle simulator"
}
|
247525
|
<p>The below is the C# implementation for the a function for given parameters <code>int a</code>, <code>int b</code> - both represent characters 'A' and 'B' respectively, where the function should return a string containing both characters 'A' and 'B' occurring <code>a</code> times and <code>b</code> times respectively but neither 'A' nor 'B' repeating consecutively for more than 2 times. Both values for <code>a</code> and <code>b</code> are given in a way that a string can be build using those numbers - so eg: <code>Foo(0,3)</code> or <code>Foo(1,7)</code> shall not be invoked.</p>
<p>eg:</p>
<p><code>Foo(3,3)</code> returns "<code>BBAABA</code>" or "<code>AABBAB</code>"</p>
<p><code>Foo(4,1)</code> returns "<code>AABAA</code>"</p>
<p><code>Foo(3,5)</code> returns "<code>BAABBABB</code>" or "<code>BBAABBAB</code>"</p>
<p>Code:</p>
<pre><code>static string Foo(int a, int b)
{
int total = a + b;
StringBuilder sb = new StringBuilder();
char charToPrint = a > b ? 'A' : 'B';
int flag = 0;
for(int x =0; x< total; x++)
{
if(flag == 2)
{
flag = 0;
charToPrint = SwapChar(charToPrint);
}
if(charToPrint == 'A' && a == 0 || charToPrint == 'B' && b == 0)
{
charToPrint = SwapChar(charToPrint);
}
if (charToPrint == 'A')
a--;
else
b--;
sb.Append(charToPrint);
flag++;
}
return sb.ToString();
}
static char SwapChar(char thisChar)
{
return thisChar == 'A' ? 'B' : 'A';
}
</code></pre>
<p>This is working but I would like to receive some feedback on this code.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T15:16:20.110",
"Id": "484535",
"Score": "0",
"body": "It looks like you've forgotten to include your `SwapChar` method. What is the code supposed to do when it is impossible to create a string with the requirements? E.g. `Foo(0, 3)` is impossible but your code returns `\"BBB\"` which violates the last rule."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T15:24:48.507",
"Id": "484536",
"Score": "0",
"body": "@RobH added the `SwapChar` method. Btw, I just edited the question to include the `Foo(0,3)` shall be called."
}
] |
[
{
"body": "<p>Your algorithm has a flaw - it's too greedy. Take this example:</p>\n<pre><code>Foo(6, 2) // "AABBAAAA"\n</code></pre>\n<p>Alas, it should return "AABAABAA".</p>\n<p>In terms of a review, your method shouldn't be called <code>Foo</code> - give it a descriptive name.</p>\n<p>Great use of <code>StringBuilder</code>. You could initialize the length to a+b in the constructor as you know what size your finished string will be.</p>\n<p>Expression bodied members can greatly improve readability in my opinion:</p>\n<pre><code>static char SwapChar(char c) => \n c == 'A' ? 'B' : 'A';\n</code></pre>\n<p>Try to avoid variables like <code>flag</code>. I had to read the whole loop before I knew what that variable meant. I'd call it something like <code>repeatCount</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T02:54:43.060",
"Id": "484574",
"Score": "0",
"body": "Thanks for the feedback and indicating the flaw"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T18:21:02.537",
"Id": "247534",
"ParentId": "247526",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T14:57:02.083",
"Id": "247526",
"Score": "7",
"Tags": [
"c#"
],
"Title": "Building a string with only two repeating characters"
}
|
247526
|
<p>I'm trying to insert data from ArrayList to HashMap<String, Language> optimally.</p>
<p>Many items may have the same languge_name (code below), so I need to group items having the same language in Language class and store languages in a HashMap with the name of the language as a Key.</p>
<p><strong>Item</strong></p>
<pre><code>String name;
String language_name;
</code></pre>
<p><strong>Language</strong></p>
<pre><code>String language_name;
int numberItems;
LinkedList<String> Items;
</code></pre>
<p>I solved this as follows:</p>
<pre><code> ArrayList<Item> items; // given array of items
HashMap<String, Language> languages = new HashMap<String, Language>();
items.forEach(item -> {
/** case 1: language isn't specified */
if (item.getLanguageName() == null) {
item.setLanguageName("unknown");
}
/** case 2: language already added */
if (languages.containsKey(item.getLanguageName())) {
languages.get(item.getLanguageName()).getItems().add(item.getName());
languages.get(item.getLanguageName())
.setNumberItems(languages.get(item.getLanguageName()).getNumberItems() + 1);
} else {
/** case 3: language isn't added yet */
LinkedList<String> languageItems = new LinkedList<String>();
languageItems.add(item.getName());
Language language = new Language(item.getLanguageName(), 1, languageItems);
languages.put(item.getLanguageName(), language);
}
});
</code></pre>
<p>Any help would be appreciated!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T06:41:09.780",
"Id": "484590",
"Score": "0",
"body": "Java Streams support collecting to maps. This page should explain how it is done: https://www.baeldung.com/java-collectors-tomap"
}
] |
[
{
"body": "<ol>\n<li><p>The Language class needs the "addItem()" method that combines incrementing numberItems and adding to the Items collection. The design intent here would be to hide the implementation details of adding an item.</p>\n</li>\n<li><p>The Language class needs a constructor for the first item added.</p>\n<pre><code> Language language = new Language(item);\n</code></pre>\n</li>\n<li><p>The languages map should be a specialization class of the HashMap, with its "add(item)" method to hide details of the new/existing item logic.</p>\n</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T16:03:10.667",
"Id": "247530",
"ParentId": "247528",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "247530",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T15:32:18.233",
"Id": "247528",
"Score": "2",
"Tags": [
"java",
"performance",
"hash-map"
],
"Title": "Optimize insertion from ArrayList to HashMap"
}
|
247528
|
<p>I need to perform some expensive calculation, such as determining a Fibonacci number:</p>
<pre class="lang-swift prettyprint-override"><code>/// Calculate the Nth Fibonacci number (inefficiently)
func fib(n: Int) -> Int {
n > 1 ? fib(n: n-1) + fib(n: n-2) : n
}
</code></pre>
<p>My project contains a number value types that need to perform calculations like <code>fib</code> based on their properties:</p>
<pre class="lang-swift prettyprint-override"><code>struct Fibber : Hashable {
/// The index in the sequence
var n: Int
/// The calculated Fibonacci number at _n_
var fibcalc: Int { fib(n: n) }
}
</code></pre>
<p>It works fine. But it is slow!</p>
<pre class="lang-swift prettyprint-override"><code>class FibberTests: XCTestCase {
func testFibCalc() {
measure { // average: 1.291, relative standard deviation: 1.5%
var fibber = Fibber(n: 1)
XCTAssertEqual(1, fibber.fibcalc)
fibber.n = 25
XCTAssertEqual(75_025, fibber.fibcalc)
fibber.n = 39
XCTAssertEqual(63_245_986, fibber.fibcalc)
}
}
}
</code></pre>
<p>So I make a single global dictionary that is keyed on <em>source code</em> location, and contains a map from a <code>Hashable</code> instance to the result of some arbitrary calculation:</p>
<pre class="lang-swift prettyprint-override"><code>/// Singleton global memoization cache, keyed on source code location and input hashable
private var memoized = Dictionary<String, Dictionary<AnyHashable, Any>>()
</code></pre>
<p>The cache key will be something like: "function:fibcalc file:Fibber.swift line:47".</p>
<p>Any Hashable instance can utilize this function to perform and memoize a calculation based on the key type, and return that cached value on subsequent invocations of the same call:</p>
<pre class="lang-swift prettyprint-override"><code>extension Hashable {
/// Caches and returns the result of the `calculation` function.
public func memoize<T>(function: StaticString = #function, file: StaticString = #file, line: Int = #line, _ calculation: (Self) -> T) -> T {
let cacheKey = "function:\(function) file:\(file) line:\(line)"
let hashKey = AnyHashable(self)
if let cached = memoized[cacheKey]?[hashKey] as? T { return cached }
if memoized[cacheKey] == nil { memoized[cacheKey] = Dictionary() }
let calculated = calculation(self)
memoized[cacheKey]?[hashKey] = calculated
return calculated
}
}
</code></pre>
<p>Memoizing these expensive calculations is now very simple:</p>
<pre class="lang-swift prettyprint-override"><code>extension Fibber {
/// The cached fib. Repeated calls on the same source instance will return the memoized result for this instance.
var fibmemo: Int { memoize(\.fibcalc) }
}
</code></pre>
<p>And we get an order-of-magnitude speedup!</p>
<pre class="lang-swift prettyprint-override"><code>extension FibberTests {
func testFibMemo() {
measure { // average: 0.132, relative standard deviation: 299.9%
var fibber = Fibber(n: 1)
XCTAssertEqual(1, fibber.fibmemo)
fibber.n = 25
XCTAssertEqual(75_025, fibber.fibmemo)
fibber.n = 39
XCTAssertEqual(63_245_986, fibber.fibmemo)
}
}
}
</code></pre>
<p><em>Assumptions:</em></p>
<ul>
<li>the Hashable key will always be a value type (this isn't currently enforceable in Swift)</li>
</ul>
<p><em>Non-Issues:</em></p>
<ul>
<li>Thread-safety: locking can be added to the cache later</li>
<li>Unbounded memory growth: <code>memoized</code> <code>Dictionary</code> will be converted to an <code>NSCache</code></li>
</ul>
<p><em>Valid Issues:</em></p>
<ul>
<li>Duck typing: the keys are <code>AnyHashable</code> and the values are <code>Any</code>, so runtime type conversion is used (yuck)</li>
</ul>
<p>My main question is: is this a good idea? Are there any issues with the cache key using the source location?</p>
|
[] |
[
{
"body": "<p>It sounds like you're on the right track, but the cache key needn't be so specific. Unless you're storing to the same cache/dictionary as other code is using, there won't be collisions.</p>\n<p>Since Fibonacci numbers build on the previous 2 numbers, recursion is a natural solution, but obviously gets slower for larger numbers. This post details a recursive memoization approach that seems like exactly what you're looking for:</p>\n<p><a href=\"https://www.hackingwithswift.com/plus/high-performance-apps/using-memoization-to-speed-up-slow-functions\" rel=\"nofollow noreferrer\">https://www.hackingwithswift.com/plus/high-performance-apps/using-memoization-to-speed-up-slow-functions</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-31T14:46:15.187",
"Id": "487251",
"Score": "0",
"body": "Welcome to Code Review! Could you elaborate on the memoization? After all, the basis for it is already mentioned in the question itself. Links can rot and your link specifically links to a subscription service."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-31T12:33:00.947",
"Id": "248697",
"ParentId": "247529",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T15:56:40.337",
"Id": "247529",
"Score": "1",
"Tags": [
"swift",
"memoization"
],
"Title": "Generic memoize function in Swift"
}
|
247529
|
<p>Writing a double-linked list seemed like a good practice for understanding it. I tried to fix all the errors that were pointed out to me in the <a href="https://codereview.stackexchange.com/questions/245602/optimizing-a-linked-list">last question</a>, as well as add new functionality. In General, I will be happy to receive new optimization tips and answers with instructions for bugs or memory leaks.</p>
<pre><code>#include <ctime>
#include <random>
template <typename T>
class QEList
{
private:
struct Node
{
Node *right;
Node *left;
T value;
Node(Node* left_a,const T& value_a, Node* right_a) : left(left_a), value(value_a), right(right_a) {}
Node(Node* left_a,Node* right_a) : left(left_a) , right(right_a) {}
};
public:
class const_iterator;
class iterator : public std::iterator<std::bidirectional_iterator_tag,Node,int,Node*,T>
{
friend class QEList;
friend class const_iterator;
private:
typename iterator::pointer ptr;
iterator(typename iterator::pointer ptr_a) : ptr(ptr_a) {}
public:
iterator& operator++()
{
ptr = ptr->right;
return *this;
}
iterator& operator--()
{
ptr = ptr->left;
return *this;
}
iterator operator++(int)
{
typename iterator::pointer temp = ptr;
ptr = ptr->right;
return temp;
}
iterator operator--(int)
{
typename iterator::pointer temp = ptr;
ptr = ptr->left;
return temp;
}
typename iterator::reference operator*() { return ptr->value; } //возвращает ссылку на значение узла
friend bool operator==(const iterator& i1, const iterator& i2){ return i1.ptr == i2.ptr; }
friend bool operator!=(const iterator& i1, const iterator& i2) { return !(i1 == i2); }
friend bool operator==(const iterator& iter, const const_iterator& c_iter);
friend bool operator!=(const iterator& iter, const const_iterator& c_iter);
};
class const_iterator : public std::iterator<std::bidirectional_iterator_tag,const Node,int,const Node *,const T>//comments from iterator are also relevant for const_iterator
{
friend class QEList;
private:
typename const_iterator::pointer ptr;
const_iterator(typename const_iterator::pointer ptr_a) : ptr(ptr_a) {}
public:
const_iterator(const iterator& iter) : ptr(iter.ptr) {}
const_iterator& operator++()
{
ptr = ptr->right;
return *this;
}
const_iterator& operator--()
{
ptr = ptr->left;
return *this;
}
const_iterator operator++(int)
{
typename const_iterator::pointer temp = ptr;
ptr = ptr->right;
return temp;
}
const_iterator operator--(int)
{
typename const_iterator::pointer temp = ptr;
ptr = ptr->left;
return temp;
}
typename const_iterator::reference operator*() { return ptr->value; }
friend bool operator==(const const_iterator& c_iter1, const const_iterator& c_iter2) { return c_iter1.ptr == c_iter2.ptr; }
friend bool operator!=(const const_iterator& c_iter1, const const_iterator& c_iter2) { return !(c_iter1 == c_iter2); }
friend bool operator==(const iterator& iter, const const_iterator& c_iter);
friend bool operator!=(const iterator& iter, const const_iterator& c_iter);
};
friend bool operator==(const iterator& iter, const const_iterator& c_iter) { return iter.ptr == c_iter.ptr; }
friend bool operator!=(const iterator& iter, const const_iterator& c_iter) { return !(iter == c_iter); }
QEList() = default;
template<typename... Types>
QEList(const T &value,Types&&... values) : QEList(values...)
{
push_front(value);
}
QEList(const QEList &QEL) { *this = QEL; }
QEList(const_iterator begin_pos,const const_iterator end_pos) // copies everything from begin_pos to end_pos (end_pos itself is not copied)
{
for(;begin_pos != end_pos;begin_pos++)
this->push_back(*begin_pos);
}
QEList(T &&value) { push_front(value); }
~QEList()
{
this->clear();
delete end_ptr;
}
void pop_back()//deletes the last node
{
Node* temp = end_ptr;
end_ptr = end_ptr->left;
end_ptr->right = nullptr;
delete temp;
m_size--;
}
void pop_front()//deletes the first node
{
Node* temp = head;
head = head->right;
head->left = nullptr;
delete temp;
m_size--;
}
void push_back(const T &value_a)//adds the value to the end of the list
{
end_ptr = new Node(end_ptr,nullptr);
end_ptr->left->value = value_a;
if(m_size > 0) end_ptr->left->left->right = end_ptr->left;
end_ptr->left->right = end_ptr;
m_size++;
}
void push_front(const T &value_a)//adds the value to the top of the list
{
head = new Node(nullptr,value_a,head);
head->right->left = head;
m_size++;
}
void clear()
{
Node *buffer;
for(int i = 0;i<m_size;i++)
{
buffer = head;
head = head->right;
delete buffer;
}
head = end_ptr;
m_size = 0;
}
void erase(const_iterator position)//deletes the node that the iterator points to (the iterator itself becomes hung)
{
if(position.ptr != head && position.ptr != end_ptr->left)
{
position.ptr->left->right = position.ptr->right;
position.ptr->right->left = position.ptr->left;
delete position.ptr;
m_size--;
}
else if(position.ptr == head)
{
this->pop_front();
}
else
{
this->pop_back();
}
}
void erase(const_iterator begin_pos,const const_iterator end_pos)//deletes everything from begin_pos to end_pos (end_pos itself is not deleted)
{
while(begin_pos != end_pos)
{
this->erase(begin_pos++);
}
}
iterator begin() { return iterator(head); }
const_iterator cbegin() const { return const_iterator(head); }
iterator end() { return iterator(end_ptr); }
const_iterator cend() const { return const_iterator(end_ptr); }
T& operator[](unsigned const int &index) const
{
if(index > (m_size-1)/2)
{
return scroll_node(-(m_size-1-index),end_ptr->left)->value;
}
else
{
return scroll_node(index,head)->value;
}
}
void operator=(const QEList &QEL)
{
this->clear();
auto iter = QEL.cbegin();
for(;iter != QEL.cend();iter++)
{
this->push_back(*iter);
}
}
size_t size() const { return m_size; }
private:
size_t m_size = 0;
Node *end_ptr = new Node(nullptr,nullptr);
Node *head = end_ptr;
Node* scroll_node(int index,Node* node_ptr) const //moves node_ptr to index forward(if index is negative ,then moves it back)
{
if(index > 0)
for(int i = 0; i < index;i++)
{
node_ptr = node_ptr->right;
}
else
{
index = abs(index);
for(int i = 0; i < index;i++)
{
node_ptr = node_ptr->left;
}
}
return node_ptr;
}
};
#include <iostream>
template<typename S>
QEList<S> qsort(const QEList<S> &lis)
{
srand(time(NULL));
if(lis.size() <= 1)
{
return lis;
}
QEList<S> min;
QEList<S> max;
QEList<S> elems;
S elem = lis[rand()%lis.size()];
auto iter = lis.cbegin();
for(;iter != lis.cend();iter++)
{
if(*iter > elem)
{
max.push_back(*iter);
}
else if(*iter < elem)
{
min.push_back(*iter);
}
else
{
elems.push_back(elem);
}
}
min = qsort(min);
iter = elems.cbegin();
for(;iter != elems.cend();iter++)
{
min.push_back(*iter);
}
max = qsort(max);
iter = max.cbegin();
for(;iter != max.cend();iter++)
{
min.push_back(*iter);
}
return min;
}
template<typename S>
QEList<S> selection_sort(QEList<S> lis)
{
QEList<int> lis2;
while(lis.size()>0)
{
auto largestIter = lis.begin();
auto iter = largestIter;
for(;iter != lis.end();iter++)
if(*iter > *largestIter)
largestIter = iter;
lis2.push_front(*largestIter);
lis.erase(largestIter);
}
return lis2;
}
int main()
{
QEList<int> lis(2345,342,5,3425,2,34,32,4,32,43,24,2,34);
QEList<int> lis2 = qsort(lis);
std::cout << "size lis: " << lis.size() << std::endl;//print size lis: 13
std::cout << "size lis2: " << lis2.size() << std::endl;//print size lis2: 13
for(int i = 0; i < lis2.size() ; i++)
std::cout << lis2[i] << std::endl;
/*
print:
2
4
5
24
32
32
34
34
43
342
2345
3425
*/
QEList<int> lis3(selection_sort(QEList<int>(1,23,4,54,54,6543,56,3546,23452,51,65,4)));
std::cout << "size lis3: " << lis3.size() << std::endl; //print 12
for(int i = 0; i < lis3.size() ; i++)
std::cout << lis2[i] << std::endl;
/*
print:
2
2
4
5
24
32
32
34
34
43
342
2345
*/
std::cout << clock()/static_cast<double>(CLOCKS_PER_SEC) << std::endl;
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T21:21:34.240",
"Id": "484552",
"Score": "2",
"body": "I am pretty rough in my reviews. Let me know if there is anything I can explain in more detail. More than happy to help a budding Engineer get better."
}
] |
[
{
"body": "<h2>Overview</h2>\n<p>Your class has a limitation that required <code>T</code> to have default constructor.</p>\n<p>Your class is not really suitable to hold anything but the most basic of types (like int/float) as removing elements does not guarantee that destructor of the removed element is called at that point. So your list can hold onto resources that will never be used.</p>\n<p>The copy constructor does not provide the strong exception guarantee, nor do you provide the standard swap operations nor the move semantics I would expect to see with a container class.</p>\n<p>In terms of adding elements I would also expect to see the ability to build objects of type <code>T</code> in place rather than forcing a copy of the object into the container.</p>\n<p>Overall a good first try but a few mistakes need to be cleaned up before this is ready.</p>\n<p>Please check out the reference implementation I wrote at then end of this answer:\n<a href=\"https://codereview.stackexchange.com/a/126007/507\">https://codereview.stackexchange.com/a/126007/507</a></p>\n<h2>Looking at compiler warnings:</h2>\n<pre><code>bash-5.0$ g++ -std=c++17 -Wall -Wextra -Werror -pedantic dl.cpp\ndl.cpp:289:22: error: comparison of integers of different signs: 'int' and 'size_t' (aka 'unsigned long') [-Werror,-Wsign-compare]\ndl.cpp:308:22: error: comparison of integers of different signs: 'int' and 'size_t' (aka 'unsigned long') [-Werror,-Wsign-compare]\ndl.cpp:13:48: error: field 'left' will be initialized after field 'right' [-Werror,-Wreorder]\ndl.cpp:12:80: error: field 'value' will be initialized after field 'right' [-Werror,-Wreorder]\ndl.cpp:142:28: error: comparison of integers of different signs: 'int' and 'size_t' (aka 'unsigned long') [-Werror,-Wsign-compare]\n\n5 errors generated.\n</code></pre>\n<p>Nothing major. I would fix them so that more serious warnings are made visible and you can compile your code at the highest warning level and make sure the code compiles with no warnings.</p>\n<p>Though in this case <code>error: field 'left' will be initialized after field 'right'</code> is not an issue it can be a serious problem with code. If you are reading the constructor and seeing a specific order of initialization of members that the class may depend on and that is not what is going to happen in reality then you can end up in some serious problems.</p>\n<h2>CodeReview</h2>\n<p>Curious why you need these headers. Lets find out.</p>\n<pre><code>#include <ctime>\n#include <random>\n</code></pre>\n<hr />\n<p>Some vertical spacing to make it easier to read please.</p>\n<pre><code>#include <random>\ntemplate <typename T>\nclass QEList\n</code></pre>\n<hr />\n<p>I would add all your code into a namespace for your code.<br />\nI have the website ThorsAnvil.com (So I put everything in ThorsAnvil namespace). But something like <code>namespace Qela {}</code> would work just as well.</p>\n<hr />\n<p>Interesting constructors:</p>\n<pre><code> Node(Node* left_a,const T& value_a, Node* right_a) : left(left_a), value(value_a), right(right_a) {}\n</code></pre>\n<p>The first constructor has an oddly defined initializer list that implies the <code>value</code> is initialized before <code>right</code>. But the members are initialized in order of declaration. So be careful of using another order as you may confuse people.</p>\n<p>Also the compiler would allow this initialization using a simple list initialization without you having to specify it (assuming there were no constructors).</p>\n<p>The second constructor:</p>\n<pre><code> Node(Node* left_a,Node* right_a) : left(left_a) , right(right_a) {}\n</code></pre>\n<p>Is odd in that you don't initialize the value. I don't see a situation where you are going to add a node without a value.</p>\n<p>There is also the issue that this means the type <code>T</code> must be default constructible. Otherwise this code will fail to compile. This is not a valid assumption for the general case.</p>\n<h3>Answer to Question: Where is the <code>T</code> default constructor called.</h3>\n<p>You call the default constructor of <code>T</code> when you create a <code>Node</code> object with explicitly initializing the <code>value</code> member.</p>\n<pre><code> // This constructor you have written:\n Node(Node* left_a,Node* right_a)\n : left(left_a)\n , right(right_a)\n {}\n\n // This is the same as writting:\n Node(Node* left_a,Node* right_a)\n : left{left_a}\n , right{right_a}\n , value{} // Even though you do not initialize value\n // the compiler must initialize this value.\n {}\n</code></pre>\n<p>Now you call this constructor in the <code>QEList</code> constructor when the <code>end_ptr</code> value is initialized.</p>\n<pre><code> // You add the is declaration to `QEList`\n Node *end_ptr = new Node(nullptr,nullptr);\n // This means on construction of the object you will call this.\n\n // So this declaration:\n QEList() = default;\n\n // Is equivalent to:\n QEList()\n : m_size{0}\n , end_ptr{new Node(nullptr,nullptr)} // This will call the above\n // Node constructor that in\n // turn calls the default T\n // constructor. \n , head{end_ptr}\n {}\n</code></pre>\n<p>You can test this all out by trying to add this:</p>\n<pre><code> class X\n {\n public:\n X(int){} // Because we define a constructor\n // the compiler will not generate a default\n // constructor for this class.\n // And we have not defined one either.\n };\n\n\n int main()\n {\n QEList<X> list;\n }\n</code></pre>\n<p>The above code will fail to compile.</p>\n<p>I would simply re-write this as:</p>\n<pre><code>struct Node\n{\n Node* right; // Note: putting the '*' next to the name is a C thing\n Node* left; // in C++ the '*' goes next to the type (usually).\n T value;\n};\n</code></pre>\n<hr />\n<p>This is now considered old:</p>\n<pre><code> typename iterator::pointer ptr;\n</code></pre>\n<p>The more modern incarnation is:</p>\n<pre><code> using ptr = iterator::pointer;\n</code></pre>\n<hr />\n<p>OK. From this implementation detail that you always have a one past the end node.</p>\n<pre><code>friend bool operator==(const iterator& i1, const iterator& i2){ return i1.ptr == i2.ptr; }\n</code></pre>\n<p>Otherwise you could not compare against the <code>end</code> iterator. Which is why you have the node constructor with no value.</p>\n<p>That's fine. But your one past the end node still contains an object of type <code>T</code> that will need default construction.</p>\n<hr />\n<p>You don't need to create (basically) the same class again. A template here with appropriate parameters should work:</p>\n<pre><code> class const_iterator : public std::iterator<std::bidirectional_iterator_tag,const Node,int,const Node *,const T>\n {\n ... STUFF\n };\n</code></pre>\n<p>Why not write it like this:</p>\n<pre><code> template<typename T, typename N>\n class Iterator: public std::iterator<std::bidirectional_iterator_tag, N, int, N*, T>\n {\n .... STUFF\n }\n using iterator = Iterator<T, Node>;\n using const_iterator = Iterator<const T, const Node>;\n</code></pre>\n<hr />\n<p>That's a queasy recursive definition:</p>\n<pre><code> template<typename... Types>\n QEList(const T &value,Types&&... values) : QEList(values...)\n {\n push_front(value);\n }\n</code></pre>\n<p>I suspect you wanted this to support a list of <code>T</code> to initialize the list with.</p>\n<p>But it also allows a couple of things I suspect you don't want:</p>\n<pre><code> QEList<int> list1;\n QEList<int> list2(5, list1);\n QELIST<int> list3(5, vec.begin(), vec.end());\n QELIST<int> list4(5, std::move(list2));\n</code></pre>\n<p>I would re-write to use <code>std::initalizaer_list</code></p>\n<pre><code> QEList(std::initializer_list<T> const& list)\n {\n for(value: list) {\n push_back(value);\n }\n }\n\n ....\n // now you can do:\n QEList list{1,2,3,4,5,6};\n</code></pre>\n<hr />\n<p>You are writing the copy constructor in terms of the assignment operator.</p>\n<pre><code> QEList(const QEList &QEL) { *this = QEL; }\n</code></pre>\n<p>Normally it is the other way around. You write the assignment operator in terms of the copy constructor (See Copy and Swap Idiom).</p>\n<p>Looking the assignment operator (which I found all the way at the bottom and private). Normally this would be public otherwise just make it a named function.</p>\n<pre><code> void operator=(const QEList &QEL)\n {\n this->clear();\n auto iter = QEL.cbegin();\n for(;iter != QEL.cend();iter++)\n {\n this->push_back(*iter);\n }\n }\n</code></pre>\n<p>This method does not provide the strong exception guarantee that I would expect from a copy constructor. So I would normally write these two methods like this:</p>\n<pre><code> QEList(const QEList& copy)\n {\n for(auto const& value: copy) {\n push_back(value);\n }\n }\n QEList& operator=(QEList const& copy)\n {\n QEList temp(copy);\n swap(temp);\n return *this;\n }\n void swap(QEList& other) noexcept\n {\n using std::swap;\n swap(head, other.head);\n swap(end_ptr, other.end_ptr);\n swap(m_size, other.m_size);\n }\n friend void swap(QEList& lhs, QEList& rhs)\n {\n lhs.swap(rhs);\n }\n</code></pre>\n<hr />\n<p>In the destructor you use <code>this-></code></p>\n<pre><code> ~QEList()\n {\n this->clear();\n delete end_ptr;\n }\n</code></pre>\n<p>This is a code smell. The only reason to use <code>this->x</code> over simply <code>x</code> is that you have an issue with shadowing the member <code>x</code> with a local variable. The compiler can not detect incorrect access to the local variable and thus can not warn you about it. This means this type of error is hard to spot and detect. It is better to never have shadowed variables (and get your compiler to warn you about variable shadowing). That way your code is easy to read and you always know what variable you are referring to as they have distinct names.</p>\n<hr />\n<p>Sure you are deleting the last element in the list correctly.</p>\n<pre><code> void pop_back()//deletes the last node\n {\n Node* temp = end_ptr;\n end_ptr = end_ptr->left;\n end_ptr->right = nullptr;\n delete temp;\n m_size--;\n }\n</code></pre>\n<p>But you are not deleting the object it contains. What happens if that object contains a DB cursor. You are now holding open a resource that will never be used.</p>\n<p>When I delete the last element from a list I expect the associated object to also be destroyed so that all its resources are cleanup.</p>\n<hr />\n<p>Same issue as <code>pop_back()</code>.</p>\n<pre><code> void pop_front()//deletes the first node\n</code></pre>\n<hr />\n<pre><code> void push_back(const T &value_a)//adds the value to the end of the list\n {\n end_ptr = new Node(end_ptr,nullptr);\n end_ptr->left->value = value_a;\n if(m_size > 0) end_ptr->left->left->right = end_ptr->left;\n end_ptr->left->right = end_ptr;\n m_size++;\n }\n</code></pre>\n<p>I think this can be simplified:</p>\n<pre><code> void push_back(const T &value_a)\n {\n Node* node = new Node(end_ptr->left, endptr, value_a);\n if(node->left) {\n node->left->right = node;\n }\n else {\n head = node;\n }\n node->right->left = node;\n ++m_size;\n }\n</code></pre>\n<hr />\n<pre><code> void clear()\n {\n ...\n // If this is not already true then you fucked up.\n // rather than explicityl throwing away a potential error\n // I would validate that this is true.\n head = end_ptr;\n m_size = 0;\n }\n</code></pre>\n<hr />\n<pre><code> void erase(const_iterator position)//deletes the node that the iterator points to (the iterator itself becomes hung)\n {\n\n // Is `end_ptr->left` always `nullptr`?????\n // I think you mean `position.ptr != end_ptr`\n if(position.ptr != head && position.ptr != end_ptr->left)\n</code></pre>\n<hr />\n<p>OK. This is logically correct.</p>\n<pre><code> void erase(const_iterator begin_pos,const const_iterator end_pos)//deletes everything from begin_pos to end_pos (end_pos itself is not deleted)\n {\n while(begin_pos != end_pos)\n {\n // You will see that most erase functions in the\n // standard return the next element after deleting.\n this->erase(begin_pos++);\n\n // The problem here is that this code is very brittle.\n // If we moved that `++` to the front it would easily\n // break the code (I think it would be undefined behavior).\n // Since the standard recomendation for C++ is to use\n // prefix ++ operations I can see a maintainer coming\n // along in a few years and potentially changing this\n // to the wrong version.\n //\n // I would change it so either.\n // A: Write a good comment why you can change the ++\n // B: Change erase() to return the next value to be\n // removed.\n }\n }\n</code></pre>\n<p>But could we not do it more effeciently?</p>\n<pre><code> void erase(const_iterator begin,const const_iterator end)\n {\n if (begin == end) {\n return;\n }\n if (begin.pos == head && end.pos == end_ptr) {\n clear();\n }\n else\n {\n if (begin.pos == head) {\n head = end.pos;\n }\n else {\n begin.pos->left->right = end.pos;\n }\n end.pos->left = begin.pos->left;\n\n Temp* next\n for(loop = begin.pos; loop != end.pos; loop = next) {\n next = loop->right;\n delete loop;\n }\n } \n }\n</code></pre>\n<hr />\n<p>That's a good start:</p>\n<pre><code> iterator begin() { return iterator(head); }\n const_iterator cbegin() const { return const_iterator(head); }\n iterator end() { return iterator(end_ptr); }\n const_iterator cend() const { return const_iterator(end_ptr); }\n</code></pre>\n<p>But you are missing a few definitions:</p>\n<pre><code> const_iterator begin() const { return const_iterator(head); }\n const_iterator end() const { return const_iterator(end_ptr); }\n</code></pre>\n<p>What about reverse iterator?</p>\n<pre><code> rbegin(), rend(), rbegin() const, rend() const\n</code></pre>\n<hr />\n<p>You can return a value by index.</p>\n<pre><code> T& operator[](unsigned const int &index) const\n</code></pre>\n<p>But that function should not be marked <code>const</code> unless you return a const reference to <code>T</code> or return <code>T</code> by value.</p>\n<p>Alternatively your would normally provide two versions of this method:</p>\n<pre><code> T& operator[](unsigned const int &index);\n T const& operator[](unsigned const int &index) const;\n</code></pre>\n<hr />\n<p>The qsort/selection sort should be a separate code reviews. There is a lot to fix above first.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T05:47:33.260",
"Id": "484583",
"Score": "0",
"body": "I would like to ask where the default constructor for T is called"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T06:46:30.290",
"Id": "484591",
"Score": "1",
"body": "@qela Have added a section above: `Answer to Question: Where is the T default constructor called.`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T20:21:08.453",
"Id": "247537",
"ParentId": "247531",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "247537",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T17:21:52.310",
"Id": "247531",
"Score": "4",
"Tags": [
"c++",
"c++11",
"linked-list",
"reinventing-the-wheel"
],
"Title": "Doubly-linked list with iterators"
}
|
247531
|
<p>I have implemented the topological sort.</p>
<p>Is there any suggestion for optimizing the solution?</p>
<p>Thanks.</p>
<pre><code>package src;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Stack;
class Graph{
int V;
LinkedList[] edges;
public Graph(int vertices){
V =vertices;
edges = new LinkedList[V];
for(int i=0;i<V;i++){
edges[i] = new LinkedList();
}
}
// Time complexity O(V+E)
public void topologicalSort() {
Stack stacks = new Stack();
boolean[] visited = new boolean[V];
for(int i=0;i<V;i++) {
if(!visited[i]){
topologicalSortUtil(i,visited,stacks);
}
}
while(!stacks.isEmpty()){
System.out.println(stacks.pop());
}
}
private void topologicalSortUtil(int i, boolean[] visited, Stack stacks) {
stacks.push(i);
visited[i] =true;
Iterator<Integer> iterator = edges[i].listIterator();
while(iterator.hasNext()){
int item = iterator.next();
if(!visited[item]){
topologicalSortUtil(item,visited,stacks);
}
stacks.push(item);
}
}
}
public class TopologicalSorting {
public static void main(String[] args) {
Graph graph = new Graph(8);
graph.topologicalSort();
}
}
package src;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Stack;
class Graph{
int V;
LinkedList[] edges;
public Graph(int vertices){
V =vertices;
edges = new LinkedList[V];
for(int i=0;i<V;i++){
edges[i] = new LinkedList();
}
}
// Time complexity O(V+E)
public void topologicalSort() {
Stack stacks = new Stack();
boolean[] visited = new boolean[V];
for(int i=0;i<V;i++) {
if(!visited[i]){
topologicalSortUtil(i,visited,stacks);
}
}
while(!stacks.isEmpty()){
System.out.println(stacks.pop());
}
}
private void topologicalSortUtil(int i, boolean[] visited, Stack stacks) {
stacks.push(i);
visited[i] =true;
Iterator<Integer> iterator = edges[i].listIterator();
while(iterator.hasNext()){
int item = iterator.next();
if(!visited[item]){
topologicalSortUtil(item,visited,stacks);
}
stacks.push(item);
}
}
}
public class TopologicalSorting {
public static void main(String[] args) {
Graph graph = new Graph(8);
graph.topologicalSort();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T13:08:04.107",
"Id": "484625",
"Score": "0",
"body": "Your source code is looking strange: you have shown two classes src.Graph as well as two src.TopologicalSorting (I didn't check whether they are identical or different), and I don't see how the graph is initialized - there just seems to be a constructor with empty lists."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T19:08:22.960",
"Id": "247535",
"Score": "3",
"Tags": [
"java",
"topological-sorting"
],
"Title": "Optimizing the topological sorting"
}
|
247535
|
<p>This is Merge Sort that i implemented, i feel i can make it better esp the combination function.</p>
<p>So i split the code into functions because i don't like seeing a bunch of spaghetti code in a single function. I have the combination logic which combines the left and right array such lower elements go first.</p>
<pre><code>def combine(left:list, right:list): #Combines both paths
left.append(float('inf')) #So the Array is never empty
right.append(float('inf')) #and the final element to compare is large
combined_list = []
while len(left) !=1 or len(right) != 1:
if left[0] < right[0]:
combined_list.append(left.pop(0))
else:
combined_list.append(right.pop(0))
return combined_list
</code></pre>
<p>Next i have this recursive function which calls itself and combination logic then after reducing the array into singular pieces then returns the bigger sorted chunks and hence final array is hence sorted.</p>
<pre><code>def merge_sort(array:list):
half_length = len(array)//2
left = array[:half_length]
right = array[half_length:]
if len(left) > 1:
left = merge_sort(left)
if len(right) > 1:
right = merge_sort(right)
return combine(left, right)
print(merge_sort([1,2,8,5,2,4,6,9,4,2]))
</code></pre>
<p>I feel that <code>left.append(float('inf'))</code> is a hack around, is there a better way of doing it spiting it into functions.</p>
|
[] |
[
{
"body": "<p>I understand what you're doing with <code>float('inf')</code>. Here is a possible way to make it a bit cleaner and more straightforward. Consider the following function:</p>\n<pre><code>def combine(left: list, right: list) -> list: \n combined_list = []\n \n # non-empty/non-empty case\n # - results in empty/non-empty OR non-empty/empty case\n while len(left) > 0 and len(right) > 0: \n if left[0] < right[0]:\n combined_list.append(left.pop(0))\n else:\n combined_list.append(right.pop(0))\n \n # empty/non-empty case OR empty/empty case\n # - One of these will be empty so extending by it will do nothing\n # - The other will have sorted items remaining that belong at the end of \n # the combined list anyway.\n # - If they are both empty this will simply do nothing.\n\n combined_list.extend(left)\n combined_list.extend(right)\n \n return combined_list\n</code></pre>\n<p>The resulting function is bit more straightforward in my opinion. Perhaps you'll agree.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T20:27:31.443",
"Id": "247539",
"ParentId": "247536",
"Score": "1"
}
},
{
"body": "<ul>\n<li><p><code>pop(0)</code> has a linear time complexity, which makes the entire time complexity quadratic.</p>\n</li>\n<li><p>The single most important advantage of merge sort is stability: the elements compare equal retain their original order. In your code, if two elements are equal the one from the right is merged first, and stability is lost.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T20:10:06.137",
"Id": "484684",
"Score": "0",
"body": "Thanks for review, but how do i get about removing the first element from the list while mutation it, should use ```combined_list.append(list[0]) and list=list [1:]``` or is there a better way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T20:53:35.677",
"Id": "484688",
"Score": "0",
"body": "Use indices. `combined_list.append(list[i]) and i += 1`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T21:42:45.443",
"Id": "247544",
"ParentId": "247536",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T19:18:34.893",
"Id": "247536",
"Score": "3",
"Tags": [
"python",
"algorithm",
"python-3.x"
],
"Title": "Merge Sort Implementation and Optimization"
}
|
247536
|
<p>I have to implement some business logic that will round a number (typically a double) upwards. Given that this number comes from a third-party and I don't know how they come to calculate it I'm anticipating errors in it. My proposed routine to mitigate rounding errors (like Math.ceil(1.000000000000002) = 2) is as follows:</p>
<pre><code>export const roundupDiscount = (discount: number) => {
// We have to give advantage to the customer for the discount value when rounding,
// that is to say, we will sacrifice the penny when we can't be exact. This means
// we have to always round the discount upwards (so we can't Math.round because
// half the time we'll round in the wrong direction.)
// To account for numbers like, say, 1.000000000000002 (i.e. (1 / 5 / 7) * 5 * 7))
// then we subtract off a "small" number (scaled with the magnitude of discount)
// which will nudge below the number we will round up to
if (!discount) return 0 // discount shouldn't be negative
const magnitude = Math.floor(Math.log(discount) / Math.log(10))
const epsilon = Math.pow(10, magnitude - 14)
return Math.ceil(discount - epsilon)
}
</code></pre>
<p>Given that a double has between 15-17 significant digits in it, I'm choosing epsilon, arbitrarily, such that I have a couple of trailing digits to play with.</p>
<p>Can anybody spot any cases where this is going to get things wrong? simplify this thing, or, given this is node.js point me towards an npm module that does this kind of thing for me?</p>
<p>Note: I have to get this past code-review at work so I'd much prefer if there was a good library out there that I can use instead and not even bother submitting this!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T17:07:45.623",
"Id": "484777",
"Score": "1",
"body": "Please explain what `roundupDiscount` should do, not more on how it works, but what it should do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T18:29:29.203",
"Id": "484793",
"Score": "0",
"body": "That's a good point, I suppose that's a bad habit of mine. Addressed this issue in my answer"
}
] |
[
{
"body": "<p><strong>Discovered this needs rework</strong></p>\n<p>Testing this with small numbers shows that for all practical purposes, this function is broken. I'd like <code>roundupDiscount(Number.EPSILON)</code> to be 0 (which could come about from subtracting two numbers meant to be equal, but differing by an error (similar to the classic (0.1 + 0.2) - 0.3)).</p>\n<p>However for a number like Number.EPSILON its value, including significant digits, is 0.000000000000000222044604925031, and so the computed epsilon here being 10e-28 is way too small to have any effect. This function only really works when the integer part > 0</p>\n<p>It can be corrected in this respect by clamping the magnitude at 0 but I think I'll have a battle to convince anyone this should go into our codebase ...</p>\n<p><strong>Updated implementation:</strong></p>\n<pre><code>export const roundupDiscount = (discount: number) => {\n // Given that discount is "sensible", if it is equal to some integer x plus a\n // small positive error component, then it must return x. Otherwise it must\n // return Math.ceil(discount)\n \n if (discount < 0 || discount > Number.MAX_SAFE_INTEGER) return discount\n if (discount < Number.EPSILON) return 0\n \n const magnitude = Math.floor(Math.max(0, Math.log(discount) / Math.log(10)))\n const epsilon = Math.pow(10, magnitude - 12) // treat last 3-4 significant digits as error\n return Math.abs(Math.ceil(discount - epsilon)) // Math.abs to prevent -0\n} \n</code></pre>\n<p><strong>Test cases:</strong></p>\n<pre><code>describe('roundupDiscount', () => {\n it('rounds the item discount correctly for numbers of differing magnitude', () => {\n let epsilon = Number.EPSILON; // machine epsilon - smallest positive number which, added to 1, will produce a value different from 1\n\n expect(roundupDiscount(1 + epsilon)).toBe(1)\n expect(roundupDiscount(1 + (10 * epsilon))).toBe(1)\n expect(roundupDiscount(1 + (100 * epsilon))).toBe(1)\n expect(roundupDiscount(1 + (1000 * epsilon))).toBe(1)\n expect(roundupDiscount(1 + (10000 * epsilon))).toBe(2) // "error" no longer small\n\n // test it handles large numbers ...\n const largeNum = 1000000000;\n const largeEpsilon = largeNum * epsilon;\n expect(roundupDiscount(largeNum + largeEpsilon)).toBe(largeNum)\n expect(roundupDiscount(largeNum + (10 * largeEpsilon))).toBe(largeNum)\n expect(roundupDiscount(largeNum + (100 * largeEpsilon))).toBe(largeNum)\n expect(roundupDiscount(largeNum + (1000 * largeEpsilon))).toBe(largeNum)\n expect(roundupDiscount(largeNum + (10000 * largeEpsilon))).toBe(largeNum + 1)\n\n // test it handles small numbers ...\n expect(roundupDiscount(epsilon)).toBe(0)\n expect(roundupDiscount(10 * epsilon)).toBe(0)\n expect(roundupDiscount(100 * epsilon)).toBe(0)\n expect(roundupDiscount(1000 * epsilon)).toBe(0)\n expect(roundupDiscount(10000 * epsilon)).toBe(1)\n })\n})\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T17:04:51.273",
"Id": "484776",
"Score": "1",
"body": "How does `if (!discount) return 0 // discount shouldn't be negative` detect negative? Looks like it detects 0. Perhaps `if (discount <= 0) return 0`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T18:32:32.583",
"Id": "484794",
"Score": "0",
"body": "Now you mention it, I was assuming that we would have bailed out long before calling this if it was negative, but as a standalone function presented here, reviewers couldn't have known this. That said, given Murphy's laws and all, the only sensitive thing to do if it is negative is to throw an error or just return it unchanged - I prefer the latter here."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T15:45:45.177",
"Id": "247573",
"ParentId": "247540",
"Score": "1"
}
},
{
"body": "<blockquote>\n<p>I'd like <code>roundupDiscount(Number.EPSILON)</code> to be 0</p>\n</blockquote>\n<p>The below code is dodgy. <code>Math.log()</code> finds the logarithm, base <em>e</em> and is <em>never</em> exactly correct except for <code>Math.log(1)</code>.</p>\n<pre><code>const magnitude = Math.floor(Math.max(0, Math.log(discount) / Math.log(10)))\n</code></pre>\n<p>Better to start with <code>Math.log10</code> which is far more likely to provide the desired result for <code>discount == powers-of-10</code>.</p>\n<pre><code>Math.floor(Math.max(0, Math.log10(discount)))\n</code></pre>\n<p>Still I find this approach weak.</p>\n<hr />\n<p>Code is really trying to perform a <code>ceiling()</code> on values unless they are only a "little above" an integer value to compensate for computational errors. That "little above" being controlled by <code>- 12</code> to form 10<sup>-12</sup> or some similar value.</p>\n<p>Now code introduces more errors in determining <code>magnitude</code> that get amplified with <code>floor()</code>.</p>\n<p>IMO, to truly handle edge cases well, use your functions that are designed to convert the binary nature of floating point value to decimal text.</p>\n<p>I, not being <code>node.js</code> savvy, take this code idea as a guide.</p>\n<p><a href=\"https://stackoverflow.com/a/30106316/2410359\"><code>.toLocaleString()</code></a> to form the string of the rounded value to as many digits you like.</p>\n<p>Then <a href=\"https://stackoverflow.com/a/642674/2410359\"><code>parseFloat()</code></a> to form the floating point value.</p>\n<p>I'd expect this to be slow, but that is a the cost of business.</p>\n<hr />\n<p>Even if this approach is too slow, it does serves as reference code to compare the proper functionality of alternate code.</p>\n<hr />\n<p>Personally, I'd try to scale value down a "little bit" and then apply the ceiling.<br />\n(Adding 0.0 should prevent any -0.0 sum.)</p>\n<pre><code>Math.ceil(discount * (1 - 1.1E-12)) + 0.0\n// ^^ or 11, 13, ...\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T06:11:46.380",
"Id": "249256",
"ParentId": "247540",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T21:07:11.880",
"Id": "247540",
"Score": "7",
"Tags": [
"node.js",
"typescript",
"floating-point"
],
"Title": "Accounting for floating point error when rounding"
}
|
247540
|
<p>I can't find an answer to this question either because it doesn't exist or because I am incapable of searching for it correctly.</p>
<p>Consider this code which prints out the numbers from 1 to 12 ad infinitum:</p>
<pre><code>month = 1
while True:
print(month)
month += 1
if month == 13: # month >= 13 ? month > 12 ?
month = 1
</code></pre>
<p>Is there any reason that the line <code>if month == 13</code> shouldn't be written as <code>if month > 12</code>, you know, "just in case?" I feel like it's "safer" to write <code>if month > 12</code> or <code>if month >= 13</code>, but I <em>know</em> that <code>month > 13</code> will <em>never</em> be true. Is there any agreed-upon best practice in a situation like this?</p>
<p>To be clear, I'm not looking for a way to improve this specific code. I'm looking for guidance on what I should do in this situation (and others like it).</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T22:37:33.553",
"Id": "484556",
"Score": "2",
"body": "\"I know that `month > 13` will never be true\": it's possible https://stackoverflow.com/q/2580933. \"what I should do in this situation\": use the `%` (modulus) operator"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T01:12:33.990",
"Id": "484564",
"Score": "1",
"body": "I find those alternatives misleading, as they suggest that it *can* be larger than 13. I find `== 13` much clearer."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T21:11:31.173",
"Id": "247541",
"Score": "2",
"Tags": [
"python"
],
"Title": "Using >= even though it's impossible for > to be true"
}
|
247541
|
<p>I am new to programming. I tried to write a valid Sudoku <em>solver</em> with backtracking, the performance is disappointing.</p>
<p>So, I tried to generate a valid Sudoku generator without backtracking.</p>
<p>The white paper implementation is 1/3 of the required numbers of strategy to generate valid Sudoku without problem. The other 2/3 is still not published because it is still in theory.</p>
<p>I spent 4 days to refactor the code, do you think the code is worth of 4 days?</p>
<p>Feel free to recommend me something to read, or how to make my code more maintainable.</p>
<p>The github repository: <a href="https://github.com/kidfrom/sudoku_js" rel="nofollow noreferrer">https://github.com/kidfrom/sudoku_js</a></p>
<p>The white paper: <a href="https://github.com/kidfrom/sudoku_js/blob/master/dump/white_paper.MD" rel="nofollow noreferrer">https://github.com/kidfrom/sudoku_js/blob/master/dump/white_paper.MD</a></p>
<p>The code: <a href="https://github.com/kidfrom/sudoku_js/blob/master/assets/js/generateSudoku.js" rel="nofollow noreferrer">https://github.com/kidfrom/sudoku_js/blob/master/assets/js/generateSudoku.js</a></p>
<pre><code>let subGridRowLength;
let subGridLength;
let gridRowLength;
let gridLength;
function newGrid(value) {
// reset global variables
gridNestedArray = [];
statusNestedArray = [];
// global variables;
subGridRowLength = value;
subGridLength = Math.pow(subGridRowLength, 2);
gridRowLength = Math.pow(subGridRowLength, 2);
gridLength = Math.pow(subGridRowLength, 4);
let gridFlatArray = [];
let statusFlatArray = [];
for (let i = 0; i < gridLength; i++) {
gridFlatArray.push(0);
statusFlatArray.push(undefined);
}
return flatToNestedArray(gridFlatArray, statusFlatArray);
}
let gridNestedArray = [];
let statusNestedArray = []; // true = sorted, false = not sorted yet.
function flatToNestedArray(gridFlatArray, statusFlatArray) {
let i = 0;
for (i = 0; i < gridLength; i += gridRowLength) {
let tempGridRow = gridFlatArray.slice(i, i + gridRowLength);
gridNestedArray.push(tempGridRow);
let tempStatusRow = statusFlatArray.slice(i, i + gridRowLength);
statusNestedArray.push(tempStatusRow);
}
return populateTheNestedArray();
}
function populateTheNestedArray() {
// r0, c0 is relative to the Grid. r0, c0 is the NestedArray[0][0] of each subGrid.
// rSG, cSG is relative to the subGrid.
for (let r0 = 0; r0 < gridRowLength; r0 += subGridRowLength) {
for (let c0 = 0; c0 < gridRowLength; c0 += subGridRowLength) {
let numbers = possibleNumbers();
for (let rSG = 0; rSG < subGridRowLength; rSG++) {
for (let cSG = 0; cSG < subGridRowLength; cSG++) {
n = Math.floor(Math.random() * gridRowLength + 1); // random 1 to 9
if (numbers.indexOf(n) > -1) {
numbers.splice(numbers.indexOf(n), 1); // prevent double numbers within the subGrid.
gridNestedArray[r0 + rSG][c0 + cSG] = n;
} else cSG--; // loop until random generated n = numbers.
}
}
}
}
// debug only: ERROR steps 2 vertical needs new strategy || Fixed
// subGridRowLength = 2;
// gridNestedArray = [
// [3, 2, 1, 2],
// [1, 4, 4, 3],
// [2, 3, 1, 3],
// [1, 4, 4, 2]
// ];
// debug only: ERROR steps 3 horizontal needs new strategy || Fixed
// subGridRowLength = 2;
// gridNestedArray = [
// [1, 4, 3, 2],
// [2, 3, 1, 4],
// [4, 2, 4, 3],
// [3, 1, 2, 1]
// ];
// debug only: ERROR horizontal steps 3 needs new strategy || Fixed
// subGridRowLength = 2;
// gridNestedArray = [
// [3,4,3,2],
// [1,2,1,4],
// [4,2,3,2],
// [3,1,1,4]
// ];
// debug only: ERROR vertical steps 8 needs new strategy || Fixed
// debug only: ERROR horizontal steps 7 needs new strategy -> bug occured again after adjustment to follow the Swap, Sort, Shrink strategy.
// subGridRowLength = 3;
// gridNestedArray = [
// [5, 8, 3, 1, 9, 6, 7, 2, 8],
// [9, 7, 6, 2, 4, 5, 4, 3, 1],
// [1, 4, 2, 3, 8, 7, 5, 6, 9],
// [7, 2, 4, 6, 3, 1, 5, 9, 7],
// [8, 9, 1, 5, 2, 8, 6, 4, 3],
// [6, 3, 5, 4, 7, 9, 2, 1, 8],
// [2, 1, 8, 7, 5, 2, 6, 9, 5],
// [3, 6, 7, 9, 1, 4, 8, 3, 4],
// [4, 5, 9, 8, 6, 3, 1, 7, 2]
// ];
// debug only: ERROR vertical steps 2 needs new strategy
// subGridRowLength = 2;
// gridNestedArray = [
// [3, 2, 3, 1],
// [4, 1, 2, 4],
// [3, 4, 3, 1],
// [1, 2, 2, 4]
// ];
// debug only: ERROR vertical steps 1 needs new strategy
// subGridRowlength = 2;
// gridNestedArray = [
// [8,4,5,4,6,3,1,6,9],
// [3,1,2,9,8,7,4,8,3],
// [9,6,7,1,5,2,5,2,7],
// [2,3,4,6,7,3,1,9,8],
// [8,1,6,9,4,5,2,5,4],
// [7,5,9,8,1,2,7,3,6],
// [2,9,5,4,9,8,3,2,8],
// [7,1,3,3,1,7,4,6,5],
// [6,4,8,5,6,2,9,7,1]
// ];
// debug only: ERROR horizontal steps 4 needs new strategy
// subGridRowLength = 3;
// gridNestedArray = [
// [4,6,7,5,3,8,9,3,8],
// [3,8,9,6,9,1,1,6,5],
// [2,5,1,2,7,4,2,7,4],
// [9,2,3,6,9,1,9,8,4],
// [8,1,4,2,8,4,7,3,5],
// [6,5,7,5,7,3,6,2,1],
// [5,6,9,2,6,9,5,2,3],
// [8,7,3,5,7,8,8,7,6],
// [4,1,2,4,3,1,1,9,4]
// ];
// debug only
console.log(`=== Start: Before Fix ===`)
console.log(JSON.stringify(gridNestedArray));
console.log(`=== End ===`)
return loopsteps();
}
function possibleNumbers() {
let numbers = [];
for (let n = 1; n <= gridRowLength; n++) {
numbers.push(n);
}
return numbers;
}
function loopsteps() {
// horizontal steps 0 -> veritcal steps 0 -> horizontal steps 1 -> repeat
for (let steps = 0; steps < gridRowLength; steps++) {
if (check("horizontal", steps, "canFix") === false) {
console.log(`ERROR horizontal steps ${steps} needs new strategy`);
break;
}
if (check("vertical", steps, "canFix") === false) {
console.log(`ERROR vertical steps ${steps} needs new strategy`);
break;
}
}
}
function check(turns, steps, request) {
if (isValid(turns, steps) === true) {
updateStatus(turns, steps);
} else if (isValid(turns, steps) === false) {
// TODO: add new strategy
// swap unsorted with unsorted
if (sortWithSG(turns, steps, "canSort") === true) {
sortWithSG(turns, steps, "sort");
check(turns, steps); // recursive
}
// swap the nextLastIndexOf duplicate.
else if (sortWithSG(turns, steps, "canSort", true) === true) {
sortWithSG(turns, steps, "sort", true);
check(turns, steps); // recursive
}
else if (request === "canFix") return false;
}
}
function isValid(turns, steps) {
let tempFlatArray = [];
// horizontal
if (turns === "horizontal") {
tempFlatArray = gridNestedArray[steps];
}
// vertical
else if (turns === "vertical") {
tempFlatArray = columnToFlatArray(steps);
}
// ERROR
else {
console.log(`ERROR isValid(${turns}) the turns' parameter is not found`);
return;
}
if (new Set(tempFlatArray).size !== tempFlatArray.length) {
return false; // isValid false
}
// check passed: isValid true
if (turns === "horizontal" || turns === "vertical") return true;
}
function columnToFlatArray(steps) {
let tempFlatArray = [];
for (let i = 0; i < gridRowLength; i++) tempFlatArray.push(gridNestedArray[i][steps]);
return tempFlatArray;
}
function updateStatus(turns, steps) {
for (let i = gridRowLength - 1; i >= 0; i--) {
// horizontal
if (turns === "horizontal" && typeof statusNestedArray[steps][i] === 'undefined') {
statusNestedArray[steps][i] = steps;
}
// vertical
else if (turns === "vertical" && typeof statusNestedArray[i][steps] === 'undefined') {
statusNestedArray[i][steps] = steps;
}
}
}
function sortWithSG(turns, steps, request, next) {
let index;
if (typeof next === 'undefined') {
index = listDuplicates(turns, steps, "lastIndexOf");
}
// nextLastIndexOf
else if (next === true) {
index = listDuplicates(turns, steps, "nextLastIndexOf");
}
let tempSubGrid = [];
let tempFlatArray = [];
if (turns === "horizontal") {
tempFlatArray = gridNestedArray[steps];
if (typeof statusNestedArray[steps][index] === 'undefined') {
tempSubGrid = subGrid(turns, steps, index);
} else if (typeof statusNestedArray[steps][index] != 'undefined') {
tempSubGrid = subGrid("vertical", index, steps); // inverted
}
} else if (turns === "vertical") {
tempFlatArray = columnToFlatArray(steps);
if (typeof statusNestedArray[index][steps] === 'undefined') {
tempSubGrid = subGrid(turns, steps, index);
} else if (typeof statusNestedArray[index][steps] != 'undefined') {
tempSubGrid = subGrid("horizontal", index, steps); // inverted
}
}
// debug only
if (turns === "horizontal") {
console.log(`${turns} steps ${steps} index ${index}
sort status ${statusNestedArray[steps][index]}
tempFlatArray ${tempFlatArray}
tempSubGrid ${tempSubGrid}`
);
} else if (turns === "vertical") {
console.log(`${turns} index ${index} steps ${steps}
sort status ${statusNestedArray[index][steps]}
tempFlatArray ${tempFlatArray}
tempSubGrid ${tempSubGrid}`
);
}
for (let i = 0; i < tempSubGrid.length; i++) {
if (typeof tempSubGrid[i] === 'undefined' ||
tempFlatArray.indexOf(tempSubGrid[i]) > -1
) continue;
if (tempFlatArray.indexOf(tempSubGrid[i]) === -1) {
// request: canSort
if (request === "canSort") {
return true;
}
// request: sort
else if (request === "sort") {
let rSG = Math.floor(
Math.floor(i / subGridRowLength)
);
let cSG = i % subGridRowLength;
// horizontal
if (turns === "horizontal") {
let r0 = Math.floor(
Math.floor(steps / subGridRowLength) * subGridRowLength
);
let c0 = Math.floor(
Math.floor(index / subGridRowLength) * subGridRowLength
);
gridNestedArray[steps][index] = [
gridNestedArray[r0 + rSG][c0 + cSG],
gridNestedArray[r0 + rSG][c0 + cSG] = gridNestedArray[steps][index]
][0];
}
// vertical
else if (turns === "vertical") {
let r0 = Math.floor(
Math.floor(index / subGridRowLength) * subGridRowLength
);
let c0 = Math.floor(
Math.floor(steps / subGridRowLength) * subGridRowLength
);
gridNestedArray[index][steps] = [
gridNestedArray[r0 + rSG][c0 + cSG],
gridNestedArray[r0 + rSG][c0 + cSG] = gridNestedArray[index][steps]
][0];
}
}
}
}
}
function listDuplicates(turns, steps, request, index) {
let tempFlatArray = [];
// horizontal
if (turns === "horizontal") {
tempFlatArray = gridNestedArray[steps];
}
// vertical
else if (turns === "vertical") {
tempFlatArray = columnToFlatArray(steps);
}
else {
console.log(`ERROR listDuplicates(${turns}, steps, request) turns' parameter is not found`);
return;
}
// request: lastIndexOf
if (request === "lastIndexOf") {
let tempDuplicates = listDuplicates(turns, steps, "list");
return tempFlatArray.lastIndexOf(
tempDuplicates[tempDuplicates.length - 1]
); // index
}
// request: nextLastIndexOf
if (request === "nextLastIndexOf") {
let tempDuplicates = listDuplicates(turns, steps, "list");
return tempFlatArray.lastIndexOf(
tempDuplicates[tempDuplicates.length - 1],
tempFlatArray.lastIndexOf(
tempDuplicates[tempDuplicates.length - 1]
) - 1
); // index
}
// request: list
else if (request === "list") {
return tempFlatArray.filter(
(item, index) => tempFlatArray.indexOf(item) != index
); // list
}
else console.log(`ERROR listDuplicates(turns, steps, ${request}) request' parameter is not found`);
}
function subGrid(turns, steps, index) {
let tempSubGrid = [];
// r0, c0 is relative to the Grid. r0, c0 is the 0,0 of each subGrid.
let r0;
let c0;
// horizontal
if (turns === "horizontal") {
r0 = Math.floor(
Math.floor(steps / subGridRowLength) * subGridRowLength
);
c0 = Math.floor(
Math.floor(index / subGridRowLength) * subGridRowLength
);
}
else if (turns === "vertical") {
r0 = Math.floor(
Math.floor(index / subGridRowLength) * subGridRowLength
);
c0 = Math.floor(
Math.floor(steps / subGridRowLength) * subGridRowLength
);
}
// rSG, cSG is relative to the subGrid.
for (let rSG = 0; rSG < subGridRowLength; rSG++) {
for (let cSG = 0; cSG < subGridRowLength; cSG++) {
// horizontal
if (turns === "horizontal") {
// if sorted
if (typeof statusNestedArray[steps][index] != 'undefined') {
// cSG > index % subGridRowLength; is to prevent accidentally resorting sorted row.
if (statusNestedArray[r0 + rSG][c0 + cSG] === steps && cSG > index % subGridRowLength) tempSubGrid.push(gridNestedArray[r0 + rSG][c0 + cSG]);
else tempSubGrid.push(undefined);
}
// if not sorted
else if (typeof statusNestedArray[steps][index] === 'undefined') {
if (rSG === 0 || typeof statusNestedArray[r0 + rSG][c0 + cSG] != 'undefined') {
tempSubGrid.push(undefined);
continue; // prevent overlapping with the next if statement.
}
tempSubGrid.push(gridNestedArray[r0 + rSG][c0 + cSG]);
}
}
// vertical
else if (turns === "vertical") {
// if sorted
if (typeof statusNestedArray[index][steps] != 'undefined'){
// rSG > index % subGridRowLength; is to prevent accidentally resorting sorted the column.
if (statusNestedArray[r0 + rSG][c0 + cSG] === steps && rSG > index % subGridRowLength) tempSubGrid.push(gridNestedArray[r0 + rSG][c0 + cSG]);
else tempSubGrid.push(undefined);
}
// if not sorted
else if (typeof statusNestedArray[index][steps] === 'undefined') {
if (cSG === 0 || typeof statusNestedArray[r0 + rSG][c0 + cSG] != 'undefined') {
tempSubGrid.push(undefined);
continue; // prevent overlapping with the next if statement.
}
tempSubGrid.push(gridNestedArray[r0 + rSG][c0 + cSG]);
}
}
}
}
return tempSubGrid;
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T08:07:01.827",
"Id": "484594",
"Score": "1",
"body": "Hi, I have removed the backtracking tag from the question. Although you mention you had implementation using backtracking, that version is not posted here and so the tag seemed inappropriate."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T10:27:40.887",
"Id": "484615",
"Score": "0",
"body": "@slepic I appreciate it. Thank you."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T22:18:54.710",
"Id": "247545",
"Score": "3",
"Tags": [
"javascript",
"recursion",
"sudoku"
],
"Title": "A valid Sudoku Generator without backtracking in JavaScript"
}
|
247545
|
<p>This set of questions are related to a project I've published for converting characters, or strings, to Hex based Unicode; eg...</p>
<pre><code>toUnicode.fromCharacter('');
//> 1f34d
toUnicode.fromString('Spam!', '0x');
//> ['0x53', '0x70', '0x61', '0x6d', '0x21']
</code></pre>
<h2>Questions</h2>
<ul>
<li><p>Are there any mistakes, such as unaccounted for edge-cases?</p>
</li>
<li><p>Have I missed any test cases?</p>
</li>
<li><p>Any suggestions on making the code more readable and/or easier to extend?</p>
</li>
<li><p>Are there any features that are wanted?</p>
</li>
</ul>
<hr />
<h2>Setup and Usage</h2>
<p>The <a href="https://github.com/javascript-utilities/to-unicode" rel="noreferrer">Source code</a> is maintained on GitHub and may be cloned via the following commands. A <a href="https://javascript-utilities.github.io/to-unicode/index.html" rel="noreferrer">Live demo</a> is hosted online, thanks to GitHub Pages.</p>
<pre class="lang-bsh prettyprint-override"><code>mkdir -vp ~/git/hub/javascript-utilities
cd ~/git/hub/javascript-utilities
git clone git@github.com:javascript-utilities/to-unicode.git
</code></pre>
<p>The build target is ECMAScript version 6, and so far both manual tests and automated JestJS tests show that the <code>toUnicode</code> methods function as intended; for both Browser and NodeJS environments.</p>
<p><strong>Example NodeJS Usage</strong></p>
<pre><code>const toUnicode = require('./to-unicode.js');
var panda_code = toUnicode.fromCharacter('');
console.log(panda_code);
//> '1f43c'
</code></pre>
<hr />
<h2>Source Code</h2>
<p>I am concerned with improving the <a href="https://github.com/javascript-utilities/to-unicode/blob/main/to-unicode.js" rel="noreferrer">JavaScript</a>, and <a href="https://github.com/javascript-utilities/to-unicode/blob/main/ts/to-unicode.ts" rel="noreferrer">TypeScript</a>; ie. HTML is intended to be simple and functional.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>'use strict';
/**
* Namespace for static methods that convert characters and strings to Unicode
*/
class toUnicode {
/**
* Converts character to Hex Unicode
* @param {string} character
* @return {string}
* @author S0AndS0
* @copyright AGPL-3.0
* @example
* toUnicode.fromCharacter('');
* //> "1f43c"
*/
static fromCharacter(character) {
return character.codePointAt(undefined).toString(16);
}
/**
* Converts string to character array of Unicode(s)
* @param {string} characters
* @return {string[]}
* @author S0AndS0
* @copyright AGPL-3.0
* @example
* toUnicode.fromString(' ');
* //> [ '1f389', '20', '1f44b' ]
*/
static fromString(characters, prefix = '') {
return [...characters].reduce((accumulator, character) => {
const unicode = toUnicode.fromCharacter(character);
accumulator.push(`${prefix}${unicode}`);
return accumulator;
}, []);
}
}
/* istanbul ignore next */
if (typeof module !== 'undefined') {
module.exports = toUnicode;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>toUnicode Usage Example</title>
<script type="text/javascript" src="assets/js/modules/to-unicode.js" differ></script>
<script type="text/javascript" differ>
const text_input__callback = (_event) => {
const client_input = document.getElementById('client__text--input').value;
const client_prefix = document.getElementById('client__text--prefix').value;
const output_element = document.getElementById('client__text--output');
const unicode_list = toUnicode.fromString(client_input, client_prefix);
console.log(unicode_list);
output_element.innerText = unicode_list.join('\n');
};
window.addEventListener('load', () => {
const client_text_input = document.getElementById('client__text--input');
const client_text_prefix = document.getElementById('client__text--prefix');
client_text_input.addEventListener('input', text_input__callback);
client_text_prefix.addEventListener('input', text_input__callback);
});
</script>
</head>
<body>
<span>Prefix: </span>
<input type="text" id="client__text--prefix" value="0x">
<br>
<span>Input: </span>
<input type="text" id="client__text--input" value="">
<pre id="client__text--output"></pre>
</body>
</html></code></pre>
</div>
</div>
</p>
<hr />
<h2>JestJS Tests</h2>
<p>For completeness here are the <a href="https://github.com/javascript-utilities/to-unicode/blob/main/__tests__/tests-to-unicode.js" rel="noreferrer">JestJS</a> tests.</p>
<pre><code>'use strict';
/**
* Tests modules within `to-unicode.js` script
* @author S0AndS0
* @copyright AGPL-3.0
*/
class toUnicode_Test {
constructor(min_code_point = 161, max_code_point = 1114111) {
this.toUnicode = require('../to-unicode.js');
this.min_code_point = min_code_point;
this.max_code_point = max_code_point;
}
randomCodePoint() {
return Math.random() * (this.max_code_point - this.min_code_point + 1) + this.min_code_point | 0;
}
runTests() {
this.testInvariance();
}
/**
* Tests if `fromCharacter()` and `fromString()` functions are reversible.
*/
testInvariance() {
const character_code_list = Array(99).fill(0).map((_) => {
return this.randomCodePoint();
});
let unicode_list = [];
let characters_string = '';
test('Is `fromCharacter()` reversible?', () => {
character_code_list.forEach((code_point) => {
const character = String.fromCodePoint(code_point);
const unicode = this.toUnicode.fromCharacter(character);
const decimal = Number(`0x${unicode}`);
expect(decimal).toEqual(code_point);
unicode_list.push(unicode);
characters_string += character;
});
});
test('Is `fromString()` reversible?', () => {
expect(this.toUnicode.fromString(characters_string)).toStrictEqual(unicode_list);
});
}
}
const test_toUnicode = new toUnicode_Test();
test_toUnicode.runTests();
</code></pre>
|
[] |
[
{
"body": "<p>This is regarding the edge-cases and test cases mentioned in the question:</p>\n<pre><code>[...characters] // or Array.from(characters)\n</code></pre>\n<p>handles splitting the characters of string to an array in most of the cases. It is better than <code>characters.split("")</code> because it handles surrogate pairs pretty well.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>console.log( \"\".length ) // 2\nconsole.log( [...\"\"] )\nconsole.log( \"\".split(\"\") )</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>What if you input something like ? You get</p>\n<pre><code>0x1f468\n0x200d\n0x1f469\n0x200d\n0x1f467\n0x200d\n0x1f466\n</code></pre>\n<p>and not a single hex as output like before. Because, there are hundreds of <em>emoji sequences</em> which are combinations of multiple emojis but display as a single emoji. They are joined with a <a href=\"https://codepoints.net/U+200d\" rel=\"nofollow noreferrer\">Zero Width Joiner (U+200D)</a> character. When you use <code>[...]</code> on them, they are split into an array of individual emojis and joiner characters.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>console.log(\"️️\".length) // 7\nconsole.log(Array.from(\"️️\"))\n\nconsole.log(\"\".length) // 11\nconsole.log(Array.from(\"\"))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Similarly, many languages create a grapheme or a symbol with <a href=\"http://en.wikipedia.org/wiki/Combining_character\" rel=\"nofollow noreferrer\">combining marks</a>. They look like distinctive units of writing, but are made up of multiple unicode points.</p>\n<p>The below strings are not the same. The first string has <code>á</code> but the second string is <code>a</code> and a combining mark <a href=\"https://codepoints.net/U+0301\" rel=\"nofollow noreferrer\">U+0301</a></p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const a = \"álgebra\",\n b = \"álgebra\"\n\nconsole.log(a === b) // false\nconsole.log(a.length, b.length)\nconsole.log([...a].join(\" , \"))\nconsole.log([...b].join(\" , \"))\n\nconsole.log([...\"हिन्दी\"].join(\" , \")) // Devanagari script</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p><a href=\"https://codepoints.net/U+093F\" rel=\"nofollow noreferrer\"><code> ि</code></a> is a vowel sound and isn't used on it's own. It needs to be combined to with a consonant like <code>ह</code>(Ha) to get <code>हि</code> (He)</p>\n<p>You can create big strings using multiple combining marks while the string looks like it has 6 distinct characters:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const a = 'Z͑ͫ̓ͪ̂ͫ̽͏̴̙̤̞͉͚̯̞̠͍A̴̵̜̰͔ͫ͗͢L̠ͨͧͩ͘G̴̻͈͍͔̹̑͗̎̅͛́Ǫ̵̹̻̝̳͂̌̌͘!͖̬̰̙̗̿̋ͥͥ̂ͣ̐́́͜͞'\n\nconsole.log(a.length) // 75\nconsole.log(Array.from(a))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>The scenarios mentioned are not issues per se. You are basically converting the string to corresponding unicode hex. But, each grapheme or a symbol doesn't necessarily correspond to a single hex in the output. You can keep these in mind or add them to your edge cases / test cases.</p>\n<p>Some further reading:</p>\n<ul>\n<li><a href=\"https://mathiasbynens.be/notes/javascript-unicode\" rel=\"nofollow noreferrer\">JavaScript has a Unicode problem</a></li>\n<li><a href=\"https://dmitripavlutin.com/what-every-javascript-developer-should-know-about-unicode/\" rel=\"nofollow noreferrer\">What every JavaScript developer should know about Unicode</a></li>\n<li><a href=\"https://unicode.org/emoji/charts/full-emoji-list.html\" rel=\"nofollow noreferrer\">Full Emoji List, v13.0</a> (You can see the Code column to know if emojis are created from multiple emojis)</li>\n<li><a href=\"https://emojipedia.org/emoji-zwj-sequence/\" rel=\"nofollow noreferrer\">Emoji Zero Width Joiner ZWJ Sequence</a></li>\n</ul>\n<hr />\n<p>Also, <code>codePointAt</code> takes a number as a parameter.</p>\n<pre><code>return character.codePointAt(undefined).toString(16)\n</code></pre>\n<p>is same as</p>\n<pre><code>return character.codePointAt().toString(16)\n</code></pre>\n<p>Both of these work because if the argument is <code>undefined</code>, it defaults to <code>0</code>. It's better to pass <code>0</code> explicitly as it is easily understandable. It wasn't clear why you were passing <code>undefined</code> initially.</p>\n<pre><code>return character.codePointAt(0).toString(16)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T00:36:06.250",
"Id": "484699",
"Score": "0",
"body": "Thanks for the detailed answer!... Passing `undefined` to `codePointAt` was done to prevent TypeScript from complaining, but I'll certainly consider switching to `0` as that seems to be less confusing for readers (myself included)... As for _`Array.from(_string_)`_ vs. _`[..._string_]`_, so far tests seem to produce equivalent output, and last I read the _spread_ syntax was the _short-hand_ way of avoiding issues with _`String.split(\"\")`_ doing unkind things to non-ASCII strings."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T05:10:35.777",
"Id": "484709",
"Score": "1",
"body": "@S0AndS0 sorry, I wan't clear in the answer. `Array.from()` and `[...]` are equivalent for a string input. They both use the [`Symbol.iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/@@iterator) property of the string to create an array."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T18:50:33.680",
"Id": "247585",
"ParentId": "247547",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T23:52:14.933",
"Id": "247547",
"Score": "7",
"Tags": [
"javascript",
"strings",
"array",
"converting",
"unicode"
],
"Title": "JavaScript string to Unicode (Hex)"
}
|
247547
|
<h1>Problem statement</h1>
<p>Ping-pong</p>
<blockquote>
<p>The ping-pong sequence counts up starting from 1 and is always either counting up or counting down. At element k, the direction switches if k is a multiple of 7 or contains the digit 7. The first 30 elements of the ping-pong sequence are listed below, with direction swaps marked using brackets at the 7th, 14th, 17th, 21st, 27th, and 28th elements:</p>
</blockquote>
<p><a href="https://i.stack.imgur.com/fei0o.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fei0o.png" alt="enter image description here" /></a></p>
<hr />
<blockquote>
<p>Implement a function pingpong that returns the nth element of the ping-pong sequence without using any assignment statements.</p>
</blockquote>
<blockquote>
<p>You may use the function num_sevens, which you defined in the previous question.</p>
</blockquote>
<blockquote>
<p>Use recursion - the tests will fail if you use any assignment statements.</p>
</blockquote>
<blockquote>
<p>Hint: If you're stuck, first try implementing pingpong using assignment statements and a while statement. Then, to convert this into a recursive solution, write a helper function that has a parameter for each variable that changes values in the body of the while loop.</p>
</blockquote>
<pre><code>def pingpong(n):
"""Return the nth element of the ping-pong sequence.
>>> pingpong(7)
7
>>> pingpong(8)
6
>>> pingpong(15)
1
>>> pingpong(21)
-1
>>> pingpong(22)
0
>>> pingpong(30)
6
>>> pingpong(68)
2
>>> pingpong(69)
1
>>> pingpong(70)
0
>>> pingpong(71)
1
>>> pingpong(72)
0
>>> pingpong(100)
2
>>> from construct_check import check
>>> # ban assignment statements
>>> check(HW_SOURCE_FILE, 'pingpong', ['Assign', 'AugAssign'])
True
"""
"*** YOUR CODE HERE ***"
</code></pre>
<hr />
<h1>Solution</h1>
<pre><code>package main
import "fmt"
func numSevens(x int) int {
if x == 0 {
return 0
}
if x%10 == 7 {
return 1 + numSevens(x/10)
} else {
return numSevens(x / 10)
}
}
func pingPong(n int) int {
var player1 func(int, int, bool) int
var player2 func(int, int, bool) int
player1 = func(currentIndex int, pingPongValue int, receiveOpponentBall bool) int {
if currentIndex == n {
return pingPongValue
}
if receiveOpponentBall {
return player1(currentIndex+1, pingPongValue+1, false)
}
if numSevens(currentIndex) > 0 || currentIndex%7 == 0 {
return player2(currentIndex, pingPongValue, true)
}
return player1(currentIndex+1, pingPongValue+1, false)
}
player2 = func(currentIndex int, pingPongValue int, receiveOpponentBall bool) int {
if currentIndex == n {
return pingPongValue
}
if receiveOpponentBall {
return player2(currentIndex+1, pingPongValue-1, false)
}
if numSevens(currentIndex) > 0 || currentIndex%7 == 0 {
return player1(currentIndex, pingPongValue, true)
}
return player2(currentIndex+1, pingPongValue-1, false)
}
return player1(1, 1, false)
}
func main() {
//fmt.Println(numSevens(12345))
fmt.Println(pingPong(29))
}
</code></pre>
<hr />
<p>Below code is written without using mutual recursion:</p>
<pre><code>func pingPongRecur(n int) int {
toggleValue := 1 ^ -1
increment := 1
var runSequence func(int, int) int
runSequence = func(currentIndex int, pingPongValue int) int {
if currentIndex == n {
return pingPongValue
}
if numSevens(currentIndex) > 0 || currentIndex%7 == 0 {
increment ^= toggleValue
}
return runSequence(currentIndex+1, pingPongValue+increment)
}
return runSequence(1, 1)
}
</code></pre>
<hr />
<ol>
<li><p>How to give better name than <code>receiveOpponentBall</code> variable? How to improve other variable naming convention? based on given problem statement.</p>
</li>
<li><p>Please add improvements in the above code from aspect of readability & good abstraction</p>
</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T09:23:41.103",
"Id": "484733",
"Score": "0",
"body": "Please stop adding tags that don't relate to the question."
}
] |
[
{
"body": "<p>From the problem statement:</p>\n<blockquote>\n<p>Implement a function pingpong that returns the nth element of the\nping-pong sequence without using any assignment statements.</p>\n<p>You may use the function num_sevens, which you defined in the previous\nquestion.</p>\n<p>Use recursion - the tests will fail if you use any assignment\nstatements.</p>\n<p>Hint: If you're stuck, first try implementing pingpong using\nassignment statements and a while statement. Then, to convert this\ninto a recursive solution, write a helper function that has a\nparameter for each variable that changes values in the body of the\nwhile loop.</p>\n</blockquote>\n<hr />\n<p>Code should be correct, maintainable, robust, reasonably efficient, and, most importantly, readable.</p>\n<hr />\n<p>Your first solution makes far too much of a simple switch in the increment value with duplicated functions differing merely in the literal integer values 1 and -1. It requires a diff comparison to find the small, obscure differences between the largely duplicate <code>player1</code> and <code>player2</code> functions. Duplication of code hurts maintainability. The solution introduces an obscure player abstraction which is not part of the problem statement. It is not readable. Also, the solution uses multiple assignment statements for the player function variables: "the tests will fail if you use any assignment statements."</p>\n<hr />\n<p>While the problem statement did say you may use <code>num_sevens</code>, this problem asks "if k contains the digit 7". To count all occurences of digit 7 when we only care about the first occurence is inefficient.</p>\n<hr />\n<p>Your second solution, "code written without using mutual recursion", which you added later, is clearly incorrect. It uses multiple assignment statements: "the tests will fail if you use any assignment statements." For no apparent reason, you use the name toogle instead of switch and you complicate things by introducing a <code>toggleValue</code> variable.</p>\n<pre><code>toggleValue := 1 ^ -1\nincrement := 1\n. . .\n increment ^= toggleValue\n</code></pre>\n<p>The <code>toggleValue</code> variable is unnecessary and the toggle algorithm is obscure. Simplicity is a virtue.</p>\n<pre><code>increment := 1\n. . .\n increment *= -1 // switch\n</code></pre>\n<hr />\n<p>The Problem Statement is an academic problem designed to discover if you have learned some fundamental programming concepts: recursion and no assignment statements. The Hint gives a detailed road-map to a solution. You did not answer the problem as stated so you get an F.</p>\n<hr />\n<p>Here is an example of the sort of solution that the problem statement likely expected:</p>\n<blockquote>\n<p>Use recursion. First try implementing pingpong using assignment\nstatements and a while statement. Then, to convert this into a\nrecursive solution, write a helper function that has a parameter for\neach variable that changes values in the body of the while loop.</p>\n</blockquote>\n<pre><code>package main\n\nimport "fmt"\n\nfunc digitSeven(x int) bool {\n if x <= 0 {\n return false\n }\n if x%10 == 7 {\n return true\n }\n return digitSeven(x / 10)\n}\n\nfunc increment(incr int, x int) int {\n if x%7 == 0 || digitSeven(x) {\n return incr * -1\n }\n return incr\n}\n\nfunc pingpong(n int, i int, v int, incr int) int {\n if i > n {\n return v\n }\n return pingpong(n, i+1, v+incr, increment(incr, i))\n}\n\nfunc PingPong(n int) int {\n return pingpong(n, 1, 0, 1)\n}\n\nfunc main() {\n for n := 1; n <= 30; n++ {\n fmt.Println(n, PingPong(n))\n }\n}\n</code></pre>\n<p>Playground: <a href=\"https://play.golang.org/p/8H6l-CpLlye\" rel=\"nofollow noreferrer\">https://play.golang.org/p/8H6l-CpLlye</a></p>\n<p>Output:</p>\n<pre><code>1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7\n8 6\n9 5\n10 4\n11 3\n12 2\n13 1\n14 0\n15 1\n16 2\n17 3\n18 2\n19 1\n20 0\n21 -1\n22 0\n23 1\n24 2\n25 3\n26 4\n27 5\n28 4\n29 5\n30 6\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T01:57:20.940",
"Id": "484702",
"Score": "0",
"body": "**1)** For your point: \"the solution uses multiple assignment statements for the player function variables\", I mean, GoLang doesn't allow me to use nested named functions with recursion. **2)** For second solution, I can avoid assignment statements, for sure by passing them as arguments, for sure......Avoiding assignment statements was never a bottleneck for me"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T01:58:54.610",
"Id": "484703",
"Score": "0",
"body": "First solution is not readable? that was surprising. I thought, i would impress you, with first solution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T02:02:11.753",
"Id": "484704",
"Score": "0",
"body": "@BurakSerdar Is first solution not readable?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T01:01:29.693",
"Id": "247594",
"ParentId": "247549",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T00:40:51.713",
"Id": "247549",
"Score": "7",
"Tags": [
"recursion",
"functional-programming",
"go"
],
"Title": "Mutual recursion - Naming the opponent serve - pingpong"
}
|
247549
|
<p>I am trying to improve upon a VBA code created through recording a macro. Can the code below be optimized (I was informed to avoid .Select as much as possible)? The code itself works fine for me though.</p>
<pre><code> Sheets("DataExport").Select
Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.ClearContents
Sheets("Analysis").Select
Range("BX1:CI4").Select
Selection.Copy
Sheets("DataExport").Select
Range("B1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
</code></pre>
|
[] |
[
{
"body": "<p>Try to avoid using <code>Select</code>. You could try the following code:</p>\n<pre class=\"lang-vb prettyprint-override\"><code> Dim ws_data As Worksheet, ws_analysis As Worksheet\n Dim lRow As Long, lCol As Long\n \n Set ws_data = ThisWorkbook.Worksheets("DataExport")\n Set ws_analysis = ThisWorkbook.Worksheets("Analysis")\n With ws_data\n lRow = .Cells(.Rows.Count, 1).End(xlUp).Row\n lCol = .Cells(1, .Columns.Count).End(xlToLeft).Column\n .Range(.Cells(1, 1), .Cells(lRow, lCol)).ClearContents\n ws_analysis.Range("BX1:CI4").Copy\n .Range("B1").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False\n End With\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T11:39:16.797",
"Id": "247551",
"ParentId": "247550",
"Score": "1"
}
},
{
"body": "<p>Let me give you the following answer/advise:</p>\n<p>As far as your first piece of code is concerned, this can be re-written as:</p>\n<pre><code>Sheets("DataExport").Range("A1").CurrentRegion.ClearContents\n</code></pre>\n<p>As far as the second piece of code is concerned (about the copying), I'd like to refer you to <a href=\"https://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba\">this very complete answer</a>. (I might give you the answer but I believe you'd better try to create it, based on this URL. If you have any issues, please edit your question, we'll have another look).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T15:27:52.280",
"Id": "484567",
"Score": "0",
"body": "Thank you very much, the link provided is indeed informative and gave me the answers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T15:55:28.567",
"Id": "484568",
"Score": "0",
"body": "@Sad22: Your welcome. In case my answer helped you find the answer, please indicate this answer as useful."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T11:49:16.453",
"Id": "247552",
"ParentId": "247550",
"Score": "3"
}
},
{
"body": "<p>Second part:</p>\n<pre class=\"lang-vb prettyprint-override\"><code>With Sheets("Analysis").Range("BX1:CI4")\n Sheets("DataExport").Range("B1").Resize(.Rows.count, .Columns.count).Value = .Value\nEnd With\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-08T00:26:25.487",
"Id": "247639",
"ParentId": "247550",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "247551",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T11:30:31.310",
"Id": "247550",
"Score": "2",
"Tags": [
"excel",
"vba"
],
"Title": "Better way to code this code snippet (copy paste)"
}
|
247550
|
<p>I'm working on a program that uses the RIOT API <em>League of Legends</em> for collecting player data and calculate how skilled a player is by using a grading system (as of right now it just the average of the last ten games for each skills). Realize I used a lot of class, what is a better way to do it?</p>
<pre><code>import requests
#ASKING USER FOR SUMMONER NAME
sumName = input('Enter summoner name:')
#COLLECTING DATA TO BE INSERTING FOR MATCHLIST DATABASE
url=('https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/'+(sumName)+'?api_key='+(key))
response=requests.get(url)
accId=(response.json()['accountId'])
#COLLECTING DATA FOR THE NEXT DATABASE API
url2=('https://na1.api.riotgames.com/lol/match/v4/matchlists/by-account/'+(accId)+'?queue=420&endIndex=20&api_key='+(key))
response2=requests.get(url2)
i=0
GAMEID = []
Idgame=20
#COLLECTS GAME ID'S FOR NEXT DATABASE FOR 20 GAMES
while Idgame>0:
GAMEID.append(response2.json()['matches'][i]['gameId'])
i=i+1
Idgame=Idgame-1
#COLLECTING DATA FROM GAME 1
class GAME1():
url3=('https://na1.api.riotgames.com/lol/match/v4/matches/'+str(GAMEID[0])+'?api_key='+(key))
response3=requests.get(url3)
Loop=0
index=0
#THIS COLLECT THE ID NUMBER OF THE PLAYER NAME THAT WAS INSERTED
while Loop<=10:
if response3.json()['participantIdentities'][index]['player']['summonerName']!=sumName:
Loop= Loop+1
index=index+1
elif response3.json()['participantIdentities'][index]['player']['summonerName']==sumName:
break
kills=response3.json()['participants'][index]['stats']['kills']
deaths=response3.json()['participants'][index]['stats']['deaths']
timer=response3.json()['gameDuration']
assists=response3.json()['participants'][index]['stats']['assists']
visions=response3.json()['participants'][index]['stats']['visionScore']
csTotal=response3.json()['participants'][index]['stats']['totalMinionsKilled']
#COLLECTING DATA FROM GAME 2
class GAME2():
url3=('https://na1.api.riotgames.com/lol/match/v4/matches/'+str(GAMEID[1])+'?api_key='+(key))
response3=requests.get(url3)
Loop=0
index=0
while Loop<=10:
if response3.json()['participantIdentities'][index]['player']['summonerName']!=sumName:
Loop= Loop+1
index=index+1
elif response3.json()['participantIdentities'][index]['player']['summonerName']==sumName:
break
kills=response3.json()['participants'][index]['stats']['kills']
deaths=response3.json()['participants'][index]['stats']['deaths']
timer=response3.json()['gameDuration']
assists=response3.json()['participants'][index]['stats']['assists']
visions=response3.json()['participants'][index]['stats']['visionScore']
csTotal=response3.json()['participants'][index]['stats']['totalMinionsKilled']
#COLLECTING DATA FROM GAME 3
class GAME3():
url3=('https://na1.api.riotgames.com/lol/match/v4/matches/'+str(GAMEID[2])+'?api_key='+(key))
response3=requests.get(url3)
Loop=0
index=0
while Loop<=10:
if response3.json()['participantIdentities'][index]['player']['summonerName']!=sumName:
Loop= Loop+1
index=index+1
elif response3.json()['participantIdentities'][index]['player']['summonerName']==sumName:
break
kills=response3.json()['participants'][index]['stats']['kills']
deaths=response3.json()['participants'][index]['stats']['deaths']
timer=response3.json()['gameDuration']
assists=response3.json()['participants'][index]['stats']['assists']
visions=response3.json()['participants'][index]['stats']['visionScore']
csTotal=response3.json()['participants'][index]['stats']['totalMinionsKilled']
#COLLECTING DATA FROM GAME 4
class GAME4():
url3=('https://na1.api.riotgames.com/lol/match/v4/matches/'+str(GAMEID[3])+'?api_key='+(key))
response3=requests.get(url3)
Loop=0
index=0
while Loop<=10:
if response3.json()['participantIdentities'][index]['player']['summonerName']!=sumName:
Loop= Loop+1
index=index+1
elif response3.json()['participantIdentities'][index]['player']['summonerName']==sumName:
break
kills=response3.json()['participants'][index]['stats']['kills']
deaths=response3.json()['participants'][index]['stats']['deaths']
timer=response3.json()['gameDuration']
assists=response3.json()['participants'][index]['stats']['assists']
visions=response3.json()['participants'][index]['stats']['visionScore']
csTotal=response3.json()['participants'][index]['stats']['totalMinionsKilled']
#COLLECTING DATA FROM GAME 5
class GAME5():
url3=('https://na1.api.riotgames.com/lol/match/v4/matches/'+str(GAMEID[4])+'?api_key='+(key))
response3=requests.get(url3)
Loop=0
index=0
while Loop<=10:
if response3.json()['participantIdentities'][index]['player']['summonerName']!=sumName:
Loop= Loop+1
index=index+1
elif response3.json()['participantIdentities'][index]['player']['summonerName']==sumName:
break
kills=response3.json()['participants'][index]['stats']['kills']
deaths=response3.json()['participants'][index]['stats']['deaths']
timer=response3.json()['gameDuration']
assists=response3.json()['participants'][index]['stats']['assists']
visions=response3.json()['participants'][index]['stats']['visionScore']
csTotal=response3.json()['participants'][index]['stats']['totalMinionsKilled']
#COLLECTING DATA FROM GAME 6
class GAME6():
url3=('https://na1.api.riotgames.com/lol/match/v4/matches/'+str(GAMEID[5])+'?api_key='+(key))
response3=requests.get(url3)
Loop=0
index=0
while Loop<=10:
if response3.json()['participantIdentities'][index]['player']['summonerName']!=sumName:
Loop= Loop+1
index=index+1
elif response3.json()['participantIdentities'][index]['player']['summonerName']==sumName:
break
kills=response3.json()['participants'][index]['stats']['kills']
deaths=response3.json()['participants'][index]['stats']['deaths']
timer=response3.json()['gameDuration']
assists=response3.json()['participants'][index]['stats']['assists']
visions=response3.json()['participants'][index]['stats']['visionScore']
csTotal=response3.json()['participants'][index]['stats']['totalMinionsKilled']
#COLLECTING DATA FROM GAME 7
class GAME7():
url3=('https://na1.api.riotgames.com/lol/match/v4/matches/'+str(GAMEID[6])+'?api_key='+(key))
response3=requests.get(url3)
Loop=0
index=0
while Loop<=10:
if response3.json()['participantIdentities'][index]['player']['summonerName']!=sumName:
Loop= Loop+1
index=index+1
elif response3.json()['participantIdentities'][index]['player']['summonerName']==sumName:
break
kills=response3.json()['participants'][index]['stats']['kills']
deaths=response3.json()['participants'][index]['stats']['deaths']
timer=response3.json()['gameDuration']
assists=response3.json()['participants'][index]['stats']['assists']
visions=response3.json()['participants'][index]['stats']['visionScore']
csTotal=response3.json()['participants'][index]['stats']['totalMinionsKilled']
#COLLECTING DATA FROM GAME 8
class GAME8():
url3=('https://na1.api.riotgames.com/lol/match/v4/matches/'+str(GAMEID[7])+'?api_key='+(key))
response3=requests.get(url3)
Loop=0
index=0
while Loop<=10:
if response3.json()['participantIdentities'][index]['player']['summonerName']!=sumName:
Loop= Loop+1
index=index+1
elif response3.json()['participantIdentities'][index]['player']['summonerName']==sumName:
break
kills=response3.json()['participants'][index]['stats']['kills']
deaths=response3.json()['participants'][index]['stats']['deaths']
timer=response3.json()['gameDuration']
assists=response3.json()['participants'][index]['stats']['assists']
visions=response3.json()['participants'][index]['stats']['visionScore']
csTotal=response3.json()['participants'][index]['stats']['totalMinionsKilled']
#COLLECTING DATA FROM GAME 9
class GAME9():
url3=('https://na1.api.riotgames.com/lol/match/v4/matches/'+str(GAMEID[8])+'?api_key='+(key))
response3=requests.get(url3)
Loop=0
index=0
while Loop<=10:
if response3.json()['participantIdentities'][index]['player']['summonerName']!=sumName:
Loop= Loop+1
index=index+1
elif response3.json()['participantIdentities'][index]['player']['summonerName']==sumName:
break
kills=response3.json()['participants'][index]['stats']['kills']
deaths=response3.json()['participants'][index]['stats']['deaths']
timer=response3.json()['gameDuration']
assists=response3.json()['participants'][index]['stats']['assists']
visions=response3.json()['participants'][index]['stats']['visionScore']
csTotal=response3.json()['participants'][index]['stats']['totalMinionsKilled']
#COLLECTING DATA FROM GAME 10
class GAME10():
url3=('https://na1.api.riotgames.com/lol/match/v4/matches/'+str(GAMEID[9])+'?api_key='+(key))
response3=requests.get(url3)
Loop=0
index=0
while Loop<=10:
if response3.json()['participantIdentities'][index]['player']['summonerName']!=sumName:
Loop= Loop+1
index=index+1
elif response3.json()['participantIdentities'][index]['player']['summonerName']==sumName:
break
kills=response3.json()['participants'][index]['stats']['kills']
deaths=response3.json()['participants'][index]['stats']['deaths']
timer=response3.json()['gameDuration']
assists=response3.json()['participants'][index]['stats']['assists']
visions=response3.json()['participants'][index]['stats']['visionScore']
csTotal=response3.json()['participants'][index]['stats']['totalMinionsKilled']
#COLLECTING DATA FROM GAME 11
class GAME11():
url3=('https://na1.api.riotgames.com/lol/match/v4/matches/'+str(GAMEID[10])+'?api_key='+(key))
response3=requests.get(url3)
Loop=0
index=0
while Loop<=10:
if response3.json()['participantIdentities'][index]['player']['summonerName']!=sumName:
Loop= Loop+1
index=index+1
elif response3.json()['participantIdentities'][index]['player']['summonerName']==sumName:
break
kills=response3.json()['participants'][index]['stats']['kills']
deaths=response3.json()['participants'][index]['stats']['deaths']
timer=response3.json()['gameDuration']
assists=response3.json()['participants'][index]['stats']['assists']
visions=response3.json()['participants'][index]['stats']['visionScore']
csTotal=response3.json()['participants'][index]['stats']['totalMinionsKilled']
#COLLECTING DATA FROM GAME 12
class GAME12():
url3=('https://na1.api.riotgames.com/lol/match/v4/matches/'+str(GAMEID[11])+'?api_key='+(key))
response3=requests.get(url3)
Loop=0
index=0
while Loop<=10:
if response3.json()['participantIdentities'][index]['player']['summonerName']!=sumName:
Loop= Loop+1
index=index+1
elif response3.json()['participantIdentities'][index]['player']['summonerName']==sumName:
break
kills=response3.json()['participants'][index]['stats']['kills']
deaths=response3.json()['participants'][index]['stats']['deaths']
timer=response3.json()['gameDuration']
assists=response3.json()['participants'][index]['stats']['assists']
visions=response3.json()['participants'][index]['stats']['visionScore']
csTotal=response3.json()['participants'][index]['stats']['totalMinionsKilled']
#COLLECTING DATA FROM GAME 13
class GAME13():
url3=('https://na1.api.riotgames.com/lol/match/v4/matches/'+str(GAMEID[12])+'?api_key='+(key))
response3=requests.get(url3)
Loop=0
index=0
while Loop<=10:
if response3.json()['participantIdentities'][index]['player']['summonerName']!=sumName:
Loop= Loop+1
index=index+1
elif response3.json()['participantIdentities'][index]['player']['summonerName']==sumName:
break
kills=response3.json()['participants'][index]['stats']['kills']
deaths=response3.json()['participants'][index]['stats']['deaths']
timer=response3.json()['gameDuration']
assists=response3.json()['participants'][index]['stats']['assists']
visions=response3.json()['participants'][index]['stats']['visionScore']
csTotal=response3.json()['participants'][index]['stats']['totalMinionsKilled']
#COLLECTING DATA FROM GAME 14
class GAME14():
url3=('https://na1.api.riotgames.com/lol/match/v4/matches/'+str(GAMEID[13])+'?api_key='+(key))
response3=requests.get(url3)
Loop=0
index=0
while Loop<=10:
if response3.json()['participantIdentities'][index]['player']['summonerName']!=sumName:
Loop= Loop+1
index=index+1
elif response3.json()['participantIdentities'][index]['player']['summonerName']==sumName:
break
kills=response3.json()['participants'][index]['stats']['kills']
deaths=response3.json()['participants'][index]['stats']['deaths']
timer=response3.json()['gameDuration']
assists=response3.json()['participants'][index]['stats']['assists']
visions=response3.json()['participants'][index]['stats']['visionScore']
csTotal=response3.json()['participants'][index]['stats']['totalMinionsKilled']
#COLLECTING DATA FROM GAME 15
class GAME15():
url3=('https://na1.api.riotgames.com/lol/match/v4/matches/'+str(GAMEID[14])+'?api_key='+(key))
response3=requests.get(url3)
Loop=0
index=0
while Loop<=10:
if response3.json()['participantIdentities'][index]['player']['summonerName']!=sumName:
Loop= Loop+1
index=index+1
elif response3.json()['participantIdentities'][index]['player']['summonerName']==sumName:
break
kills=response3.json()['participants'][index]['stats']['kills']
deaths=response3.json()['participants'][index]['stats']['deaths']
timer=response3.json()['gameDuration']
assists=response3.json()['participants'][index]['stats']['assists']
visions=response3.json()['participants'][index]['stats']['visionScore']
csTotal=response3.json()['participants'][index]['stats']['totalMinionsKilled']
#COLLECTING DATA FROM GAME 16
class GAME16():
url3=('https://na1.api.riotgames.com/lol/match/v4/matches/'+str(GAMEID[15])+'?api_key='+(key))
response3=requests.get(url3)
Loop=0
index=0
while Loop<=10:
if response3.json()['participantIdentities'][index]['player']['summonerName']!=sumName:
Loop= Loop+1
index=index+1
elif response3.json()['participantIdentities'][index]['player']['summonerName']==sumName:
break
kills=response3.json()['participants'][index]['stats']['kills']
deaths=response3.json()['participants'][index]['stats']['deaths']
timer=response3.json()['gameDuration']
assists=response3.json()['participants'][index]['stats']['assists']
visions=response3.json()['participants'][index]['stats']['visionScore']
csTotal=response3.json()['participants'][index]['stats']['totalMinionsKilled']
#COLLECTING DATA FROM GAME 17
class GAME17():
url3=('https://na1.api.riotgames.com/lol/match/v4/matches/'+str(GAMEID[16])+'?api_key='+(key))
response3=requests.get(url3)
Loop=0
index=0
while Loop<=10:
if response3.json()['participantIdentities'][index]['player']['summonerName']!=sumName:
Loop= Loop+1
index=index+1
elif response3.json()['participantIdentities'][index]['player']['summonerName']==sumName:
break
kills=response3.json()['participants'][index]['stats']['kills']
deaths=response3.json()['participants'][index]['stats']['deaths']
timer=response3.json()['gameDuration']
assists=response3.json()['participants'][index]['stats']['assists']
visions=response3.json()['participants'][index]['stats']['visionScore']
csTotal=response3.json()['participants'][index]['stats']['totalMinionsKilled']
#COLLECTING DATA FROM GAME 18
class GAME18():
url3=('https://na1.api.riotgames.com/lol/match/v4/matches/'+str(GAMEID[17])+'?api_key='+(key))
response3=requests.get(url3)
Loop=0
index=0
while Loop<=10:
if response3.json()['participantIdentities'][index]['player']['summonerName']!=sumName:
Loop= Loop+1
index=index+1
elif response3.json()['participantIdentities'][index]['player']['summonerName']==sumName:
break
kills=response3.json()['participants'][index]['stats']['kills']
deaths=response3.json()['participants'][index]['stats']['deaths']
timer=response3.json()['gameDuration']
assists=response3.json()['participants'][index]['stats']['assists']
visions=response3.json()['participants'][index]['stats']['visionScore']
csTotal=response3.json()['participants'][index]['stats']['totalMinionsKilled']
#COLLECTING DATA FROM GAME 19
class GAME19():
url3=('https://na1.api.riotgames.com/lol/match/v4/matches/'+str(GAMEID[18])+'?api_key='+(key))
response3=requests.get(url3)
Loop=0
index=0
while Loop<=10:
if response3.json()['participantIdentities'][index]['player']['summonerName']!=sumName:
Loop= Loop+1
index=index+1
elif response3.json()['participantIdentities'][index]['player']['summonerName']==sumName:
break
kills=response3.json()['participants'][index]['stats']['kills']
deaths=response3.json()['participants'][index]['stats']['deaths']
timer=response3.json()['gameDuration']
assists=response3.json()['participants'][index]['stats']['assists']
visions=response3.json()['participants'][index]['stats']['visionScore']
csTotal=response3.json()['participants'][index]['stats']['totalMinionsKilled']
#COLLECTING DATA FROM GAME 20
class GAME20():
url3=('https://na1.api.riotgames.com/lol/match/v4/matches/'+str(GAMEID[19])+'?api_key='+(key))
response3=requests.get(url3)
Loop=0
index=0
while Loop<=10:
if response3.json()['participantIdentities'][index]['player']['summonerName']!=sumName:
Loop= Loop+1
index=index+1
elif response3.json()['participantIdentities'][index]['player']['summonerName']==sumName:
break
kills=response3.json()['participants'][index]['stats']['kills']
deaths=response3.json()['participants'][index]['stats']['deaths']
timer=response3.json()['gameDuration']
assists=response3.json()['participants'][index]['stats']['assists']
visions=response3.json()['participants'][index]['stats']['visionScore']
csTotal=response3.json()['participants'][index]['stats']['totalMinionsKilled']
#Object from each game class
game1= GAME1()
game2= GAME2()
game3= GAME3()
game4= GAME4()
game5= GAME5()
game6= GAME6()
game7= GAME7()
game8= GAME8()
game9= GAME9()
game10= GAME10()
#Calcuating the average of 10 games for each stat
killsAvg= (game1.kills+game2.kills+game3.kills+game4.kills+game5.kills+game6.kills+game7.kills+game8.kills+game9.kills+game10.kills)/10
assistsAvg=(game1.assists+game2.assists+game3.assists+game4.assists+game5.assists+game6.assists+game7.assists+game8.assists+game9.assists+game10.assists)/10
deathsAvg=(game1.deaths+game2.deaths+game3.deaths+game4.deaths+game5.deaths+game6.deaths+game7.deaths+game8.deaths+game9.deaths+game10.deaths)/10
visionsAvg=(game1.visions+game2.visions+game3.visions+game4.visions+game5.visions+game6.visions+game7.visions+game8.visions+game9.visions+game10.visions)/10
csAvg=(game1.csTotal+game2.csTotal+game3.csTotal+game4.csTotal+game5.csTotal+game6.csTotal+game7.csTotal+game8.csTotal+game9.csTotal+game10.csTotal)/10
print('His average kills is '+str(killsAvg)+' in the last 10 games')
print('His average assists is '+str(assistsAvg)+' in the last 10 games')
print('His average deaths is '+str(deathsAvg)+' in the last 10 games')
print('His average visions is '+str(visionsAvg)+' in the last 10 games')
print('His average csing is '+str(csAvg)+' in the last 10 games')
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T15:20:29.653",
"Id": "484630",
"Score": "0",
"body": "I don't see the variable `key` defined anywhere?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T18:42:15.960",
"Id": "484668",
"Score": "1",
"body": "Please apply the black code formatter: https://github.com/psf/black"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T05:51:09.910",
"Id": "484712",
"Score": "1",
"body": "@MartinThoma Perhaps next time, not now answers have arrived."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T07:06:23.650",
"Id": "484723",
"Score": "3",
"body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-08T06:11:08.657",
"Id": "484841",
"Score": "1",
"body": "The question is not about the formatting and the answers I have seen don't focus on that part. You just make it harder for people to understand your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-08T22:31:09.533",
"Id": "484878",
"Score": "0",
"body": "Have you tried writing this code without classes?"
}
] |
[
{
"body": "<h2>Classes</h2>\n<p>Why do you need a separate class for each game whose data you request? This is very inflexible, should you need to request the data for more or fewer games. Just use one class to represent a game. It looks like all the attributes in your game classes are identical except for the key or index used to access GAMEID. Therefore, just use a range based loop to get as many instances of the same class as you need, storing the instances in a data structure such as a list. This is exactly the motivation for having a class in the first place; you bundle data and functionality together so you can reuse it.</p>\n<pre><code>game1= GAME1()\ngame2= GAME2()\ngame3= GAME3()\ngame4= GAME4()\ngame5= GAME5()\ngame6= GAME6()\ngame7= GAME7()\ngame8= GAME8()\ngame9= GAME9()\ngame10= GAME10()\n</code></pre>\n<p>This whole thing should really be a loop.</p>\n<h2>Names</h2>\n<p>Also, naming. names like url2 are not very descriptive. What exactly is the url? The names should be clear and unambiguous. In this case it's not that big of a deal since you're only using them once or twice.</p>\n<h2>Functions/Methods</h2>\n<p>Your code doesn't have a single function in it. This is not good. Just look at that block of code that you copy-pasted for all 20 of your classes. If you had defined it as a function once you could just call that function 20 times. By using a loop that function would have to appear in code just one time.</p>\n<p>That whole block at the bottom should be in a function too.</p>\n<p>Ideally the only top level execution in your program should be this:</p>\n<pre><code>if __name__ == '__main__':\n main()\n</code></pre>\n<p>or</p>\n<pre><code>if __name__ == '__main__':\n # body of what would have been main()\n</code></pre>\n<p>to encapsulate all functionality in one place, after all the definitions, and to make sure that if the module is imported (namespace isn't __main__), it won't be executed.</p>\n<h2>Requests</h2>\n<p>after a statement like r = requests.get(), call r.raise_for_status() since it will notify you if the request fails.\nalso, instead of concatenating arguments into the url string, call get() with two parameters. One being the API URL without your specific queries, and the other being a dictionary mapping keywords to your queries.</p>\n<pre><code>r = requests.get('https://...', {'keyword' : query})\nr.raise_for_status()\n</code></pre>\n<h2>Style</h2>\n<p>Too much white space. Refer to the Python style guide.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T05:41:44.950",
"Id": "247556",
"ParentId": "247554",
"Score": "22"
}
},
{
"body": "<p><strong>Abstracting classes</strong></p>\n<p>In your question you asked how to abstract classes so I thought I would show a concrete example of how this is done. Here is a minimal example of how you could abstract your game function.</p>\n<pre><code>class GAME():\n def __init__(self, ID):\n url = ('https://na1.api.riotgames.com/lol/match/v4/matches/'+str(ID)+'?api_key='+(key))\n response = requests.get(url)\n Loop = 0\n index = 0\n\n # THIS COLLECT THE ID NUMBER OF THE PLAYER NAME THAT WAS INSERTED\n\n while Loop <= 10:\n\n if response.json()['participantIdentities'][index]['player']['summonerName'] != sumName:\n Loop = Loop+1\n index = index+1\n elif response.json()['participantIdentities'][index]['player']['summonerName'] == sumName:\n break\n \n self.kills = response.json()['participants'][index]['stats']['kills']\n self.deaths = response.json()['participants'][index]['stats']['deaths']\n self.timer = response.json()['gameDuration']\n self.assists = response.json()['participants'][index]['stats']['assists']\n self.visions = response.json()['participants'][index]['stats']['visionScore']\n self.csTotal = response.json()['participants'][index]['stats']['totalMinionsKilled']\n\n# Object from each game class\n\n\ngame1 = GAME(GAMEID[0])\ngame2 = GAME(GAMEID[1])\ngame3 = GAME(GAMEID[2])\ngame4 = GAME(GAMEID[3])\ngame5 = GAME(GAMEID[4])\ngame6 = GAME(GAMEID[5])\ngame7 = GAME(GAMEID[6])\ngame8 = GAME(GAMEID[7])\ngame9 = GAME(GAMEID[8])\ngame10 = GAME(GAMEID[9])\n</code></pre>\n<p>The <code>__init__</code> function is ran on the creation of the class instance, you can see that it requires an <code>ID</code> to be handed when it is ran. You seem unfamiliar with some of pythons class syntax so to explain the self.var notation, just know that if a variable has self before it, then that variable will be accessible outside of the class. Whereas the variables like <code>Loop</code>, <code>index</code>, and <code>response</code> are not.</p>\n<p>I still think it would be useful to read through some examples of how classes can be implemented but hopefully, this example shows how their purpose can be useful.</p>\n<p><a href=\"https://www.w3schools.com/python/python_classes.asp\" rel=\"nofollow noreferrer\">https://www.w3schools.com/python/python_classes.asp</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T15:12:28.323",
"Id": "484756",
"Score": "0",
"body": "Wouldn't it be better to make a list with the games, instead of having 10 lines? Also, according to http://pep8online.com/, the code has several PEP8 issues."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T22:22:40.023",
"Id": "484822",
"Score": "1",
"body": "Definitely, in this case i was trying to take a direct example with as few changes as possible to demonstrate the point. I was planning to later come up with an example of some other recommendations or see if someone else responded in the downtime, which it seems @ivo did very well :-)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T15:32:59.513",
"Id": "247570",
"ParentId": "247554",
"Score": "12"
}
},
{
"body": "<p>The other reviewers have already explained how you should re-organize your classes, but I want to expand a bit on how you create them and how it can save you a lot of typing.</p>\n<p>So we assume that you use the classes created by akozi.\nThen we can put the creation of these classes inside a <a href=\"https://www.pythonforbeginners.com/basics/list-comprehensions-in-python\" rel=\"noreferrer\">list comprehension</a>.</p>\n<pre><code>nr_games=10\ngames=[GAME(GAMEID[i]) for i in range(nr_games)]\n</code></pre>\n<p>The notation might be new, but the result is just that you have a list containing your 10 games. If you don't like list comprehensions, then you can always replace them with for loops.</p>\n<p>This is much easier to manage and manipulate. As a result your following steps become much easier as well.</p>\n<pre><code>killsAvg= sum( game.kills for game in games ) / nr_games\nassistsAvg= sum( game.assists for game in games ) / nr_games\n...\n</code></pre>\n<p>It might seem like this mainly saves you a lot of typing, but it has some other advantages. It is for example a lot easier to adjust and maintain, for example when changing the nr_games or when adding a new score type.\nAdditionally, imagine that there is a typo somewhere in the code, then which version would you prefer to check?</p>\n<hr />\n<p>Generally speaking, whenever you find that you have to do a lot of repeated typing/copy-pasting, stop for a moment and think whether there is a cleaner way to do things.\nOften times a lot of the typing can be solved by using data structures such as lists and dictionaries.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T15:07:41.593",
"Id": "484755",
"Score": "0",
"body": "instead of `nr_games=10`, why not `nr_games = count(GAMEID)`? Also, wouldn't `no_games` be prefered, as \"no.\" is the abbreviation of \"number\"?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-10T07:14:30.993",
"Id": "485001",
"Score": "0",
"body": "You probably mean `nr_games = len(GAMEID)`? But yeah, that's definitely be an option. I didn't do it here because the original code has `len(GAMEID)` as 20 but only takes the average of the 10 first games.\nPersonally I read no_... as 'not/no' instead of 'number'. So I would find it a bit confusing even though it might be more correct."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-10T08:44:17.353",
"Id": "485011",
"Score": "1",
"body": "That's a good point, about `no_games`, didn't think about that. Regarding the other point, you're right, it does point to 20 games. However, in the code, you will notice that only `GAME1()` to `GAME10()` were used. All the calculations use 10 games, and average of those 10 only. However, 20 game ids are fetched anyway. Maybe it's intended to have more games later? Maybe O.P. got tired of writting everything for the average and decided to ask if there was a better solution?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T06:49:00.180",
"Id": "247598",
"ParentId": "247554",
"Score": "8"
}
},
{
"body": "<p>One of the more costly bits nobody has mentioned:</p>\n<p>Cache the result of <code>response.json()</code>. Cache other frequently used things.</p>\n<p>I.e. write:</p>\n<pre><code> decoded = response.json()\n while Loop<=10:\n if decoded['participantIdentities'][index]['player']['summonerName']!=sumName:\n Loop = Loop+1\n index = index+1\n elif decoded['participantIdentities'][index]['player']['summonerName']==sumName:\n break\n \n stats = decoded['participants'][index]['stats']\n self.kills=stats['kills']\n self.deaths=stats['deaths']\n self.timer=decoded['gameDuration']\n self.assists=stats['assists']\n self.visions=stats['visionScore']\n self.csTotal=stats['totalMinionsKilled']\n</code></pre>\n<p>That while loop should also be revised. Don't have two index variables. Don't limit yourself to 10 participants. If possible, use an appropriate python construct to find the index. Perhaps something like:</p>\n<pre><code> index = [ a['player']['summonerName'] for a in decoded['participantIdentities'] ].index(sumName)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-08T18:35:15.970",
"Id": "247657",
"ParentId": "247554",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T03:19:29.783",
"Id": "247554",
"Score": "9",
"Tags": [
"python",
"api"
],
"Title": "Player data collection program"
}
|
247554
|
<p><strong>Context</strong></p>
<p>I would like to receive feedback on my code for the question which can be seen <a href="https://codereview.stackexchange.com/questions/247526/building-a-string-with-only-two-repeating-characters">here</a>.</p>
<p><strong>Problem</strong></p>
<p>This is another C# implementation for the a function for given parameters <code>int a</code>, <code>int b</code> - both represent characters 'A' and 'B' respectively, where the function should return a string containing both characters 'A' and 'B' occurring a times and b times respectively but neither 'A' nor 'B' repeating consecutively for more than 2 times. Both values for a and b are given in a way that a string can be build using those numbers - so eg: <code>Foo(0,3)</code> or <code>Foo(1,7)</code> shall not be invoked.</p>
<p>eg:</p>
<p><code>Foo(3,3)</code> returns <code>"BBAABA"</code> or <code>"AABBAB"</code></p>
<p><code>Foo(4,1)</code> returns <code>"AABAA"</code></p>
<p><code>Foo(3,5)</code> returns <code>"BAABBABB"</code> or <code>"BBAABBAB"</code></p>
<p><strong>Code</strong></p>
<pre><code>static string GenerateString (int a, int b)
{
int remainingTwiceChar = a;
int remainingOnceChar = b;
string twiceChar = "A";
string onceChar = "B";
if(b>a)
{
twiceChar = "B";
onceChar = "A";
remainingTwiceChar = b;
remainingOnceChar = a;
}
int mod = (a + b) % 3;
int div = (a + b) / 3;
StringBuilder sb = new StringBuilder(a + b);
for(int x = 0; x < div ; x++)
{
if (remainingTwiceChar >= 2 && remainingOnceChar >= 1)
{
sb.Append(twiceChar);
sb.Append(twiceChar);
sb.Append(onceChar);
remainingTwiceChar -= 2;
remainingOnceChar--;
}
else
{
sb.Append(twiceChar);
sb.Append(onceChar);
sb.Append(onceChar);
}
}
for (int x = 0; x < mod; x++)
{
if (remainingOnceChar > 0)
{
sb.Append(onceChar);
remainingOnceChar--;
}
if (remainingTwiceChar > 0)
{
sb.Append(twiceChar);
remainingTwiceChar--;
}
}
return sb.ToString();
}
</code></pre>
<p>Even though the implementation in the original question has a bug, my code does not have it. I attended this question a code testing platform. I guess, the code works (even it does not have the flaw that the code in the question has), however the testing platform gave only 33.33% marks to my question. Can anybody suggest me what I am doing wrong.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T07:58:51.810",
"Id": "484593",
"Score": "3",
"body": "Please include your test cases. Maybe there is some edge case that you missed? Did you try some larger numbers? Is a percentage all the feedback you got from the platform?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T03:38:36.747",
"Id": "247555",
"Score": "2",
"Tags": [
"c#"
],
"Title": "Building a string with only two repeating characters (different code)"
}
|
247555
|
<p>If you look at <code>ImportAndPreload</code> method, it looks bad because:</p>
<p><em>MovingAverageConvergenceDivergence</em>, <em>StochasticRSI</em>, <em>RelativeStrengthIndex</em> and <em>ExponentialMovingAverage</em>. They are all indicators, they all inherit from <code>IndicatorBase</code>. What would happen if I wanted to pass a few more indicators? There would be 10 indicators passed by arguments, which is annoying and it's against S.O.L.I.D. Is there a way to make that method like a variadic function in C++ and pass infinite amount of indicators. By the way, as you can see below, IndicatorBase is generic, which prevents <code>params IndicatorBase<???>[] args</code>.</p>
<p>For example: <code>ImportAndPreload(symbol, interval, macd, stoch, rsi, ema, ...)</code></p>
<p>I'm also open for other ideas.</p>
<pre><code>MovingAverageConvergenceDivergence macd = new MovingAverageConvergenceDivergence(12, 26, 100);
StochasticRSI stoch = new StochasticRSI(14, 9, 3, 3);
RelativeStrengthIndex rsi = new RelativeStrengthIndex(20);
ExponentialMovingAverage ema = new ExponentialMovingAverage(20);
ImportAndPreload(symbol, interval, macd, stoch, rsi, ema);
// Abstract base class for all indicators:
public abstract class IndicatorBase<TInput, TOutput>
where TInput: struct
where TOutput : struct
{
public abstract TOutput ComputeNextValue(TInput input);
public abstract void Reset();
}
private void ImportAndPreload(string symbol, KlineInterval interval, MovingAverageConvergenceDivergence macd, StochasticRSI stoch, RelativeStrengthIndex rsi, ExponentialMovingAverage ema)
{
// Import candles
List<BinanceKline> candles = Client.GetKlines(symbol, interval, limit: 1000).Data.SkipLast(1).ToList();
for (int i = 0; i < 3; i++)
{
List<BinanceKline> moreCandles2 = Client.GetKlines(symbol, interval, startTime: null, endTime: candles.First().OpenTime, limit: 1000).Data.SkipLast(1).ToList();
candles.InsertRange(0, moreCandles2);
}
// Workaround in case it gets more bigger time to import candles
List<BinanceKline> moreCandles = Client.GetKlines(symbol, interval, limit: 2).Data.SkipLast(1).ToList();
candles.AddRange(moreCandles.ExceptUsingJsonCompare(candles));
// Preload indicators
for (int i = 0; i < candles.Count; i++)
{
macd.ComputeNextValue(candles[i].Close);
stoch.ComputeNextValue(candles[i].Close);
rsi.ComputeNextValue(candles[i].Close);
ema.ComputeNextValue(candles[i].Close);
}
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>The simplest solution would be using <code>params</code>.</p>\n<pre><code>private void ImportAndPreload<TInput, TOutput>(params IndicatorBase<TInput, TOutput>[] foos) { ... }\n</code></pre>\n<p>if you want something more managed, you can use <code>IEnumerable<IndicatorBase<TInput, TOutput>></code> which would makes uses any type of collections. I would prefer using <code>IEnumereble</code> over <code>params</code> in this case, because you would store all indicators into a collection, which would be easier to handle, move (if needed) or even modify.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T17:09:29.357",
"Id": "484649",
"Score": "0",
"body": "Isn't that only if you have same `TInput` and `TOutput` for all indicators you will pass to params? For example: `public class MovingAverageConvergenceDivergence : IndicatorBase<decimal, (decimal Signal, decimal MACD, decimal Histogram)>` `public class ExponentialMovingAverage : IndicatorBase<decimal, decimal>`. They have different TInput/TOutput."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T17:43:28.180",
"Id": "484655",
"Score": "1",
"body": "@nop since its `TInput` and `TOutput` are different, then it won't be possible to use this approach. Use Jeff 's method in this case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T19:16:45.087",
"Id": "484676",
"Score": "0",
"body": "yup, thanks for your answer too!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T16:31:31.130",
"Id": "247578",
"ParentId": "247563",
"Score": "4"
}
},
{
"body": "<p>This will depend on whether or not all of the indicators you're interested in passing have the same generic type arguments. If they do then iSR5's solution is the simplest.</p>\n<p>If not then you'll need a more complicated solution. On one hand I notice that you're not using any of the outputs of <code>ComputeNextValue</code>; you're only providing inputs to the indicators. Then one possible solution would be to define an interface with the void counterpart of <code>ComputeNextValue</code> which only takes an input and produces no output:</p>\n<pre><code>public abstract class IndicatorBase<TInput, TOutput> : IIndicatorBase<TInput>\n where TInput : struct\n where TOutput : struct\n{\n public abstract TOutput ComputeNextValue(TInput input);\n public abstract void Reset();\n\n void IIndicatorBase<TInput>.ComputeNextValue(TInput input) =>\n ((IndicatorBase<TInput, TOutput>)this).ComputeNextValue(input);\n}\n\npublic interface IIndicatorBase<TInput>\n where TInput: struct\n{\n void ComputeNextValue(TInput input);\n}\n</code></pre>\n<p>Then <code>ImportAndPreload</code> can become this: (I'm not sure what <code>BinanceKline</code> is, but the input type you're supplying to each indicator is the type of <code>BinanceKline.Close</code>, so that'd be the generic type argument for <code>IIndicatorBase</code>)</p>\n<pre><code>private void ImportAndPreload(string symbol, KlineInterval interval, params IIndicatorBase<TypeOfBinanceKlineDotClose>[] indicators)\n{\n ...\n\n // Preload indicators\n for (int i = 0; i < candles.Count; i++)\n {\n foreach (var indicator in indicators)\n {\n indicator.ComputeNextValue(candles[i].Close);\n }\n }\n}\n\n...\n\nImportAndPreload(symbol, interval, macd, stoch, rsi, ema);\n</code></pre>\n<p>This will support any indicator whose input is the type of <code>BinanceKline.Close</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T17:41:06.290",
"Id": "484653",
"Score": "0",
"body": "Awesome! Thanks a lot, that's what I wanted!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T17:20:22.800",
"Id": "247581",
"ParentId": "247563",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "247581",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T11:18:26.507",
"Id": "247563",
"Score": "6",
"Tags": [
"c#"
],
"Title": "Shortening list of arguments to some kind of a variadic function"
}
|
247563
|
<p>It is my solution from a challange from edabit.com named "Drunken Python". Thats the task:
You need to create two functions to substitute str() and int(). A function called int_to_str() that converts integers into strings and a function called str_to_int() that converts strings into integers.</p>
<p>I hope you can tell me things I could do better and if the algorithms I used (e.g. to calculate the length of an int) are optimal.</p>
<pre><code># A function called int_to_str() that converts integers into strings and a function called str_to_int() that
# converts strings into integers without using the in built functions "int()" and str().
def str_to_int(num_str):
dec_places = {11: 10000000000, 10: 1000000000, 9: 100000000, 8: 10000000, 7: 1000000, 6: 100000, 5: 10000, 4: 1000,
3: 100, 2: 10, 1: 1}
char_digit = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
num = 0
length = len(num_str)
for i in range(length):
x = char_digit[num_str[0 - (i + 1)]] * dec_places[i + 1]
num = num + x
return num
def calculate_length(num):
div = 10
i = 1
while num / div >= 1:
div = div * 10
i = i + 1
return i
def int_to_str(num_int):
word = ""
div = 10
char_digit = {0: '0', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9'}
length = calculate_length(num_int)
for i in range(length):
x = (num_int % div) // (div // 10)
word = char_digit[x] + word
num_int = num_int - x
div = div * 10
return word
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T11:30:30.053",
"Id": "484618",
"Score": "1",
"body": "`dec_places = {11: 10000000000, 10: 1000000000, 9: 100000000, 8: 10000000, 7: 1000000, 6: 100000, 5: 10000, 4: 1000, 3: 100, 2: 10, 1: 1}` **:** Consider `10 raised to power (k - 1)`'s python equivalent."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T12:14:46.007",
"Id": "484622",
"Score": "2",
"body": "Simpler: `str_to_int = eval; int_to_str = repr` :-P"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T05:35:34.830",
"Id": "484710",
"Score": "1",
"body": "\"You need to create two functions to substitute str() and int().\" That should be \"You need to create two functions to substitute for str() and int().\" Given how important wording is in programming, it's disappointing to see people being so cavalier."
}
] |
[
{
"body": "<h1>Keep it simple</h1>\n<p>Your functions are way too complicated. First, you can convert a single digit from integer to character by using <code>ord()</code> and the fact that the ordinals of the characters <code>'0'</code> to '<code>9</code>' are consecutive. Furthermore, you don't need to calculate the length of an integer if you reverse the way you build up the string. Here are example implementations that are simpler:</p>\n<pre><code>def str_to_int(num_str):\n num = 0\n\n for char in num_str:\n num *= 10\n num += ord(char) - ord('0')\n\n return num\n\ndef int_to_str(num_int):\n word = ""\n\n while num_int:\n word = chr(ord('0') + num_int % 10) + word\n num_int //= 10\n\n return word or "0"\n</code></pre>\n<h1>Integers can be negative</h1>\n<p>Your code (and my example simplification above) does not handle negative integers.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T13:09:08.993",
"Id": "484626",
"Score": "2",
"body": "`ord('0')` is a constant value. Can be put outside loop"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T15:52:33.350",
"Id": "484635",
"Score": "0",
"body": "Thank you! Your idea to use unicode numbers is surely way more efficient and very clever. I didn't even know about ord() and chr() before."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T13:02:15.477",
"Id": "247566",
"ParentId": "247564",
"Score": "4"
}
},
{
"body": "<p>Some minor comments to get started</p>\n<ul>\n<li>As <code>str_to_int</code> is intended to be an implementation of <code>int</code> you can name it as such. Either <code>int_</code> or plain <code>int</code> would be fine as names.</li>\n<li>The <code>0</code> in <code>num_str[0 - (i + 1)]</code> is not needed.</li>\n<li>Appending and prepending to a string in a loop has not entirely obvious quadratic time complexity. It won't matter much for short strings and adding single characters at a time, but be careful in choosing the right data structure.</li>\n<li><code>num = num + x</code> is more commonly written as <code>num += x</code></li>\n<li>If you don't use the loop variable, you can leave it out by replacing it with an underscore. <code>for _ in range(length):</code></li>\n</ul>\n<hr />\n<p>The code to convert a string to an int is unnecessarily limited. A KeyError is raised on a test like <code>x = str(10**16); str_to_int(x)</code>.</p>\n<p>Replacing the dictionary with <code>pow</code> will fix this.</p>\n<pre><code>10 ** (k - 1) # or you can write pow(10, k - 1)\n</code></pre>\n<p>Which in the code becomes</p>\n<pre><code>def str_to_int(num_str):\n # Deleted dec_places\n char_digit = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}\n num = 0\n length = len(num_str)\n for i in range(length):\n x = char_digit[num_str[-(i + 1)]] * 10 ** i # simplified from 10 ** ((i + 1) - 1)\n num += x\n return num\n</code></pre>\n<hr />\n<p><code>int_to_str</code> does a bit more work than it needs to. If you remove the line <code>num = num - x</code> you'll find the results are still the same.</p>\n<p>There is a slightly better approach you can take. Instead of multiplying up <code>div</code>, you could instead divide down <code>num_int</code>. The advantage of the suggested approach is that you will always be dividing and and modding by 10, rather than increasing powers of 10. This (should) be a bit faster overall, since it is easier to do arithmetic with small numbers.</p>\n<p>Modifying your current code to use this method might look like:</p>\n<pre><code>def str_(num_int):\n word = ""\n char_digit = {0: '0', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9'}\n length = calculate_length(num_int)\n for i in range(length):\n x = num_int % 10\n num_int //= 10\n word = char_digit[x] + word\n return word\n</code></pre>\n<p>You can use the same idea to simplify <code>calculate_length</code>. But even better, you don't need to calculate the length anymore, since you can stop when <code>num_int</code> has had all its digits divided out. You will need a special case for <code>0</code> though.</p>\n<pre><code>def str_(num_int):\n if num_int == 0:\n return '0'\n word = ""\n char_digit = {0: '0', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9'}\n while num_int:\n x = num_int % 10\n num_int //= 10\n word = char_digit[x] + word\n return word\n</code></pre>\n<hr />\n<p><code>int</code> has had a good bit more time spent on it, and as such has a little more robustness and functionality. You might consider whether you want to handle any of these cases.</p>\n<ul>\n<li>Negative numbers.</li>\n<li>Bases other than base 10.</li>\n<li>Whitespace around the number (' 777 \\t').</li>\n<li>Underscore as a separator ('10_000').</li>\n<li>A leading '+' ('+42')</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T15:49:24.427",
"Id": "484634",
"Score": "0",
"body": "Wow! I am so thankful for your help. I already learned so much from this! I think I'll try recoding the whole program to make sure I remember everything correctly and I'll try to implement the extra features(espacially the negative numbers). But again, thank you very much!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T18:54:42.910",
"Id": "484670",
"Score": "1",
"body": "About the quadratic runtime warning for strings: I just measured how long the string concats and divisions-by-10 take for a number with 30000 digits. The concats took about 0.02 seconds, the divisions about 1.5 seconds: https://repl.it/repls/GrumpyBuzzingSoftware#main.py"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T19:37:52.020",
"Id": "484681",
"Score": "1",
"body": "That is surprising. I will leave my comment on quadratic behaviour in, on the off chance someone reading has never heard of it before."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T13:52:15.333",
"Id": "247567",
"ParentId": "247564",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "247567",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T11:24:05.950",
"Id": "247564",
"Score": "7",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"reinventing-the-wheel"
],
"Title": "This python code converts integers to strings and strings to ints without the inbuilt functions \"int()\" and \"str()\""
}
|
247564
|
<p>I'm writing start/stop module for my application.</p>
<p>I have a class that manages application life cycle and I called it <code>Work</code>.
<code>Work</code> uses <code>WorkState</code> class that contains 4 states the application can be in, that's:</p>
<ul>
<li>INITIALIZING (state between NOT_RUNNING and RUNNING)</li>
<li>RUNNING</li>
<li>FINALIZING (state between RUNNING and NOT_RUNNING)</li>
<li>NOT_RUNNING</li>
</ul>
<p>The class also contains some useful methods to manage states.</p>
<p><code>Work</code> uses <code>QueryExecutor</code>. <code>QueryExecutor</code> is just a subclass of <code>ThreadPoolExecutor</code> with overriden method <code>afterExecute()</code> that changes application state after performing a start/stop task. (e.g. changing state from INITIALIZING to RUNNING after performing a start operation).</p>
<p><em><strong>MY VISION:</strong></em></p>
<p>When a thread invoke the <code>start()</code>/<code>stop()</code> methods, the code mustn't allow other thread to interfere the process until it's done. Also, there's no way to perform the stop action when the system is not started and vice versa.</p>
<p><em><strong>MY CONCERNS:</strong></em></p>
<ul>
<li>Should I change locking system to "fair"?</li>
<li>Will it work smoothly with <strong>2 threads</strong>? (There's no possibility that the <code>start()</code>/<code>stop()</code> can be accessed at the same time by more than <strong>2 threads</strong>)</li>
<li>Does the code have any bugs I can't see?</li>
<li>Any way to write it much simpler?</li>
</ul>
<p><strong>Work.java</strong></p>
<pre><code>public class Work {
//public start() and stop() methods that can be accessed
//from two threads:
//- JavaFX main thread (user action)
//- other thread (after all of the task are done)
//
//Those methods return a boolean that indicates if
//the chosen action was performed properly
//(just to show an alert to user)
public static boolean start() {
return processQuery(Query.START);
}
public static boolean stop() {
return processQuery(Query.STOP);
}
//------Internals
private static final QueryExecutor queryProcessor = new QueryExecutor(Work::unlockProcessing);
private static final WorkState state = new WorkState();
private static final Object lock = new Object();
private static boolean processQuery(Query query) {
synchronized (lock) {
if (state.isInProperState(query)) {
state.changeState(query);
queryProcessor.execute(query == Query.START ? Work::startQuery : Work::stopQuery);
return true;
} else {
return false;
}
}
}
private static void unlockProcessing() {
synchronized (lock) {
state.matureState();
}
}
private static void startQuery() {
// <SOME SYNCHRONOUS CODE>
}
private static void stopQuery() {
// <SOME SYNCHRONOUS CODE>
}
}
</code></pre>
<p><strong>WorkState.java</strong></p>
<pre><code>public class WorkState {
private State state = State.NOT_RUNNING;
public void changeState(Query query) {
state = query == Query.START ? State.INITIALIZING : State.FINALIZING;
}
public void matureState() {
state = state == State.INITIALIZING ? State.RUNNING : State.NOT_RUNNING;
}
public boolean isInProperState(Query query) {
return (state == State.RUNNING && query == Query.STOP)
|| (state == State.NOT_RUNNING && query == Query.START);
}
private enum State {
INITIALIZING, RUNNING, FINALIZING, NOT_RUNNING;
}
}
</code></pre>
<p><strong>QueryExecutor.java</strong></p>
<pre><code>public class QueryExecutor extends ThreadPoolExecutor {
private final Runnable unlockProcessingAfterExecute;
public QueryExecutor(Runnable unlockProcessingAfterExecute) {
super(1, 1, 0L,
TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>());
this.unlockProcessingAfterExecute = unlockProcessingAfterExecute;
}
@Override
protected void afterExecute(Runnable r,
Throwable t) {
super.afterExecute(r, t);
unlockProcessingAfterExecute.run();
}
}
</code></pre>
<p><strong>Query enum</strong></p>
<pre><code>public enum Query {
START, STOP
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T05:49:12.417",
"Id": "502844",
"Score": "0",
"body": "How is this related to `JavaFX`?"
}
] |
[
{
"body": "<p>Please take a look at this library for inspiration on how to state machine could be defined:\n<a href=\"https://projects.spring.io/spring-statemachine/\" rel=\"nofollow noreferrer\">https://projects.spring.io/spring-statemachine/</a></p>\n<ul>\n<li>Should I change locking system to "fair"? => Could you please clarify what you are trying to achieve</li>\n<li>Will it work smoothly with 2 threads? (There's no possibility that the start()/stop() can be accessed at the same time by more than 2 threads) => Yes. You have declared the only monitor object (<code>lock</code>) and configured <code>corePoolSize = 1</code>, <code>maximumPoolSize = 1</code>.</li>\n<li>Does the code have any bugs I can't see? => I do not understand what is the purpose of this exercise</li>\n<li>Any way to write it much simpler? => I think yes. Work is a singleton. the synchronized keyword could be used directly on <code>Work</code>'s methods. And without clarification, it looks like that the whole solution could be replaced with <code>ThreadPoolExecutor</code>, cause it is not clear why do we need <code>RUNNING</code>, <code>FINALIZING</code> states.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T12:34:47.543",
"Id": "484746",
"Score": "0",
"body": "1. Non-fair locks can potentially cause starvation. As you can see in my code, `lock` object can be used at the same time by 3 threads (JavaFX main, other thread and the second other thread from `QueryExecutor`). That could potentially lead to starvation"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T09:04:57.407",
"Id": "247601",
"ParentId": "247565",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T12:50:34.807",
"Id": "247565",
"Score": "3",
"Tags": [
"java",
"multithreading",
"javafx"
],
"Title": "Concerned about thread safety"
}
|
247565
|
<p>I've written a 'fast & dirty' PowerShell script to harvest a system inventory of Windows client and\or server operating systems to streamline case note documentation.</p>
<pre><code>$NewLine = "`n"
$FileName = Join-Path $Env:USERPROFILE 'Desktop\System Inventory.txt'
# Current Date
$TimeStamp = Get-Date -Format F
$SystemInventory = "# Current Date", $NewLine, $TimeStamp, $NewLine
# Detailed System Information
$OS = systeminfo.exe
$SystemInventory = $SystemInventory + "# Operating System", $OS, $NewLine
# PowerShell
$PoSh = $PSVersionTable.PSVersion
$SystemInventory = $SystemInventory + "# PowerShell", $PoSh, $NewLine
# .Net Framework
function Get-NetFramework {
$Lookup = @{
378389 = [version]'4.5'
378675 = [version]'4.5.1'
378758 = [version]'4.5.1'
379893 = [version]'4.5.2'
393295 = [version]'4.6'
393297 = [version]'4.6'
394254 = [version]'4.6.1'
394271 = [version]'4.6.1'
394802 = [version]'4.6.2'
394806 = [version]'4.6.2'
460798 = [version]'4.7'
460805 = [version]'4.7'
461308 = [version]'4.7.1'
461310 = [version]'4.7.1'
461808 = [version]'4.7.2'
461814 = [version]'4.7.2'
528040 = [version]'4.8'
}
Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -Recurse | `
Get-ItemProperty -Name Version, Release -EA 0 | Where-Object { $_.PSChildName -eq "Full" } | `
Select-Object @{ Name = ".NET Framework"; expression = { $_.PSChildName } }, Version, Release
}
$NetFrmWrk = Get-NetFramework | Format-Table -AutoSize
$SystemInventory = $SystemInventory + "# .Net Framework", $NetFrmWrk
# Storage Capacity
function Get-FreeSpace {
Get-WmiObject Win32_LogicalDisk -Filter "DriveType=3" -Computer . |
Select-Object SystemName, DeviceID, VolumeName,
@{ Name = "Total Size (GB)"; expression = { "{0:N1}" -f ($_.Size / 1GB) } },
@{ Name = "Free Space (GB)"; expression = { "{0:N1}" -f ($_.Freespace / 1GB) } },
@{ Name = "Free Space %"; expression = { "{0:N1}" -f (($_.Freespace / $_.Size) * 100) } } | Format-Table -AutoSize
}
$Storage = Get-FreeSpace
$SystemInventory = $SystemInventory + "# Storage", $Storage
# WindowsUpdateHistory
$Session = [activator]::CreateInstance([type]::GetTypeFromProgID('Microsoft.Update.Session'))
$Search = $Session.CreateUpdateSearcher()
$Count = $Search.GetTotalHistoryCount()
$Patch = $Search.QueryHistory(0, $Count)
$Updates = @()
foreach ($Update in $Patch) {
if ($Update.Operation -eq 1 -and $Update.ResultCode -eq 2 -and $Update.Title -notlike '*KB2267602*'-and $Update.Title -notlike '*KB4052623*') {
$Updates += New-Object -Type PSObject -Property @{
'KB' = [regex]::match($Update.Title, 'KB(\d+)')
'Date' = $Update.Date
'Title' = $Update.Title
'Description' = $Update.Description
}
}
}
$UpdateHistory = $Updates | Sort-Object Date -Descending | Format-Table KB, Date, Title -AutoSize
$SystemInventory = $SystemInventory + "# Updates & Hotfixes", $UpdateHistory
# Roles & Features
$CimOsInfo = Get-CimInstance -ClassName Win32_OperatingSystem
$CimSysType = $CimOsInfo.ProductType
if ($CimSysType -eq 1) {
Function ClientFeatures {
Get-WindowsOptionalFeature -Online | Where-Object State -EQ 'Enabled' | Select-Object FeatureName | Sort-Object FeatureName
}
$ClientFeatures = ClientFeatures
$SystemInventory = $SystemInventory + "# Roles & Features - Windows Client Platform", $ClientFeatures
}
else {
Function ServerFeatures {
Get-WindowsFeature | Where-Object Installed | Format-Table -Autosize -Wrap
}
$ServerFeatures = ServerFeatures
$SystemInventory = $SystemInventory + "# Roles & Features - Windows Server Platform", $ServerFeatures
}
# Save & Display Results
Clear-Host
Write-Host "Hard copy saved as" $FileName; Write-Host
$SystemInventory | Out-File -FilePath $FileName -Encoding ascii
Get-Content -Path $FileName
Write-Host "Hard copy saved as" $FileName; Write-Host
</code></pre>
<p>The results when run against my current system: <a href="https://1drv.ms/t/s!AvdD4MxAwWZA4EOvaJC9ey_6KuoE?e=z8bTHT" rel="nofollow noreferrer">System Inventory - Results</a>.</p>
<p>I have tested and validated this code's performance against remote systems within an active directory environment a few months back but have made several changes since then. As things stand right now, I currently do not have the resources to validate my code's performance against systems within an Active Directory environment. Real basic, I ran my script using the following sequence:</p>
<ol>
<li>Launch PowerShell (Admin)</li>
<li>& '.\System Inventory.ps1' <remote system
name, e.g. \AUPP-DC01></li>
</ol>
<p>Would very much appreciate the community's thoughts relative to this routine's performance and overall utility.</p>
<p>Thank you so much!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T02:41:31.250",
"Id": "484706",
"Score": "0",
"body": "the 1st thing that comes to mind is running all this in parallel. the `Invoke-Command` cmdlet will accept a list of systems & a scriptblock ... and then run it on those systems in parallel. quite a time saver. [*grin*] the other is making all those calls to the target system ... even if you just want to hit one system, don't make multiple calls targeting that system ... send the code to the target & run it there."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T15:25:20.883",
"Id": "247569",
"Score": "2",
"Tags": [
"beginner",
"powershell"
],
"Title": "PowerShell Script to Harvest System Inventory"
}
|
247569
|
<p>I've been going through some 2019 AoC challenges and decided to solve <a href="https://adventofcode.com/2019/day/6" rel="noreferrer">Day 6</a> in Haskell with the help of <code>Data.Tree</code>.</p>
<p>In summary, the puzzle provides a list of orbits (edges) as input, resembling:</p>
<pre><code>COM)B
B)C
C)D
D)E
E)F
B)G
G)H
D)I
E)J
J)K
K)L
K)YOU
I)SAN
</code></pre>
<p>where <code>COM</code> is supposedly the centre of all orbits (i.e. the root). We are tasked with parsing this and...</p>
<ul>
<li>for Part 1: Find the <strong>total</strong> number of <em>direct</em> and <em>indirect orbits</em>. In the example,
<ul>
<li><code>B</code> directly orbits <code>COM</code></li>
<li><code>C</code> directly orbits <code>B</code> (hence, indirectly orbiting <code>COM</code>)</li>
<li><code>D</code> directly orbits <code>C</code> (hence, indirectly orbiting <code>B</code> <em>and</em> <code>COM</code>)</li>
<li>and so on...</li>
</ul>
</li>
<li>for Part 2: Find the <em>minimum number of orbital transfers</em>. Basically, the number of traversals needed to get from the orbit of <code>YOU</code> to the orbit of <code>SAN</code>. In the example, the traversals are <code>K -> J -> E -> D -> I</code>. Hence, the minimum number of transfers is <strong><code>4</code></strong>.</li>
</ul>
<p>Here is my solution to both parts:</p>
<pre class="lang-hs prettyprint-override"><code>import Data.Tree
type Satellite = String
type STree = Tree Satellite
type Orbit = (Satellite, Satellite)
-- Part 1
main :: IO ()
main = interact $ show . countOrbits . fromOrbits . map parseOrbit . lines
-- Part 2
-- main :: IO ()
-- main = interact $ show . findMinimumTransfers "YOU" "SAN" . fromOrbits . map parseOrbit . lines
parseOrbit :: String -> Orbit
parseOrbit s = (takeWhile (/= ')') s, tail $ dropWhile (/= ')') s)
fromOrbits :: [Orbit] -> STree
fromOrbits orbits = construct "COM"
where construct :: Satellite -> STree
construct root = Node { rootLabel = root, subForest = map construct $ children root }
children :: Satellite -> [Satellite]
children sat = map snd $ filter ((== sat) . fst) orbits
countOrbits :: STree -> Integer
countOrbits = countOrbitsImpl 0
where countOrbitsImpl :: Integer -> STree -> Integer
countOrbitsImpl depth (Node rootLabel subForest)
| length subForest == 0 = depth
| otherwise = depth + (sum $ map (countOrbitsImpl (depth + 1)) subForest)
-- finds the minimum number of orbital transfers required between two targets
findMinimumTransfers :: Satellite -> Satellite -> STree -> Int
findMinimumTransfers tar tar' = findImpl 0
where -- find the common node where targets are (possibly indirect) children
findImpl :: Int -> STree -> Int
findImpl depth (Node rootLabel subForest)
| rootLabel == tar || rootLabel == tar' = depth - 1
| length subForest == 0 = 0
| otherwise =
let childResults = filter (/= 0) $ map (findImpl (depth + 1)) subForest
in if length childResults == 2
then sum childResults - (depth * length childResults) -- found common node
else sum childResults -- propagate results
</code></pre>
<p>I'm itching for feedback on the recursion. I use it mainly to keep track of a node's <code>depth</code> and later return it as part of the result... but is there a "better" way to write this? Maybe with folds or applicatives?</p>
<p>I <em>did</em> think about keeping depth as part of a node's data (so that we might have <code>type STree = Tree (Satellite, Int)</code>), then maybe we could fold over that, but I didn't want to "bloat" the structure with redundant information.</p>
<p>Other feedback is also welcome. Thanks!</p>
<p><sub>N.B. this is not a duplicate of <a href="https://codereview.stackexchange.com/questions/234762/adventofcode-2019-day-6-in-haskell">AdventOfCode 2019 day 6 in Haskell</a> as the implementation is different.</sub></p>
|
[] |
[
{
"body": "<h1><code>break</code> and <code>span</code></h1>\n<p>When we try to split a string in Haskell, we're a little bit out of luck if we only use the trusty <code>Prelude</code> and <code>base</code>. Handy functions like <code>split</code> or <code>splitOn</code> are in the adaptly named <code>split</code> package, and parser combinators are completely other beasts and an oribtal (heh) laser cannon on this problem.</p>\n<p>However, there are two functions that provide almost exactly what <code>parseOrbit</code> is trying to achieve: splitting a string on a single character:</p>\n<pre><code>span, break :: (a -> Bool) -> [a] -> ([a], [a])\nspan f xs = (takeWhile f xs, dropWhile f xs)\nbreak f xs = span (not . f)\n</code></pre>\n<p>We can simplify <code>parseOrbit</code> therefore to</p>\n<pre><code>parseOrbit :: String -> Orbit\nparseOrbit s = let (a, _:b) = break (==')') s in (a, b)\n</code></pre>\n<p>However, you seem to prefer <code>where</code>, so let's use a <code>where</code> clause instead:</p>\n<pre><code>parseOrbit :: String -> Orbit\nparseOrbit s = (a, b)\n where (a, _:b) = break (==')') s\n</code></pre>\n<h1>Type signatures in where clauses</h1>\n<p>As we have seen above, <code>(a, _:b)</code> had no type signature. Type signatures in <code>where</code> clasues are usually omitted. There is some <a href=\"https://stackoverflow.com/questions/10609936/why-is-it-so-uncommon-to-use-type-signatures-in-where-clauses\">controversy about that</a>, however there are some things to keep in mind:</p>\n<ul>\n<li>GHC never warns about missing type signatures in <code>where</code> clauses</li>\n<li>functions with type parameters cannot have a type without <code>ScopedTypeSignatures</code> (see <a href=\"https://stackoverflow.com/questions/48400105/specifying-a-function-type-signature-in-a-where-clause\">this SO question for an example</a>)</li>\n<li>a change in the top level type signature might need a lot of changes in <code>where</code> clauses</li>\n<li>if a function is complex enough to need a type, it might be reasonable to promote it into a top-level function. That way it can also be tested.</li>\n</ul>\n<p>I personally therefore omit type signatures in <code>where</code> clauses (<code>ST</code> shenengians aside).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-08T08:03:19.960",
"Id": "247648",
"ParentId": "247574",
"Score": "4"
}
},
{
"body": "<h1><code>countOrbits</code></h1>\n<p>Let's take a look at what your algorithm is doing. Suppose you are at a root node <code>r</code> with subtree <code>s</code> at depth <code>d0</code>. You return the sum of <code>d0</code> and all of the depths of the nodes in <code>s</code>.</p>\n<h2>Nitpicks</h2>\n<p><code>sum [] = 0</code>, so you could just write <code>countOrbitsImpl</code> as its <code>otherwise</code> clause. Not checking the <code>length</code> also makes your code slightly faster. <code>length</code> is O(n) in the list it acts on. So if <code>length subForest /= 0</code>, you'll iterate over the whole subforest before knowing that.</p>\n<p>In this case, you can eliminate the unnecessary guard, but where it is necessary to check the subforest, you should prefer <code>null subForest</code> to <code>length subForest == 0</code> because of the aforementioned reason.</p>\n<p>You should either put an <code>_</code> in front of a variable you don't use (<code>_rootLabel</code>) or replace the variable name with an <code>_</code>. Otherwise, if you turn on <code>-Wall</code> you'll get a warning about an unused variable.</p>\n<h2>Rewriting</h2>\n<p>You asked about an alternative to your recursive function using a fold or applicative. Here's a way to restate your algorithm: imagine that each node in the tree had a depth associated with it. You want the sum of that.</p>\n<p>So instead of recursing over the tree, you can make a tree of depths and then sum that tree. We'll get to how you can sum it in a moment, but let's first make that tree.</p>\n<pre class=\"lang-hs prettyprint-override\"><code>mkDepthTree :: Integer -> STree -> Tree Integer\nmkDepthTree depth (Node _ subForest) = Node depth (map (mkDepthTree (depth+1)) subForest)\n</code></pre>\n<p>This doesn't look very different from <code>countOrbitsImpl</code>, it just isn't adding anything up.</p>\n<p>Once we have the tree of depths, we want to sum it. Fortunately, <code>Tree</code> has a <a href=\"https://hackage.haskell.org/package/base-4.14.0.0/docs/Data-Foldable.html\" rel=\"nofollow noreferrer\"><code>Foldable</code></a> instance. Which means it's a valid input to <code>sum</code>. Thus, you can write <code>countOrbits</code> as</p>\n<pre class=\"lang-hs prettyprint-override\"><code>countOrbits :: STree -> Integer\ncountOrbits = sum . mkDepthTree 0\n where mkDepthTree depth (Node _ subForest) = Node depth (map (mkDepthTree (depth+1)) subForest)\n</code></pre>\n<p>I used your indentation, although I personally prefer using 2 spaces, putting a newline after <code>where</code> and then indenting the line after by 2 more.</p>\n<h2>Which to prefer?</h2>\n<p>In a function that is this simple, I wouldn't say either version is necessarily better. Converting to a tree of depths then summing feels more elegant (it can almost be written as a <code>foldMap</code> if you didn't need the depth information), but it's also slightly harder to understand. Recursing directly is slightly clunkier, but IMO easier to understand.</p>\n<p>So it's your decision.</p>\n<h1>More to come?</h1>\n<p>It got kind of late so I'm stopping this review. I'll see if I can edit in a review of <code>findMinimumTransfers</code> later.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-08T10:13:08.007",
"Id": "247653",
"ParentId": "247574",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "247648",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T16:03:45.077",
"Id": "247574",
"Score": "5",
"Tags": [
"programming-challenge",
"haskell"
],
"Title": "Advent of Code 2019: Day 6 (with Trees)"
}
|
247574
|
<p>I have Java (or C#, Python, Kotlin, or other similar language) class that will be used to communicate with client over network. Protocol used by this application allows many different ways to create connection (TCP, unix socket, serial port, …) and perform handshake (plain connection or TLS, with or without authentication). I use separate abstract class that will initialize the connection (called <code>ConnectionStarter</code>) and create instance of <code>Connection</code>. <code>Connection</code> will query the client for some information (this part is <strong>not</strong> dependent on used <code>ConnectionStarter</code>) and then allow communication with the other side.</p>
<h3>Initialisation of the connection</h3>
<ol>
<li><code>ConnectionStarter</code> creates the connection</li>
<li><code>ConnectionStarter</code> performs handshake</li>
<li><code>ConnectionStarter</code> creates <code>Connection</code></li>
<li><code>Connection</code> queries the client</li>
<li>the connection is initialized and <code>Connection</code> can be freely used</li>
</ol>
<p>The <code>Connection</code> will be <em>always</em> created by some descendant of <code>ConnectionStarter</code>.</p>
<hr />
<p>The question is: Should I include the <em>step 4</em> in <code>Connection</code> constructor or move it to separate function that <em>has to</em> be called?</p>
<h2>Source code</h2>
<pre class="lang-java prettyprint-override"><code>abstract class ConnectionStarter {
Connection startConnection() {
Socket socket = inializeSocket(); // Step 1
performHandshake(socket); // Step 2
return new Connection(socket); // Step 3
}
abstract Socket initializeSocket();
abstract void performHandshake()
}
class Connection {
Socket socket;
Connection(Socket socket) {
this.socket = socket;
// ━━ The client will be queried now (Step 4) ━━
queryClient()
}
void queryClient() { … } // Step 4
}
// Accessibility modifiers are omitted for simplicity.
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T16:31:37.907",
"Id": "484640",
"Score": "0",
"body": "Using Java is not a good idea. Use the technology that supports M:N threading model"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T17:00:56.597",
"Id": "484645",
"Score": "0",
"body": "@overexchange Code in the question is simplified a lot. I will not create single-threaded application. The real problem is that I do not want to block thread creating the connection."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T17:27:55.807",
"Id": "484651",
"Score": "0",
"body": "Whenever there is combination of CPU + IO bound computation, prefer technology that supports M:N threading model. Java runs on 1:1 threading modle using some C library. Prefer RUST or GO"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T19:10:36.080",
"Id": "484673",
"Score": "5",
"body": "\"Code in the question is simplified a lot.\" Code Review is about improving existing, working code. The example code that you have posted is not reviewable in this form because it leaves us guessing at your intentions. Unlike Stack Overflow, Code Review needs to look at concrete code in a real context. Please see [Why is hypothetical example code off-topic for CR?](//codereview.meta.stackexchange.com/q/1709)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T08:39:40.703",
"Id": "484731",
"Score": "0",
"body": "@overexchange that sounds interesting do you have some materials regarding the topic that I can read. I've read for threading models on OS level from Operating System Concepts from Abraham, Silberschatz, Galvin and Gagne, but I havent got the chance to see how different languages are using this threading models"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T15:54:21.807",
"Id": "484761",
"Score": "0",
"body": "@kuskmen you need to visit each language material and dwell into the details"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T20:46:28.907",
"Id": "484813",
"Score": "0",
"body": "Ye, but I cant find anything specific everything is like saying this is very platform specific and framework specific so how can you be so sure its 1:1 for java"
}
] |
[
{
"body": "<p>Usage of IO in the constructor can be confusing. You can call the <code>queryClient()</code> from <code>ConnectionStarter</code>:</p>\n<pre class=\"lang-java prettyprint-override\"><code>abstract class ConnectionStarter {\n Connection startConnection() {\n Socket socket = inializeSocket(); // Step 1\n performHandshake(socket); // Step 2\n Connection connection = Connection(socket); // Step 3\n connection.queryClient();\n return connection;\n }\n\n abstract Socket initializeSocket();\n abstract void performHandshake()\n}\n\nclass Connection {\n Socket socket;\n\n Connection(Socket socket) {\n this.socket = socket;\n }\n\n void queryClient() { … } // Step 4\n}\n\n// Accessibility modifiers are omitted for simplicity.\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T16:13:38.730",
"Id": "247576",
"ParentId": "247575",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T16:13:38.730",
"Id": "247575",
"Score": "-1",
"Tags": [
"java",
"c#",
"object-oriented",
"io",
"constructor"
],
"Title": "Is performing IO in constructor good idea?"
}
|
247575
|
<p>I have the following tables in MySQL:</p>
<pre><code>create table PostSchema
(id int not null primary key auto_increment,
categories int not null,
title varchar(50),
status varchar(20),
comments bool,
body varchar(255),
filename varchar(255),
date_created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP);
create table commentSchema (
id int not null primary key auto_increment,
userID int,
message varchar(255),
image varchar(255),
date_created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
postID int);
</code></pre>
<p><strong>Currently..</strong></p>
<p>When a post is created it saves an image in the <code>'/uploads'</code> directory. Path name is referenced in table <code>PostSchema</code> column name <code>filename</code>.</p>
<p>Next, when a comment is created with an image attached it is also saved in <code>'/uploads'</code> directory and the actual path name is referenced in <code>commentSchema</code> in column <code>image</code>.</p>
<p><strong>My Idea</strong></p>
<p>I have a router set up to <code>delete</code> the records from <code>PostSchema</code> and any <code>comments</code> are relevant to <code>PostSchema</code>. On top of that, I'll implement a <code>unlink</code> function to remove any images referenced in the both tables that are held in the <code>/uploads</code> directory.</p>
<p>I have a working code, just want to hear some reviews if there is anywhere I can improve :)</p>
<p><strong>Current working code:</strong></p>
<pre><code>router.delete('/:id', (req, response)=>{
// Execute query for deleting the post
// Get filename from database
db.query("SELECT filename FROM PostSchema WHERE id = ?", req.params.id,(err,fileResult)=>{
// If error
if(err){
return res.status(500).end(err.message);
}
// If not an error continue...
else{
try {
// Unlink comments images
db.query("select image from commentschema where postID = ?", req.params.id, (cErr, cRes)=>{
if(cErr){
return res.status(500).end(err.message);
}
else{
if(fs.existsSync(uploadDir + cRes[0].image)){
fs.unlink(uploadDir + cRes[0].image, (commentFile) => {
if (commentFile) throw err;
});
}
}
});
// Unlink PostSchema images
fs.unlink(uploadDir + fileResult[0].filename, (errs)=>{
// Delete PostSchema + Delete comments
db.query("delete t1, t2 from postschema t1 join commentschema t2 on t1.id = t2.postid where t1.id = ?;", req.params.id,(errors, results)=>{
if(errors){
console.log(errors);
}
else{
db.query("delete from postschema where id = ?", req.params.id, (er, res)=>{
if(errors){
console.log(errors);
}
else{
// Redirect to all posts page
req.flash('success_message', 'Post was succesfully deleted');
response.redirect(303, '/admin/posts');
}
});
}
});
});
}
catch (e) {
return res.status(500).end(e.message);
}
}
});
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T13:06:23.837",
"Id": "485660",
"Score": "1",
"body": "Please do not update the code in your question after receiving answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T13:54:21.413",
"Id": "485669",
"Score": "0",
"body": "@Mast No problem - thanks for the infromation"
}
] |
[
{
"body": "<p>I am not primarily a JS developer, therefore I won't assist you with the JavaScript part itself, but I can give you a few hints regarding several issues I've found.</p>\n<h2>Lack of transactional safety</h2>\n<p>In your example, you're executing two <code>DELETE</code> statements on the database.</p>\n<pre><code>1) delete t1, t2 from postschema t1 join commentschema t2 on t1.id = t2.postid where t1.id = ?\n\n2) delete from postschema where id = ?\n</code></pre>\n<p>Those statements are isolated in their own transactions and commit right after their execution. The problem here is, if the statement <strong>1)</strong> succeeds, but <strong>2)</strong> fails, all the records deleted with the statement <strong>1)</strong> will remain deleted, which can easily lead to unexpected database state.</p>\n<p>In order to prevent this, you want to wrap the statements which should either all succeed or all fail in a <a href=\"https://en.wikipedia.org/wiki/Database_transaction\" rel=\"nofollow noreferrer\">database transaction</a>.</p>\n<h2><code>DELETE</code> statement ambiguity and difficult readability</h2>\n<p>Although MySQL supports deleting records through <code>JOIN</code>, effectively allowing you to delete data from multiple tables in a single go, such statements are difficult to track what gets actually deleted. On top of that, certain database engines do not support such mechanism at all.</p>\n<p>I highly recommend you to change the statement, so that it deletes only the comments, which makes the query much easier to follow and to read.</p>\n<pre><code>DELETE FROM commentschema WHERE postid = ?\n</code></pre>\n<h2>Removing a file from the FS before removing a database record</h2>\n<p>This may introduce an unintentional side effect, if deletion of database records fails, leading to a situation where the database record points to a file location which no longer exists.</p>\n<p>In order to solve this, the order of operation should be swapped:</p>\n<ol>\n<li>delete data from the database,</li>\n<li>(now that nothing points to the file) delete the file from the file system.</li>\n</ol>\n<p>I have also noticed you're loading images for comments (plural!) by <code>postId</code>, but only removing the image of the first comment in the returned collection.</p>\n<p>This may be an accidental error in your implementation, since later you're deleting all comments, which makes me believe you want to delete all images, too.</p>\n<h2>Code nesting</h2>\n<p>Your code is quite nested, due to callbacks. In order to resolve this, you can:</p>\n<ol>\n<li>introduce smaller functions with different responsibilities (e.g. a function to load data from the database, a function to delete a file,...),</li>\n<li>convert functions which output result through callbacks to promises and cleanup the code a little bit through promise-chaining (even better if you use <code>async/await</code>).</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-13T10:15:30.793",
"Id": "247848",
"ParentId": "247577",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T16:31:03.197",
"Id": "247577",
"Score": "2",
"Tags": [
"javascript",
"node.js"
],
"Title": "Node JS delete multiple MySQL linked records and delete physical file"
}
|
247577
|
<p>During development I needed to design a state machine with decision which runs to completion and performs state transition without the need to wait for events. So i come up with the following implementation that I want to share.</p>
<p>So the state machine is described with the following Enum</p>
<pre><code>public enum PnoBarringState {
OPERATOR_WHITE_LIST_START {
@Override
public PnoBarringState nextState(SessionData sessionData, String pnoValue) {
if (commonMethods.isMatchingOperatorsWhiteList(sessionData, pnoValue)) {
return GROUP_WHITE_LIST;
} else {
return OPERATOR_BLACK_LIST;
}
}
},
GROUP_WHITE_LIST {
@Override
public PnoBarringState nextState(SessionData sessionData, String pnoValue) {
if (commonMethods.isMatchingGroupsWhiteList(sessionData, pnoValue)) {
return PNO_CHECK_FINISHED;
} else {
return GROUP_BLACK_LIST;
}
}
},
OPERATOR_BLACK_LIST {
@Override
public PnoBarringState nextState(SessionData sessionData, String pnoValue) {
if (commonMethods.isMatchingOperatorsBlackList(sessionData, pnoValue)) {
return PNO_FORBIDDEN_NUMBER_OPERATOR_LEVEL;
} else {
return GROUP_WHITE_LIST;
}
}
},
GROUP_BLACK_LIST {
@Override
public PnoBarringState nextState(SessionData sessionData, String pnoValue) {
if (commonMethods.isMatchingGroupsBlackList(sessionData, pnoValue))
return PNO_FORBIDDEN_NUMBER_GROUP_LEVEL;
else {
return PNO_CHECK_FINISHED;
}
}
},
PNO_CHECK_FINISHED {
@Override
public PnoBarringState nextState(SessionData sessionData, String pnoValue) {
return this;
}
@Override
public boolean hasNext() {
return false;
}
},
PNO_FORBIDDEN_NUMBER_OPERATOR_LEVEL {
@Override
public PnoBarringState nextState(SessionData sessionData, String pnoValue) {
throw new CustomUncheckedException( "Operator Level Barring");
}
},
PNO_FORBIDDEN_NUMBER_GROUP_LEVEL {
@Override
public PnoBarringState nextState(SessionData sessionData, String pnoValue) {
throw new CustomUncheckedException("Group Level Barring");
}
};
public abstract PnoBarringState nextState(SessionData sessionData, String pnoValue);
public boolean hasNext() { return true; }
}
</code></pre>
<p>Function "nextState()" is abstract and implemented in each state in order to examine the transition and return to a new state. Only the "END" state is returning to the same state.
Since it is also desinged to be used in a run-to-completation a "hasNext()" function is provided. The "END" state is overwritting so as to declare the finish of the state-machine.</p>
<p>This enum is then used inside a normal application code with the following way.</p>
<pre><code>PnoBarringState pnoBarringState = PnoBarringState.OPERATOR_WHITE_LIST_START;
while (pnoBarringState.hasNext()) {
pnoBarringState = pnoBarringState.nextState(sessionData, pnoValue);
}
</code></pre>
<p>I am not sure whether any pattern describes it in the same way but i was feeling like sharing it.
Any other approaches are considered valuable.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T17:57:43.993",
"Id": "484658",
"Score": "4",
"body": "There are way better OO [_design-patterns_](https://sourcemaking.com/design_patterns/state) than this. Use _Flyweights_ instead of the enum."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T05:43:17.423",
"Id": "484711",
"Score": "0",
"body": "To be honest I don't get how with Flyweights will create a run-to-completion case. I mean an single event trigger will cause the pass from all affected states. Are you also referring that the states will be Different Concrete classes (which is somethign i am trying to avoid)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T06:04:39.667",
"Id": "484714",
"Score": "0",
"body": "_\"which is somethign i am trying to avoid\"_ Why so? Usually you should avoid to clutter the context with the concrete states, and especially with their specific behaviors."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T06:37:22.937",
"Id": "484717",
"Score": "0",
"body": "At least i am trying to avoid to depict every state with a class. State Pattern for example creates too many useless classes. Anyway ... Do you have any small sampe how Flyweights migth help to create a \"state or transition pattern since I have never seen any implementation for such a thing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T06:55:12.283",
"Id": "484719",
"Score": "0",
"body": "Please explain why you feel that the classes created in the state-pattern are useless."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T06:59:17.907",
"Id": "484720",
"Score": "0",
"body": "@MakisPapapanagiotou _\"Do you have any small sampe how Flyweights\"_ These would be the concrete state classes. You can provide an abstract base class for those which implement no specific behavior, beyond `getNext()`. I have an example for a framework in c++, but it uses templates. I believe with Java generics it could be even easier to implement such."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T07:03:02.223",
"Id": "484721",
"Score": "0",
"body": "@TorbenPutkonen: For me the most common problem issue is: More difficult to see all states and their relations by looking at code, since they are spread among several different classes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T07:03:20.980",
"Id": "484722",
"Score": "0",
"body": "@πάνταῥεῖ: Can you ping me this part in C++ ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T07:07:26.230",
"Id": "484724",
"Score": "0",
"body": "sorry ...i mean send me any kind of link to this code.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T07:12:23.680",
"Id": "484727",
"Score": "0",
"body": "@MakisPapapanagiotou https://makulik.github.io/sttcl/ Warning: It's complex, but reasonably documented. And you won't need static polymorphism (it's not possible in Java anyways, and is an optimization for low resource (embedded) systems)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T09:28:16.597",
"Id": "484734",
"Score": "0",
"body": "From a fast look i had this is more like a state-machine pattern. At least one think that mess me up with this is that i don't have a direct look of the state machine interraction. Thus when having multiple and large number of states/events I would rather go towards \"transition pattern like\". i..e table clearly defining the transitions and having as elements callbacks, function pointers or objects (what ever fits better) to describe the action. Anyway this is a matter of taste and in any case what ever discussion for design principles may give some food for thought (my personal view of course)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T10:09:49.590",
"Id": "484736",
"Score": "0",
"body": "@MakisPapapanagiotou That's where the Java package structure comes in. How I see it is that you now have several different responsibilities stuck in a single enumeration, violating SOLID principles. Also, I have a principle of avoiding introducing non-standard methods to enums. I do not want to surprise my user base with non-standard functionality."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T10:11:41.390",
"Id": "484737",
"Score": "0",
"body": "In a equally valid justification: stuffing the states inside the emum makes it harder to see all states because you always have to open the enum instead of just looking at the class structure."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T11:44:19.460",
"Id": "484743",
"Score": "0",
"body": "Your forbidden values throw when you call `nextState`. Does it really make sense for `hasNext` to return `true` in this scenario?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-11T07:21:58.290",
"Id": "485126",
"Score": "0",
"body": "Do your `isMatching...` functions mutate `SessionData`?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "15",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T17:53:08.743",
"Id": "247582",
"Score": "1",
"Tags": [
"java",
"design-patterns",
"enum",
"state-machine"
],
"Title": "Self Running iterable state machine with Enums in Java"
}
|
247582
|
<p>Core Guidelines mention a type <code>synchronized_value<T></code>, which supposedly pairs <code>std::mutex</code> with the internal value. I couldn't find any implementation both in <em>GSL-Lite</em> and <em>MS GSL</em> libraries.
The SV class stores <code>T value</code> coupled with <code>std::mutex</code>. It implements pointer and dereference operators which create a temporary object of <code>xlock</code> which locks the mutex while alive.</p>
<p>Example usage is:</p>
<pre><code>synchronized_value<Dummy> svDummy{}; // when Dummy is default-constructable
Foo(*svDummy);
</code></pre>
<p>When <code>Foo()</code> is called, a temporary <code>xlock</code> locks the mutex and keeps it until the function returns.</p>
<p>I implemented my class and want to have it reviewed.</p>
<p>I decided to delete move constructors of <code>xlock</code>, because it stores a reference and I don't want to deal with invalid state. Moreover I see no reason for such functionality.</p>
<p>To check the implementation I have written 3 tests: 2 control with <code>std::lock_guard</code> and <code>std::unique_lock</code> that explicitly lock a separate mutex. And 1 with <code>synchronized_value</code>. All the tests are passing.</p>
<p>Here is a link to my <a href="https://github.com/ElDesalmado/synchronized_value" rel="noreferrer">repository</a> with the library and tests (CTest).</p>
<pre><code>#pragma once
#include <mutex>
#include <type_traits>
template<typename ...>
using void_t = void;
template<typename T, typename Tuple, typename = void_t<>>
struct is_aggregate_constructable_ : std::false_type
{
};
template<typename T, typename ... Args>
struct is_aggregate_constructable_<T,
std::tuple<Args...>,
void_t<decltype(T{Args()...})>> : std::true_type
{
};
template<typename T, typename ... Args>
struct is_aggregate_constructable :
is_aggregate_constructable_<T, std::tuple<Args...>>
{
};
// TODO: add timer?
template<typename T, typename Mutex = std::mutex>
class xlock
{
public:
using value_type = std::conditional_t<std::is_const<T>::value, const T, T>;
using mutex_type = Mutex;
xlock(value_type &refValue, Mutex &mutex)
: refValue_(refValue),
uniqueLock_(mutex)
{}
xlock(const xlock &other) = delete;
xlock(xlock &&other) = delete;
xlock &operator=(const xlock &other) = delete;
xlock &operator=(xlock &&other) = delete;
value_type *operator->()
{ return &refValue_; }
const value_type *operator->() const
{ return &refValue_; }
value_type &operator*()
{ return refValue_; }
const value_type &operator*() const
{ return refValue_; }
operator value_type &()
{ return refValue_; }
operator const value_type &() const
{ return refValue_; }
~xlock()
{
}
private:
value_type &refValue_;
std::unique_lock<mutex_type> uniqueLock_;
};
template<typename T, typename Mutex = std::mutex>
class synchronized_value
{
public:
using value_type = T;
using mutex_type = Mutex;
using xlock_t = xlock<value_type, mutex_type>;
using cxlock_t = xlock<const value_type, mutex_type>;
template<typename =
std::enable_if_t<std::is_default_constructible<T>::value>>
synchronized_value()
{};
explicit synchronized_value(T value)
: value_(std::forward<T>(value))
{}
synchronized_value(const synchronized_value &) = delete;
synchronized_value &operator=(const synchronized_value &) = delete;
synchronized_value(synchronized_value &&other) = delete;
synchronized_value &operator=(synchronized_value &&other) = delete;
xlock_t operator*()
{ return {value_, mutex_}; }
cxlock_t operator*() const
{ return {value_, mutex_}; }
xlock_t operator->()
{ return {value_, mutex_}; }
cxlock_t operator->() const
{ return {value_, mutex_}; }
value_type &value()
{ return value_; }
const value_type& value() const
{ return value_; }
private:
value_type value_;
mutable mutex_type mutex_;
};
</code></pre>
<p>Testing functions:</p>
<pre><code>// run_check.h
#pragma once
#include "synchronized_value/synchronized_value.h"
#include <iostream>
#include <thread>
struct Dummy
{
int64_t id;
bool b;
};
struct Wrapped
{
synchronized_value<Dummy>& sv;
};
// false if check is successful
bool run_check(Dummy& d, int64_t assign, size_t intervals)
{
d.id = assign;
// std::cout << "run_check " << assign << " thread: " <<
// std::this_thread::get_id() << '\n';
for (size_t i = 0; i != intervals; ++i)
++d.id;
// std::cout << "end_check " << assign << " thread: " <<
// std::this_thread::get_id() << '\n' << std::endl;
return bool(d.id - assign - intervals);
}
bool run_check_w(Wrapped& w, int64_t assign, size_t intervals)
{
return run_check(*w.sv, assign, intervals);
}
template <typename Guard>
bool check_mutex(Dummy& d, std::mutex& mutex, uint64_t assign, size_t intervals)
{
Guard guard{mutex};
d.id = assign;
for (size_t i = 0; i != intervals; ++i)
++d.id;
return bool(d.id - assign - intervals);
}
</code></pre>
<p>Testing unit:</p>
<pre><code>#include "run_check.h"
#include <future>
#include <random>
#include <string>
#include <iostream>
template <typename T1, typename T2>
constexpr bool is_same_v = std::is_same<T1, T2>::value;
int main(int argc, const char **argv)
{
size_t intervals = 10000;
if (argc == 2)
{
try
{
intervals = std::stoll(argv[1]);
}
catch (const std::invalid_argument &)
{
std::cerr << "Invalid argument for intervals: using " << intervals <<
" intervals fot test" << std::endl;
}
}
static_assert(is_aggregate_constructable<Dummy, uint64_t, bool>(), "Invalid result");
static_assert(is_aggregate_constructable<Dummy, int, bool>(), "Invalid result");
static_assert(is_aggregate_constructable<Dummy, int, int>(), "Invalid result");
static_assert(!is_aggregate_constructable<Dummy, double, int>(), "Invalid result");
static_assert(is_same_v<typename xlock<Dummy>::value_type,
Dummy>, "Invalid result");
static_assert(is_same_v<typename xlock<const Dummy>::value_type,
const Dummy>, "Invalid result");
std::mutex mutex;
Dummy d{1};
{
xlock<Dummy> xlock1{d, mutex};
xlock1->id;
Dummy dummy = *xlock1;
Dummy& refDummy = *xlock1;
const Dummy& crefDummy = *xlock1;
}
{
xlock<const Dummy> xlock_const{d, mutex};
xlock_const->id;
Dummy dummy = *xlock_const;
// Dummy& refDummy = *xlock_const;
const Dummy& crefDummy = *xlock_const;
}
{
const xlock<const Dummy> xlock_const{d, mutex};
xlock_const->id;
}
{
synchronized_value<Dummy> synchValue{d};
synchValue->id;
Dummy dummy = *synchValue;
Dummy& refDummy = *synchValue;
const Dummy& crefDummy = *synchValue;
}
{
const synchronized_value<Dummy> synchValueConst2{d};
synchValueConst2->id;
Dummy dummy = *synchValueConst2;
// Dummy& refDummy = *synchValueConst2;
const Dummy& crefDummy = *synchValueConst2;
}
synchronized_value<Dummy> dummy{{16}};
bool first_check = run_check(*dummy, 42, 1000);
std::random_device rd;
std::mt19937 rng(rd());
std::uniform_int_distribution<int64_t> dist(-69800, 385697);
std::vector<Wrapped> input(1000, {dummy});
std::vector<std::future<bool>> results;
for (size_t i = 0; i != 1000; ++i)
{
results.push_back(std::async(std::launch::async,
&run_check_w,
std::ref(input[i]),
dist(rng),
intervals));
}
int result = 0;
for (size_t i = 0; i != 1000; ++i)
result += (int)results[i].get();
return result;
}
</code></pre>
<p>Control tests you can find at my repo.</p>
<p>How it can be improved? What may have I missed?</p>
<hr />
<p>I updated this question. I found out that initial test was incorrect, but I have fixed it. Now everything works</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T21:32:32.540",
"Id": "484689",
"Score": "1",
"body": "You haven't clearly explained (nor linked to an explanation of) what `synchronized_value<T>` is supposed to do, nor what `xlock` is supposed to do. You ask why your test harness \"fails,\" but surely you could find that out by compiling it and seeing which line has the error, right? Or which of the tests misbehaves at run time? The whole point of testing is to find out _what_ goes wrong and _why_. If you don't know, then your tests aren't granular enough."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T21:42:12.720",
"Id": "484690",
"Score": "1",
"body": "@Quuxplusone I thought saying that it pairs `std::mutex` to the value is enough. If not, later I will add this explanation. `xlock` is an object that locks the mutex while it is alive and is created when `synchronized_value` gets dereferenced. So when I pass `Dummy` to `run_check` by dereferencing synch value, I lock its mutex in a temporary `xlock` object. It should not be unlocked until function has returned and a destructor of `xlock` has been locked. Basically it is the same approach as locking mutex, but in this case it is stored within."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T21:44:06.410",
"Id": "484691",
"Score": "1",
"body": "@Quuxplusone I can not *find out which line has error* since it is undetectable (on 10000 invocations there are only 10-100 fails). And happens **only** in **Debug** mode."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T22:09:03.963",
"Id": "484696",
"Score": "2",
"body": "Ah, your `xlock` doesn't match anything in the [proposal P0290](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0290r2.html). What you're missing is the `apply` function that takes a callable and a pack of SVs, calls `std::lock` with all the SVs, calls the callable with the-values-of-all-the-SVs, and then unlocks all the SVs before returning. If your test fails only 1 in 1000 times, try running it 1000 times and then see which line has the failure. You might need to add some debugging printfs, or split the test program into smaller pieces."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T02:32:34.383",
"Id": "484705",
"Score": "0",
"body": "@Quuxplusone this is completely different story. The proposal is for `std::apply` to be able to take SVs as arguments, my class is for locking on dereferencing. Though I have an idea that my test does something wrong."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T19:11:46.680",
"Id": "247586",
"Score": "7",
"Tags": [
"c++",
"multithreading",
"c++14",
"thread-safety",
"concurrency"
],
"Title": "Implementing GSL synchronized_value"
}
|
247586
|
<p>I recently finished chapter 8 of Rust's book, and below is my solution to the <a href="https://doc.rust-lang.org/stable/book/ch08-03-hash-maps.html#summary" rel="nofollow noreferrer">third exercise</a>:</p>
<blockquote>
<p>Using a hash map and vectors, create a text interface to allow a user
to add employee names to a department in a company. For example, “Add
Sally to Engineering” or “Add Amir to Sales.” Then let the user
retrieve a list of all people in a department or all people in the
company by department, sorted alphabetically.</p>
</blockquote>
<p>I'd appreciate pointers on how the code can be improved. Thanks in advance.</p>
<pre><code>use std::io;
use std::collections::HashMap;
//An attempt at Rust book's chapter 8's third exercise:
//https://doc.rust-lang.org/book/ch08-03-hash-maps.html
fn main() {
println!("The Office - Text Interface.");
println!();
println!("Enter a query, type HELP for a list of keyword and their functions, or type EXIT to exit.");
println!();
//build hashmap{department: vec[names]} database, insert default values
let mut company = HashMap::new();
let depts = vec!["SALES", "ENGINEERING", "HR", "SANITATION"];
let sales = vec!["Sally", "Jordan", "Charlie", "Abigail"];
let engineering = vec!["Suzy", "Jay", "Chi", "Amy"];
let hr = vec!["Son", "Jack", "Chia", "Anna"];
let sanitation = vec!["August", "Entangle", "Will", "Jada"];
let tup = [sales, engineering, hr, sanitation];
let mut g: Vec<_> = Vec::new();
company = depts.into_iter()
.map(|x| x.to_string())
.zip(tup.iter().map(|y| {g = y.iter().map(|q| q.to_string()).collect(); g.clone()}))
.collect();
let keywords = ["ADD", "LIST", "UPDATE", "REMOVE", "HELP", "EXIT"];
// loop the input part of the text interface.
//validate first keyword, send queries to functions.
loop {
let mut query = String::new();
println!("::");
//check for empty input
io::stdin().read_line(&mut query).expect("Enter a valid input");
query = query.trim().to_string();
// println!("{}", query);
if query.is_empty() {
println!("Invalid input. Type HELP for a keyword reference.");
continue;
}
//check for valid first keyword
let keyword = query.split_whitespace().next().unwrap().to_uppercase();
if !keywords.contains(&&keyword[..]) {
println!("Invalid Keyword. Type HELP for a keyword reference.");
continue;
}
//keyword validated. Call the function.
let mut query = query.split_whitespace().collect::<Vec<_>>();
match &&keyword[..] {
&"EXIT" => return,
&"HELP" => help(),
&"ADD" => add(&mut query, &mut company),
&"LIST" => list(&mut query, &mut company),
&"UPDATE" => update(&mut query, &mut company),
&"REMOVE" => remove(&mut query, &mut company),
_ => (),
}
// println!("{:?}", company); //debug purposes: print the entire hashmap on each loop to monitor changes.
continue;
}
}
fn add(q: &mut Vec<&str>, company: &mut HashMap<String, Vec<String>>) {
//validate add syntax
let length = q.len();
if length < 3 || length > 4 {
println!("Invalid ADD syntax. Type HELP for a keyword reference.");
return;
}
//add a new department
if length == 3 {
match (q[0], q[1], q[2]) {
("ADD", "-D", d) => {
//check if dept exists
let dept = d.to_uppercase();
if company.contains_key(&dept) {
println!("Department {} already exists.", d);
return;
}
//add dept
company.entry(dept).or_insert(Vec::new());
println!("Created department {}.", d);
return;
}
_ => {
println!("Invalid syntax.");
return;
}
}
}
//add a person to a department
if length == 4 {
match (q[0], q[1], q[2], q[3]) {
("ADD", name, "TO", d) => {
//check if dept exists
let dept = d.to_uppercase();
if !company.contains_key(&dept) {
println!("Department {} does not exist.", d);
return;
}
//check if name already exists in dept
if company[&dept].contains(&name.to_owned()) {
println!("The name {} already exists in {}.", name, dept);
return;
}
//add name to vector
(*company.get_mut(&dept).unwrap()).push(name.to_owned());
println!("Added {} to {}.", name, d);
}
_ => {
println!("Invalid Syntax");
return;
}
}
}
}
fn list(q: &mut Vec<&str>, company: &mut HashMap<String, Vec<String>>) {
//sanitize input
let length = q.len();
if length != 2 && length !=4 {
println!("Invalid number of arguments.");
return;
}
if length == 2 {
match (q[0], q[1]) {
//list all depts
("LIST", "-D") => {
let mut depts: Vec<_> = company.keys().collect();
depts.sort();
for d in depts {
println!("{}", d);
}
return;
}
//list everyone in all depts, sorted alphabetically
("LIST", "-E") => {
for (dept, mut names) in company.clone() {
println!("---{}---", dept);
names.sort();
for name in names {
println!("{}", name);
}
}
}
_ => {
println!("Invalid Syntax.");
return;
}
}
}
if length == 4 {
match (q[0], q[1], q[2], q[3]) {
("LIST", "-E", "IN", d) => {
//check if dept exists
let dept = d.to_uppercase();
if !company.contains_key(&dept) {
println!("Department {} does not exist.", d);
return;
}
//list all in department
println!("---{}---", dept);
(*company.get_mut(&dept).unwrap()).sort();
for name in &company[&dept] {
println!("{}", name);
}
}
_ => {
println!("Invalid Syntax.");
return;
}
}
}
}
fn update(q: &mut Vec<&str>, company: &mut HashMap<String, Vec<String>>) {
let length = q.len();
if length != 5 && length != 6 {
println!("Invalid UPDATE syntax.");
return;
}
if length == 5 {
match (q[0], q[1], q[2], q[3], q[4]) {
//update a department
("UPDATE", "-D", old_d, "TO", new_d) => {
//check if dept exists
let old_dept = old_d.to_uppercase();
let new_dept = new_d.to_uppercase();
if !company.contains_key(&old_dept) {
println!("Department {} does not exist.", old_d);
return;
}
if company.contains_key(&new_dept) {
println!("Department {} already exists.", new_d);
return;
}
//rename dept. Technique is to build a new vector with that same name since you
//cannot change the key of a hash map.
let temp_dept = company.get(&old_dept).unwrap().clone();
company.insert(new_dept.to_uppercase(), temp_dept);
company.remove(&old_dept);
println!("Changed Department {} to {}.", old_d, new_d);
return;
}
_ => {
println!("Invalid syntax.");
return;
}
}
}
//change a name in a department
match (q[0], q[1], q[2], q[3], q[4], q[5]) {
("UPDATE", old_name, "FROM", d, "TO", new_name) => {
//check if dept exists
let dept = d.to_uppercase();
if !company.contains_key(&dept) {
println!("Department {} does not exist.", d);
return;
}
//check if old name and new name exist
if !company[&dept].contains(&old_name.to_owned()) {
println!("The name {} does not exist in {}.", old_name, dept);
return;
}
if company[&dept].contains(&new_name.to_owned()) {
println!("The name {} already exists in {}.", new_name, dept);
return;
}
//update the name.
for (i, name) in company[&dept].clone().iter().enumerate() {
if name == old_name {
(*company.get_mut(&dept).unwrap())[i] = new_name.to_owned();
println!("Changed {} in {} to {}.", old_name, dept, new_name);
return;
}
}
}
_ => {
println!("Invalid Syntax.");
return;
}
}
}
fn remove(q: &mut Vec<&str>, company: &mut HashMap<String, Vec<String>>) {
let length = q.len();
if length !=3 && length !=4 {
println!("Invalid REMOVE syntax.");
return;
}
if length == 3 {
match (q[0], q[1], q[2]) {
("REMOVE", "-D", d) => {
//check if dept exists
let dept = d.to_uppercase();
if !company.contains_key(&dept) {
println!("Department {} does not exist.", d);
return;
}
//remove the department.
company.remove(&dept);
println!("Removed department {}.", d);
return;
}
_ => {
println!("Invalid Syntax.");
return;
}
}
}
//remove a person
match (q[0], q[1], q[2], q[3]) {
("REMOVE", name, "FROM", d) => {
//check if dept exists
let dept = d.to_uppercase();
if !company.contains_key(&dept) {
println!("Department {} does not exist.", d);
return;
}
//check if name exists
if !company[&dept].contains(&name.to_owned()) {
println!("The name {} does not exist in {}.", name, dept);
return;
}
//remove the name
for (i, _name) in company[&dept].clone().iter().enumerate() {
if _name == name {
(*company.get_mut(&dept).unwrap()).remove(i);
println!("Removed {} from {}.", name, dept);
return;
}
}
}
_ => {
println!("Invalid Syntax.");
return;
}
}
}
fn help() {
println!("The Office - KEYWORD HELP");
println!();
println!("Note: All keywords are case-sensitive.");
println!("Keywords: \nLIST - Lists items in the database");
println!("Usage: LIST -E - Lists all employees");
println!(" LIST -E IN [DEPARTMENT] - Lists all employees in specified department.");
println!(" LIST -D - Lists all departmnets in the company");
println!();
println!("ADD - Adds items to the database.");
println!("Usage: ADD [name] TO [department] - Adds the name to the specified department.");
println!(" ADD -D [department] - Adds the department to the roster.");
println!();
println!("REMOVE - Removes items from the database.");
println!(" REMOVE -D [department] - Removes the particular department from the database.");
println!(" REMOVE [name] FROM [department] - Removes the person from the specified department.");
println!();
println!("UPDATE - Changes records in the database.");
println!("Usage: UPDATE -D [old name] TO [new name] - Changes a department's name.");
println!(" UPDATE [old name] FROM [department] TO [new name] - Changes a person's name.");
println!();
println!("HELP - Prints this help screen.");
println!();
println!("EXIT - Exits the program.")
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T11:03:28.703",
"Id": "484741",
"Score": "3",
"body": "To improve readability, run `cargo fmt` in your project root. This will run [rustfmt](https://github.com/rust-lang/rustfmt) which will automatically format your code according to the official code style. If you want, you can [configure rustfmt](https://rust-lang.github.io/rustfmt/?version=master&search=) to behave differently"
}
] |
[
{
"body": "<p>Welcome to Code Review.</p>\n<h1>Formatting</h1>\n<p>The first thing I did to your code was to apply <code>rustfmt</code> by typing\n<code>cargo fmt</code>. <code>rustfmt</code> formats your code to fit with Rust's standard\nformatting guidelines. Here's some notable changes.</p>\n<pre><code>- company = depts.into_iter()\n- .map(|x| x.to_string())\n- .zip(tup.iter().map(|y| {g = y.iter().map(|q| q.to_string()).collect(); g.clone()}))\n- .collect();\n+ company = depts\n+ .into_iter()\n+ .map(|x| x.to_string())\n+ .zip(tup.iter().map(|y| {\n+ g = y.iter().map(|q| q.to_string()).collect();\n+ g.clone()\n+ }))\n+ .collect();\n</code></pre>\n<p>Method invocation chains are indented. Complex closures are formatted\nover several lines.</p>\n<pre><code>- if length !=3 && length !=4 {\n+ if length != 3 && length != 4 {\n</code></pre>\n<p>Most binary operators are surrounded by spaces.</p>\n<h1>Clippy</h1>\n<p>After that, <code>cargo clippy</code> pointed out some issues with your code.</p>\n<pre><code>warning: unneeded `return` statement\n --> src\\main.rs:270:13\n |\n270 | return;\n | ^^^^^^^ help: remove `return`\n |\n = note: `#[warn(clippy::needless_return)]` on by default\n = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_return\n\nwarning: unneeded `return` statement\n --> src\\main.rs:332:13\n |\n332 | return;\n | ^^^^^^^ help: remove `return`\n |\n = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_return\n</code></pre>\n<p>In Rust, functions automatically return when control flow reaches the\nend of the function body, so the explicit <code>return</code>s are unnecessary.</p>\n<pre><code>warning: value assigned to `company` is never read\n --> src\\main.rs:16:9\n |\n16 | let mut company = HashMap::new();\n | ^^^^^^^^^^^\n |\n = note: `#[warn(unused_assignments)]` on by default\n = help: maybe it is overwritten before being read?\n</code></pre>\n<p>You assigned an initial value to <code>company</code>, but overwrote it\nafterwards. It is recommended to postpone the declaration of\n<code>company</code> to the place you calculate it.</p>\n<pre><code>warning: you don't need to add `&` to both the expression and the patterns\n --> src\\main.rs:64:9\n |\n64 | / match &&keyword[..] {\n65 | | &"EXIT" => return,\n66 | | &"HELP" => help(),\n67 | | &"ADD" => add(&mut query, &mut company),\n... |\n71 | | _ => (),\n72 | | }\n | |_________^\n |\n = note: `#[warn(clippy::match_ref_pats)]` on by default\n = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#match_ref_pats\nhelp: try\n |\n64 | match &keyword[..] {\n65 | "EXIT" => return,\n66 | "HELP" => help(),\n67 | "ADD" => add(&mut query, &mut company),\n68 | "LIST" => list(&mut query, &mut company),\n69 | "UPDATE" => update(&mut query, &mut company),\n ...\n</code></pre>\n<p>Self explanatory.</p>\n<pre><code>warning: use of `or_insert` followed by a function call\n --> src\\main.rs:98:37\n |\n98 | company.entry(dept).or_insert(Vec::new());\n | ^^^^^^^^^^^^^^^^^^^^^ help: try this: `or_insert_with(Vec::new)`\n |\n = note: `#[warn(clippy::or_fun_call)]` on by default\n = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#or_fun_call\n</code></pre>\n<p><code>.or_insert(Vec::new())</code> always constructs the vector; if the entry\nalready exists, the newly constructed empty vector is discarded. A\nbetter alternative is <code>.or_default(Vec::new)</code>. (It probably doesn't\nmake a big difference in this case though.)</p>\n<h1>Structuring data</h1>\n<p>In Chapter 5 <a href=\"https://doc.rust-lang.org/stable/book/ch05-00-structs.html\" rel=\"nofollow noreferrer\">Using Structs to Structure Related Data</a>, we learned\nto use structs and methods to organize our data. We can define some\n<code>struct</code>s to clarify the meaning of our data:</p>\n<pre><code>#[derive(Clone, Debug)]\nstruct Department {\n employees: Vec<String>,\n}\n\n#[derive(Clone, Debug)]\nstruct Company {\n departments: HashMap<String, Department>,\n}\n</code></pre>\n<p>And we can build the preset data in an associated function:</p>\n<pre><code>impl Company {\n fn preset() -> Self {\n let departments = &[\n ("SALES", &["Sally", "Jordan", "Charlie", "Abigail"]),\n ("ENGINEERING", &["Suzy", "Jay", "Chi", "Amy"]),\n ("HR", &["Son", "Jack", "Chia", "Anna"]),\n ("SANITATION", &["August", "Entangle", "Will", "Jada"]),\n ];\n\n Company {\n departments: departments\n .iter()\n .map(|&(name, department)| {\n (\n name.to_string(),\n Department {\n employees: department.iter().map(|&s| s.to_string()).collect(),\n },\n )\n })\n .collect(),\n }\n }\n}\n</code></pre>\n<p>(Personally, I would prefer using serialization instead of hardcoding\nthe preset data.)</p>\n<h1>Unnecessary allocation</h1>\n<p>In <code>main</code>, there is an unnecessary allocation:</p>\n<pre><code>query = query.trim().to_string();\n</code></pre>\n<p>You can simply make a reference into the original input:</p>\n<pre><code>let query = query.trim();\n</code></pre>\n<p>Note that <a href=\"https://doc.rust-lang.org/stable/book/ch03-01-variables-and-mutability.html#shadowing\" rel=\"nofollow noreferrer\">shadowing</a> is used here to maintain the variable that\nowns the original string.</p>\n<h1>Input parsing</h1>\n<p>You first check for empty input, and then use <code>.next().unwrap()</code>.\nJust use a <code>match</code>:</p>\n<pre><code>let query = query.trim();\nlet mut args = query.split_whitespace();\n\nmatch args.next() {\n None => println!("Empty input. Type HELP for a keyword reference."),\n Some("ADD") => execute::add(args.collect(), &mut company),\n Some("EXIT") => return,\n Some("HELP") => help(),\n Some("LIST") => execute::list(args.collect(), &mut company),\n Some("REMOVE") => execute::remove(args.collect(), &mut company),\n Some("UPDATE") => execute::update(args.collect(), &mut company),\n Some(_) => println!("Invalid Keyword. Type HELP for a keyword reference."),\n}\n</code></pre>\n<p>I put all the helper functions in a <code>execute</code> module. I also changed\nthe parsing functions to take <code>args</code> by value. The keyword is\nexcluded from the list of arguments.</p>\n<h1><code>add</code></h1>\n<p>Checking if a department exists can be done with the entry API:</p>\n<pre><code>let department = department.to_uppercase();\nmatch departments.entry(&department) {\n Entry::Occupied(_) => println!("Department {} already exists.", d),\n Entry::Vacant(entry) => {\n entry.insert(Department::new());\n println!("Created department {}.", d);\n }\n}\n</code></pre>\n<p>In fact, the whole function can be simplified with pattern matching:</p>\n<pre><code>pub fn add(args: &[&str], company: &mut Company) {\n let departments = &mut company.departments;\n\n match *args {\n ["-D", department] => {\n use std::collections::hash_map::Entry;\n\n let department = department.to_uppercase();\n\n match departments.entry(department) {\n Entry::Occupied(entry) => {\n println!("Department {} already exists.", entry.key())\n }\n Entry::Vacant(entry) => {\n println!("Created department {}.", entry.key());\n entry.insert(Department::new());\n }\n }\n }\n [name, "TO", department] => {\n let department = department.to_uppercase();\n\n let employees = match departments.get_mut(&department) {\n None => {\n println!("Department {} does not exist.", department);\n return;\n }\n Some(department) => &mut department.employees,\n };\n\n if employees.iter().any(|employee| employee == name) {\n println!("The name {} already exists in {}.", name, department);\n } else {\n employees.push(name.to_string());\n println!("Added {} to {}.", name, department);\n }\n }\n _ => println!("Invalid syntax."),\n }\n}\n</code></pre>\n<p>Other functions can be simplified in a similar fashion.</p>\n<h1><code>continue</code></h1>\n<p>Similar to the implicit <code>return</code>, you do not need to explicitly\ncontinue to the next iteration of the loop at the end of the loop\nbody.</p>\n<h1><code>help</code></h1>\n<p>The <a href=\"https://docs.rs/indoc/1.0/indoc/\" rel=\"nofollow noreferrer\"><code>indoc</code></a> crate provides a nice way to write multiline string\nliterals:</p>\n<pre><code>pub fn help() {\n println!(indoc! { r#"\n <fill in text here>\n "#})\n}\n</code></pre>\n<p>The indentation common to every line will be stripped, and the rest of\nthe indentation will be preserved.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-08T16:13:15.213",
"Id": "484869",
"Score": "0",
"body": "This is detailed and helpful, thanks a lot. Using the indoc crate especially is one tip I hadn't even considered."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-08T04:00:47.850",
"Id": "247642",
"ParentId": "247588",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "247642",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-06T20:25:52.903",
"Id": "247588",
"Score": "7",
"Tags": [
"beginner",
"rust"
],
"Title": "Rust Book's Chapter 8 - Text Interface"
}
|
247588
|
<pre><code>@Effect()
createQuiz$: Observable<Action> = this.actions$.pipe(
ofType<quizAction.CreateQuiz>(quizAction.CREATE_QUIZ),
switchMap((action) => {
return this.quizService.createQuiz(action.payload)
.pipe(
map(() => {
return new quizAction.CreateQuizCompleted()
}),
catchError(error => {
console.log(error);
return of(new quizAction.CreateQuizCompleted());
})
);
})
);
export class QuizComponent implements OnInit {
constructor(
private quizService: QuizService,
private store:Store<{app: fromApp.State}>,
) { }
ngOnInit(): void {
}
trackByIdx = (index: number): number => index;
onCreate(): void {
this.store.select(fromApp.selectUserId).pipe(
take(1)
).subscribe(userId => this.handleCreate(userId));
}
handleCreate(userId: string): void {
let value = this.quizService.createDefaultQuiz();
if (this.quizService.hasPermission(userId) && this.quizService.validateQuiz(value)) {
this.store.dispatch(new quizAction.CreateQuiz(value));
}
}
}
</code></pre>
<p>I am wondering if there's any memory leak that can occur or any non-idiomatic patterns that I am using without knowing. Does everything look fine?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T01:12:38.053",
"Id": "247595",
"Score": "2",
"Tags": [
"javascript",
"angular-2+"
],
"Title": "Ngrx effects in angular application"
}
|
247595
|
<p>This is my first time requesting a code review. This is code I wrote in Python to create a DNA sequence analyzer. This is for the Harvard CS50 course.</p>
<p>I was really hoping to get some constructive criticism on this code I finished for the DNA problem in Problem Set 6. This code passed all tests and is fully functional as far as I am aware.</p>
<p>I was mainly wondering if there were any more succinct ways to rewrite parts of it. I spent several hours writing this and my brain is pretty exhausted, so near the end I just went for whatever worked.</p>
<p>Any input is appreciated! (Also, sorry if this is an excessive amount of comments, but they help me keep everything clear in my head.)</p>
<pre><code>import re
import csv
from sys import argv
# Checks for correct number of command-line arguments
if not len(argv) == 3:
print("Incorrect number of command-line arguments.")
exit(1)
# Declares a dictionary containing STR counts
str_counts = {
"AGATC": "0",
"TTTTTTCT": "0",
"AATG": "0",
"TCTAG": "0",
"GATA": "0",
"TATC": "0",
"GAAA": "0",
"TCTG": "0"
}
# Opens the csv and txt files to read (and closes them later)
with open(argv[1], "r", newline="") as csv_file, open(argv[2], "r") as sequence:
# Reads the database into a dict and the sequence into a string
db = csv.DictReader(csv_file)
sq = sequence.read()
# Stores the fieldname of the dictionary and stores the keys in STRS, skipping first line
keys = db.fieldnames
key_len = len(keys)
# Skips first row of headers
STRs = keys[1:key_len]
# Bool to signal if match was found
matched = False
# Checks for STR matches and length of those matches, then stores those values in str_counts
for STR in STRs:
# Executes following code only if there are 1 or more matches
if re.search(rf"(?:{STR}+)", sq):
# Creates a list of matches
matches = re.findall(rf"(?:{STR})+", sq)
# Finds the longest match
longest = max(matches, key = len)
# Stores that value in corresponding dict key
str_counts[STR] = len(longest) / len(STR)
# Compares str_counts values to database to find match
# Compares the match count values to the database values
for row in db:
# Declares a counter to later check if all STR values are matched
# Resets counter to zero every iteration
match_count = 0
# Declares a temporary dictionary with only int match values to compare STR counts to
compare = {}
# Stores the names field for use later
match_name = row['name']
# Deletes the names field so we only have ints in our compare dict
del row['name']
# Converts values to integers for easy comparison
for key, value in row.items():
compare[key] = int(value)
# Increments match count
for STR in STRs:
if compare[STR] == str_counts[STR]:
match_count += 1
# If all fields are matched, print match name, switch bool to true
if match_count == len(STRs):
matched = True
print(match_name)
if not matched:
print("No Match")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T03:14:21.380",
"Id": "484707",
"Score": "3",
"body": "Do you have any link to the problem description? because a DNA sequence analysis may have various purposes. Apart from that, there are some minor possible modifications but they would make the code quite compact such as replacing initialized and called variables with the initializer value. e.g `matches = re.findall(rf\"(?:{STR})+\", sq) | longest = max(matches, key = len)` => `longest = max(re.findall(rf\"(?:{STR})+\", sq), key = len)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T04:31:36.823",
"Id": "484708",
"Score": "1",
"body": "Is counting all it has to do? We can shorten it quite a bit using I built-in tools then. Please post the description of the assignment/challenge."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T06:11:08.940",
"Id": "484716",
"Score": "3",
"body": "Probably this is the [link](https://cs50.harvard.edu/x/2020/psets/6/dna/) to the problem description."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T17:11:42.883",
"Id": "484779",
"Score": "0",
"body": "dariosicily has the correct link!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T17:42:37.837",
"Id": "484786",
"Score": "1",
"body": "@MiguelAvila thank you for the tip! I changed that in my code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T18:50:31.080",
"Id": "484797",
"Score": "2",
"body": "Hey, on Code Review it's site policy to leave the code in the question as is once you have gotten an answer. This rule helps prevent some very messy situations. As such I have rolled back your latest edit; I hope you can be understanding in this. You may be interested in [our guidance](//codereview.meta.stackexchange.com/a/1765) on how best to follow up from getting an answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T18:55:24.157",
"Id": "484801",
"Score": "1",
"body": "@Peilonrayz Sorry about that! Thank you for letting me know!"
}
] |
[
{
"body": "<p>I would group the code in functions and call them from a central <code>main</code>. With how you have it now, simply loading the file into an interactive console will cause all the code to run, which, if the code is long running or causes side-effects, may be less than ideal. Say I wrote a port-scanner, and it takes 2-3 minutes to run. I may not want it to start simply because I loaded the file into a REPL in Pycharm. Not only would that waste a few minutes each time, port-scanning can get you in trouble if done on a network that you don't have permission to scan.</p>\n<p>Code wrapped in functions is simply easier to control the execution of, because it will only run when the function is called.</p>\n<p>Grouping code into functions also allows you to easily test each chunk in isolation from the rest of the code. It's difficult to test code when you're dependent on the first half of the code to supply test data to the latter-half. It's much easier however to simply load the script into a REPL, and throw test data at the function (or use proper unit-tests). Then you can test one piece of code in isolation without touching the rest of the code.</p>\n<hr />\n<p>I personally believe that <code>STRs</code> and <code>STR</code> should be lower-case. <a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"nofollow noreferrer\">According to PEP8</a>, Python's style and convention guide, regular variables should be lower case, with words separated by underscores. Variables that are considered to be constants however should be upper-case, separated by underscores.</p>\n<p>Local variables that remain unchanged have never clicked as "constants" in my head, so it depends on what you decide.</p>\n<p>Regardless though, <code>STRs</code> should either be all upper-case, or all lower-case; in which case the <code>STR</code> counterpart will need to be renamed so it doesn't clash with the <code>str</code> built-in. A name like <code>str_</code> could be used, or you could use a more descriptive name.</p>\n<hr />\n<pre><code>compare = {}\n\n. . .\n\nfor key, value in row.items():\n compare[key] = int(value)\n</code></pre>\n<p>This can make use of a dictionary comprehension. Whenever you have the pattern of creating a set/list/dictionary before a loop, then populating the structure within the loop, you should consider a comprehension:</p>\n<pre><code>compare = {key: int(value) for key, value in row.items()}\n</code></pre>\n<hr />\n<p>Similarly, to ensure that a condition holds for an entire collection (or two in this case), you can combine <a href=\"https://docs.python.org/3/library/functions.html#all\" rel=\"nofollow noreferrer\"><code>all</code></a> with a generator expression (the part passed to <code>all</code>):</p>\n<pre><code>if all(compare[STR] == str_counts[STR] for STR in STRs):\n matched = True\n print(match_name)\n</code></pre>\n<p>"If all corresponding values in the two dictionaries match, set the matched flag". It reads quite nicely.</p>\n<p>That gets rid of the need for <code>match_count</code>, and the second last loop.</p>\n<hr />\n<p>You're looping more than you need to. You appear to only care about if at least one match is found; yet you keep looping even after one is.</p>\n<p>I'd break once one is found. If you combine that with <a href=\"https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops\" rel=\"nofollow noreferrer\"><code>for's</code> <code>else</code> clause</a>, you can prevent unnecessary looping and still detect failure:</p>\n<pre><code>for row in db:\n . . .\n if all(compare[STR] == str_counts[STR] for STR in STRs):\n print(match_name)\n break\n\nelse:\n print("No Match")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T17:11:14.603",
"Id": "484778",
"Score": "0",
"body": "_With how you have it now, simply loading the file into an interactive console will cause all the code to run, which makes working with a REPL more difficult._ So what about running python script from console with `-i` flag to keep it interactive?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T17:14:15.850",
"Id": "484781",
"Score": "1",
"body": "@KonstantinKostanzhoglo I commonly use that and _having no functions is hard to work with_."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T17:37:27.373",
"Id": "484783",
"Score": "0",
"body": "@carcigenicate You are right, I just wanted to mention the possibility of being able to access the result of the computation interactively when the program finished its execution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T17:38:47.940",
"Id": "484784",
"Score": "0",
"body": "@Carcigenicate thank you for the feedback! Splitting everything into functions may be slightly difficult since my variables are so interwoven, but I'll try to figure it out. Changed 'STR' and 'STRs' to better lowercase variables. Thank you for the dict comprehension and all() tips! I hadn't run across those in Python syntax yet and implemented them immediately (I was looking for solutions like those). Your last suggestion didn't seem to work in my code (it prints 'No Match' even if a match is found), but I'll keep looking into it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T17:43:00.687",
"Id": "484787",
"Score": "2",
"body": "@Star No problem. And yes, when code is initially formatted to use globals, it can take some work to get everything arranged into functions. Ideally, every function should take as arguments the data it needs, and should `return` the results of whatever computations it does (ideally). That can make reasoning about code easier, and makes testing much easier, but ya, it takes some work to get there. For the last issue, make sure the `else` is properly indented at the same level as the `for`. Because `else` is valid for a few constructs, it's easy to \"attach\" it to the wrong statement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T18:47:27.287",
"Id": "484795",
"Score": "0",
"body": "@Carcigenicate I split everything into functions and put the refactored code into my original post. If you have time to look through again and give me your thoughts, I would greatly appreciate it, but no worries if not - you've helped me plenty already."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T18:51:30.337",
"Id": "484798",
"Score": "1",
"body": "@Star Please do not update code in questions. If anyone is in the process of writing a review, a change to the code may invalidate what they have, and we certainly don't want to discourage any other suggestions. It's completely appropriate to post a second question with updated code if you want a review of the new code. If you post a new question, I may have time later to look it over."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T14:36:43.493",
"Id": "247608",
"ParentId": "247596",
"Score": "6"
}
},
{
"body": "<p>I'll start off by saying, Hey! Good job! There's a lot of things you got right in this code, including the use of <code>with</code> for file open/close operations and checking the number of command line arguments.</p>\n<p>Now I'll rip it to shreds. :|</p>\n<ol>\n<li><p>First, check out <a href=\"https://pep8.org/\" rel=\"nofollow noreferrer\">PEP-8</a>, the Python community coding standard.</p>\n<p>You may find things in there you disagree with, but it's a pretty good starting point. (And if you don't match it, everyone on here will nag you for it, so ...)</p>\n</li>\n<li><p>Don't import <code>sys.argv</code>.</p>\n<p>This is a small thing, but other coders expect to see it spelled out. You can create a local variable that references it, if you're going to do a lot of operations. But for your purposes, it's actually more clear to write:</p>\n<pre><code> if len(sys.argv) != 3:\n</code></pre>\n</li>\n<li><p>Don't declare your <code>str_counts</code> dictionary globally.</p>\n<p>Global variables are bad, m'kay? Also, there's no need for this, which I will get to later.</p>\n</li>\n<li><p>Don't initialize your <code>str_counts</code> dictionary with data.</p>\n<p>I know why you did this, but you had to read the CSV file to get the keys so you could set this up in advance, right? And there's a couple of ways to do this all-at-once, which I will get to later. So just delete this entire global variable.</p>\n</li>\n<li><p>Don't let your <code>with</code> blocks get too long.</p>\n<p>You have two items in your context. But you only actually need one at a time. So rewrite that code to do the minimum you have to do with each thing:</p>\n<pre><code>with open(sys.argv[2]) as f:\n sequence = f.read()\n\nwith open(sys.argv[1], newline='') as f:\n db = csv.DictReader(f)\n assert 'name' in db.fieldnames\n</code></pre>\n</li>\n<li><p>Initialize your counts dictionary on the fly. Or not.</p>\n<p>Once you know the field names, which it turns out are also the STR sequences, you could create an initialized dictionary on the fly.</p>\n<pre><code>str_counts = {}\nfor str in db.fieldnames:\n if str != 'name':\n str_counts[str] = 0\n</code></pre>\n<p>This approach uses a <em>dict comprehension</em> to do the same thing:</p>\n<pre><code>str_counts = {str: 0 for str in db.fieldnames if str != 'name'}\n</code></pre>\n<p>It turns out that this is a common need. People frequently need a dictionary initialized with default values. (Gene Rayburn: This thing is <em>sooo commmmonnnn!</em> Audience: How common is it?)</p>\n<p>It's so common that Python has a special type in the standard library just for this case! Presenting: <a href=\"https://docs.python.org/3/library/collections.html?highlight=collections%20defaultdict#collections.defaultdict\" rel=\"nofollow noreferrer\"><code>collections.defaultdict</code></a></p>\n<p>A <code>defaultdict</code> is a dictionary that knows how to construct a "default value". Because you tell it how! All you need to do is create the dict with a "callable" (a function, lambda, classname, etc.) and it will either look up the key you give it and return the value, or not find the key you give it, call the callable, and return that instead.</p>\n<p>For your purposes, the default value is <code>int</code>, a function which creates a default integer if you call it. And default integers start with a value of 0, so ... <code>#winning!</code></p>\n<pre><code># at top of file\nimport collections\n\n# ...\n# later in code:\nstr_counts = collections.defaultdict(int)\n</code></pre>\n</li>\n<li><p>Don't guard a regex operation with a regex operation of similar complexity.</p>\n<p>You have a <code>re.findall</code> that is guarded by a <code>re.search</code>. With basically the same pattern, and the same search string, and no other help.</p>\n<p>You could be doing this to save time, but that's a non-starter since <code>search</code> and <code>findall</code> would have the same execution time if the STR does not appear in the sequence.</p>\n<p>You could be doing this to avoid some other operation. But you're not. And it's pretty trivial to write your code in such a way that the "found" path and the "not found" path both produce the same results. Do that instead.</p>\n<p>(Note: there are plenty of times when you <em>do</em> want to put a guard of some kind on an operation. This just isn't one of those times.)</p>\n<p>If <code>max</code> returns 0, and you compute <code>0 / len(field)</code>, you'll be storing 0, which is fine.</p>\n</li>\n<li><p>Don't delete the names from your database.</p>\n<p>Your comparison starts by deleting the <code>'name'</code> fields and then using a dict comprehension to copy the other fields to a new dict. Instead of doing that, just use <code>if</code> to exclude the name fields:</p>\n<pre><code>compare = {k: int(v) for k, v in row.items() if k != 'name'}\n</code></pre>\n</li>\n<li><p>Note that dictionaries can be compared for equality using the <code>==</code> operator:</p>\n<pre><code>if compare == str_counts:\n</code></pre>\n</li>\n<li><p>A great way to document your code, for problems like these, it to create a "header comment" at the top of the file using Python's triple-quote string mechanism (""" string """) and copy the problem text into it. That gives you something to refer to, and makes the program file entirely self-contained.</p>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-08T20:22:25.323",
"Id": "484873",
"Score": "0",
"body": "Thank you for the feedback! `sys.argv` doesn't appear to work in the CS50 IDE I'm using, but I'll keep that in mind for projects outside of CS50. Am I correct in thinking that if I separate the `with` statements, I should nest them so that both files stay open while I'm using them? Also, on point 7, when I try to remove the outer `re.search()` I get an error saying `max()` arg is an empty sequence. Again, maybe this is just an issue with the IDE I'm using, I'm not sure. Still looking through the rest of your suggestions, but wanted to touch on these few things first."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-08T20:34:49.370",
"Id": "484875",
"Score": "0",
"body": "I was able to implement the rest of your suggestions without error, yay! I decided to use dictionary comprehension to initialize my dictionary \"on the fly\". I also deleted the lines of code that deleted the `'name'` fields and instead added an `if` statement as you suggested. Code is still passing all tests and I appreciate being able to make it shorter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-09T04:17:52.383",
"Id": "484887",
"Score": "1",
"body": "Great news. Remember to use `sys.argv` you have to `import sys` at the top. You should not need to nest the `with` statements because all you do with the text file is slurp it into the `sequence` variable. Just `with` it, `.read()` it, and let it die. I don't know why the `max` arg is an empty sequence. If it works inside the `if re.search` it should work stand-alone. You'll have to debug that. I don't think there's very many things special about the CS50 environment (which, by the way, thank you for asking this question because I never knew about that project at all -- so freaking cool!)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T20:28:53.320",
"Id": "247630",
"ParentId": "247596",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "247608",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T02:41:08.580",
"Id": "247596",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"regex",
"formatting",
"hash-map"
],
"Title": "Can it be shorter?: DNA Sequence Analyzer from CS50 written in Python"
}
|
247596
|
<p>I've made a simple food inventory manager in Python3<br />
Please tell me what can be improved<br />
<a href="https://github.com/KhushrajRathod/FoodInventory-Manager" rel="nofollow noreferrer">GitHub</a></p>
<pre><code>import os
import pickle
import time
remaining_ingredients = {}
dishes = []
class Dish:
name = ""
required_ingredients = {}
def __init__(self, name: str, required_ingredients: dict):
self.required_ingredients = required_ingredients
self.name = name
def add_ingredient(self, name, amount):
self.required_ingredients[name] = amount
def remove_ingredient(self, to_delete):
del self.required_ingredients[to_delete]
def cook_dish(self):
global remaining_ingredients
remaining_ingredients_backup = remaining_ingredients.copy()
for name, amount in self.required_ingredients.items():
if remaining_ingredients[name] >= amount:
remaining_ingredients[name] -= amount
else:
print(f"Dish requires more of ingredient {name}.\nYou currently have - {remaining_ingredients[name]}\n"
f"Required - {amount}\nTry again.")
remaining_ingredients = remaining_ingredients_backup
time.sleep(1)
return
print("Successfully removed ingredients required by the dish from inventory")
time.sleep(1)
return
# Save and load functions for remaining ingredients and dishes
def save_obj(obj, name):
current_directory_is = os.getcwd()
final_directory_is = os.path.join(current_directory_is, r'FoodMonitor')
if not os.path.exists(final_directory_is):
os.makedirs(final_directory_is)
with open('FoodMonitor/' + name + '.pkl', 'wb') as f:
pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)
def load_obj(name):
with open('FoodMonitor/' + name + '.pkl', 'rb') as f:
return pickle.load(f)
# Standard multi choice question template
def multi_choice_question(options: list):
while True:
print("Enter the number of your choice -",
*(f"{number}. {option}" for number, option in enumerate(options, 1)),
sep='\n', end='\n\n')
'''
The same as -
print("\nEnter the number of your choice - ")
for i, option in enumerate(options, 1):
print('{0}. {1}'.format(i, option))
print("\n"")
'''
try:
answer = int(input())
if 1 <= answer <= len(options):
return answer
print("That option does not exist! Try again!")
except ValueError:
print("Doesn't seem like a number! Try again!")
# For getting an int from the user'
def get_int():
while True:
try:
return int(input())
except ValueError:
print("Doesn't seem like a number! Try again!")
''' UI methods - For direct interaction with the user'''
def buy_ingredients():
if len(remaining_ingredients) != 0:
print("Which ingredient did you buy?\n")
multi_choice_params = []
for name, amount in remaining_ingredients.items():
multi_choice_params.append(name)
ingredient_name = multi_choice_params[multi_choice_question(multi_choice_params) - 1]
print("How much did you buy?")
ingredient_amount = get_int()
remaining_ingredients[ingredient_name] += ingredient_amount
print("Successfully updated ingredient library")
else:
print("No ingredients yet! Use option 4 to add new ingredients.")
time.sleep(1)
def cook_dish():
if len(dishes) != 0:
print("Which dish would you like to cook?")
dish_names = []
for dish in dishes:
dish_names.append(dish.name)
answer = multi_choice_question(dish_names)
Dish.cook_dish(dishes[answer - 1])
else:
print("No dishes yet! Use option 3 to create new dish templates")
def edit_dish():
def new_dish():
if len(remaining_ingredients) != 0:
while True:
name_of_dish = input("What will the name of the dish be?").lower().strip()
if name_of_dish not in dishes:
break
print("That dish already exists! Try again!")
print("How many ingredients will the dish contain?")
amount = get_int()
list_of_ingredients = {}
# get ingredients
print("Enter all your ingredients:")
for x in range(amount):
# check if ingredient exists
while True:
s = input(f"No. {x + 1}. -----> ").lower().strip()
if s in remaining_ingredients:
name_of_ingredient = s
break
else:
print("That ingredient doesn't exist! Try again!")
print("How much of that ingredient will the dish use?")
amount = get_int()
list_of_ingredients[name_of_ingredient] = amount
dishes.append(Dish(name_of_dish, list_of_ingredients))
else:
print("No ingredients yet! Use option 4 to add new ingredients for use in this dish.")
def remove_dish():
if len(dishes) != 0:
print("Which dish would you like to delete?")
dish_names = []
for dish in dishes:
dish_names.append(dish.name)
to_delete = multi_choice_question(dish_names) - 1
to_delete_name = dishes[to_delete].name
del dishes[to_delete]
print(f"Successfully deleted dish {to_delete_name}")
else:
print("No dishes yet! Use option 3 to add new ingredients.")
def modify_dish():
global dishes
if len(dishes) != 0:
print("Which dish would you like to modify?")
dish_names = []
for dish in dishes:
dish_names.append(dish.name)
to_modify = multi_choice_question(dish_names)
print(f"What would you like to modify about this dish?")
thing_to_modify = multi_choice_question(
["Name", "Required ingredients", "Quantity of required ingredient(s)"])
if thing_to_modify == 1:
dishes[to_modify - 1].name = input("Enter new name: ").lower().strip()
print("Successfully changed name!")
elif thing_to_modify == 2:
answer = multi_choice_question(["Add a new ingredient", "Remove an existing ingredient"])
if answer == 1:
print("Which ingredient would you like to add to this dish?")
remaining_ingredient_names = list(remaining_ingredients.keys())
required_ingredients = list(dishes[to_modify - 1].required_ingredients.keys())
ingredients_not_used_in_dish = list(set(remaining_ingredient_names) - set(required_ingredients))
if len(ingredients_not_used_in_dish) != 0:
to_add = multi_choice_question(ingredients_not_used_in_dish)
print("How much of that ingredient will the dish require?")
amount_required = get_int()
dishes[to_modify - 1].add_ingredient(ingredients_not_used_in_dish[to_add - 1], amount_required)
print(f"Successfully added {ingredients_not_used_in_dish[to_add - 1]} "
f"to {dishes[to_modify - 1].name}")
else:
print("All ingredients in inventory are already used in dish")
else:
print("Which ingredient would you like to remove from this dish?")
required_ingredient_names = list(dishes[to_modify - 1].required_ingredients.keys())
to_remove = multi_choice_question(required_ingredient_names)
dishes[to_modify - 1].remove_ingredient(required_ingredient_names[to_remove - 1])
print(f"Successfully removed {required_ingredient_names[to_remove - 1]} from "
f"{dishes[to_modify - 1].name}")
else:
print("Which ingredient's quantity would you like to change?")
required_ingredient_names = list(dishes[to_modify - 1].required_ingredients.keys())
to_change = multi_choice_question(required_ingredient_names)
print("Enter the new quantity for the ingredient")
quantity = get_int()
dishes[to_modify - 1].required_ingredients[required_ingredient_names[to_change - 1]] = quantity
print(
f"Successfully changed amount of {required_ingredient_names[to_change - 1]} required "
f"in {dishes[to_modify - 1].name} to {quantity}")
else:
print("No ingredients yet! Use option 3 to add new ingredients.")
to_do = multi_choice_question(["Add a new dish",
"Delete an existing dish",
"Edit an existing dish",
])
if to_do == 1:
new_dish()
elif to_do == 2:
remove_dish()
else:
modify_dish()
time.sleep(1)
def edit_ingredients():
def new_ingredient():
while True:
name = input("What will the name of the new ingredient be?").lower().strip()
if name in remaining_ingredients:
print("Ingredient already exists! Try again!")
continue
break
print("How much of this ingredient do you currently have?")
amount = get_int()
remaining_ingredients[name] = amount
print(f"Successfully added {name}")
def remove_ingredient():
if len(remaining_ingredients) != 0:
print("Which ingredient do you want to delete?")
to_remove = multi_choice_question(list(remaining_ingredients.keys()))
removed = list(remaining_ingredients.keys())[to_remove - 1]
del remaining_ingredients[removed]
print(f"Successfully deleted {removed}")
else:
print("No ingredients yet! Use option 4 to add new ingredients.")
def edit_ingredient_quantity():
if len(remaining_ingredients) != 0:
print("Which ingredient's amount do you want to change?")
to_change = multi_choice_question(list(remaining_ingredients.keys()))
print("What will the new amount of the ingredient?")
new_value = get_int()
remaining_ingredients[list(remaining_ingredients.keys())[to_change - 1]] = new_value
print(f"Success! {list(remaining_ingredients.keys())[to_change - 1]} now has value {new_value}")
else:
print("No ingredients yet! Use option 4 to add new ingredients.")
to_do = multi_choice_question(
["Add a new ingredient", "Remove an existing ingredient", "Edit the amount of an existing ingredient"])
if to_do == 1:
new_ingredient()
elif to_do == 2:
remove_ingredient()
else:
edit_ingredient_quantity()
time.sleep(1)
def get_ingredients():
print("Current Ingredient Inventory:\n")
if len(remaining_ingredients) == 0:
print("No ingredients yet!\n")
else:
for name, amount in remaining_ingredients.items():
print(f"{name} : {amount}")
time.sleep(1)
def get_dishes():
print("Current Dishes:\n")
if len(dishes) == 0:
print("No dishes yet!\n")
for x in dishes:
print(f"{x.name}, containing ", end="")
print(str(x.required_ingredients)[1:-1])
time.sleep(1)
current_directory = os.getcwd()
final_directory = os.path.join(current_directory, r'FoodMonitor')
if os.path.exists(final_directory):
remaining_ingredients = load_obj("I")
dishes = load_obj("D")
while True:
choice = multi_choice_question(
["If you bought ingredients, choose option 1. ", "If you cooked a dish choose option 2. ",
"To add a new dish or edit/delete an existing one, choose option 3. ",
"To add a new ingredient or edit/delete an existing one, choose option 4. ",
"To view current ingredient inventory, choose option 5",
"To view current dishes, choose option 6",
"To save inventory and quit the application, choose option 7. "])
if choice == 1:
buy_ingredients()
if choice == 2:
cook_dish()
if choice == 3:
edit_dish()
if choice == 4:
edit_ingredients()
if choice == 5:
get_ingredients()
if choice == 6:
get_dishes()
if choice == 7:
print("See you next time...")
save_obj(remaining_ingredients, "I")
save_obj(dishes, "D")
exit(0)
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T04:15:28.587",
"Id": "495321",
"Score": "0",
"body": "Meaning no offense, why did you pick this project? This is something I've seen dozens of people write, and zero people ever use."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T05:14:55.353",
"Id": "495506",
"Score": "0",
"body": "¯\\\\_(ツ)_/¯ - Idk, I didn't realise that dozens of people have written this -- I was under the impression that I was the first one to think of this :)"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T05:59:07.013",
"Id": "247597",
"Score": "1",
"Tags": [
"python",
"python-3.x"
],
"Title": "Simple food inventory manager in Python3"
}
|
247597
|
<p>I'd like to know how to improve this code because I think that the <code>main_func</code> is too big and I can not split it into other functions or classes.</p>
<p>Also, I want to know if I can or should use <strong>classes</strong> to make it cleaner.</p>
<pre><code>import random
import string
def starting():
print('HANGMAN')
print('Set game mode:')
print('0. To exit')
print('1. Easy')
print('2. Medium')
print('3. Hard')
difficult = int(input('Your choice: '))
if difficult == 1:
difficult_easy()
elif difficult == 2:
difficult_medium()
elif difficult == 3:
difficult_hard()
else:
exit('Exiting...')
def main_func(word_lst, guesses_given):
secret_word = random.choice(word_lst)
output = []
guessed_letters = []
alphabet = string.ascii_letters
length = len(secret_word)
print(f'Your word has {len(secret_word)} characters ')
for i in range(len(secret_word)):
output.append('_')
while '_' in output:
letter = input('Enter a letter: ')
if letter not in alphabet:
print('You should enter only one letter!\n ')
elif len(letter) != 1:
print('You can only display 1 letter at a time\n')
else:
if letter not in guessed_letters:
guessed_letters.append(letter)
if letter in secret_word:
for n in range(length):
if secret_word[n] == letter:
output[n] = letter.upper()
print(*output, sep=' ')
if '_' not in output:
print('You won!')
if letter not in secret_word:
guesses_given -= 1
print(f"This letter is not in the secret word. REMAINING TRIES: {guesses_given}\n")
if guesses_given == 0:
print(f"You lost. The secret word was '{secret_word.upper()}'")
break
else:
print('You have already guessed this letter!\n\n')
print('GAMEOVER')
play_again()
def play_again():
again = input('Play again? (y/n)\n')
if again.lower() == 'yes' or again.lower() == 'y':
starting()
else:
exit('Exiting...')
def difficult_easy():
main_func(['hall', 'exam', 'road', 'gate', 'debt', 'poet', 'sir', 'girl', 'food'], 14)
def difficult_medium():
main_func(['customer', 'baseball', 'language', 'stranger', 'quantity',
'judgment', 'republic', 'proposal', 'magazine'], 12)
def difficult_hard():
main_func(['assumption', 'impression', 'restaurant', 'indication', 'excitement',
'depression', 'government', 'inspection', 'protection', 'investment'], 10)
if __name__ == '__main__':
starting()
</code></pre>
<p>For me, it looks garbage, but I did my best to make it simple and short at the same time. I want to use classes to make it more simple, but I still hadn't figured out... The last thing I want to ask is about the <code>if __name__ == '__main__':</code>, am I using it correctly?</p>
<p>I posted it on Stack Overflow but people said that the site is only for specific problems in your code, so they told me to go here.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T10:43:17.290",
"Id": "484738",
"Score": "1",
"body": "_\"that the site is only for specific problems in your code, so they told me to go here\"_ Well, this site here is about improvement of code all implemented, and working as intended (to the authors best knowledge). So if you confirm that your code does everything as intended, you're right here. Bur if you're asking whether you do `if __name__ == '__main__':` correctly, I have some doubts."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T10:46:38.027",
"Id": "484740",
"Score": "2",
"body": "The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T16:58:55.810",
"Id": "484769",
"Score": "0",
"body": "Yeah, i'm beggining to code, so this is all new for me, thanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T19:57:53.847",
"Id": "484810",
"Score": "2",
"body": "Some years back I wrote [a sample Hangman Game](https://gist.github.com/bjmc/284a731c01470a628b2f424bbb41bf22) for a Python programming class I was teaching. You could read it for inspiration. It's not really that different from yours, conceptually."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T21:54:05.633",
"Id": "484820",
"Score": "0",
"body": "sure, actually really similar, but i found yours more organized @bjmc"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T22:09:08.557",
"Id": "484821",
"Score": "0",
"body": "\" I can not split it into other functions or classes.\" Do you mean that you don't know how to split it, or you can't as in \"aren't allowed to\" (for whatever reason, homework rules, or something)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T23:35:42.687",
"Id": "484829",
"Score": "0",
"body": "I like to use classes bc I think that it makes the code a pleasure to read, it's like the top level organization, and I can't use them here because I don't know how. I tried for like 1 hour or so to put them in but it just became more complicated and messy. Also, I didn't know if they were actually gonna improve it, I mean, isn't it too small? I saw many tutorials on YT to use Classes but them all are too simple like `class Robot(): def sayHi():`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-08T08:41:51.347",
"Id": "484851",
"Score": "0",
"body": "@filip augusto Watch out though because mine was written for Python 2 - you might already know this but Python 2 has been retired now and anyone learning Python in 2020 should focus on Python 3."
}
] |
[
{
"body": "<h1>Whitespace Following Code Blocks</h1>\n<p>According to the <a href=\"https://www.python.org/dev/peps/pep-0008/#:%7E:text=Use%20blank%20lines%20in%20functions,related%20sections%20of%20your%20file.\" rel=\"nofollow noreferrer\">Python style guide</a>, you should use whitespace sparingly. Try aiming for one single line between functions and code blocks.</p>\n<h1>Unclear Function Naming</h1>\n<p><code>main_func()</code> is not a very clear function name. As a developer reading the code, I am unsure as to what this function contains.</p>\n<p>For a solution to this problem, read the next section:</p>\n<h1>Single-Responsibility Principle</h1>\n<p>Instead of grouping all of the main game code into <code>main_func()</code>, figure out blocks of code that have a single responsibility, and refactor them into their own function.</p>\n<p>For example, the start of <code>main_func()</code> contains code to choose a word. You could refactor this into a <code>choose_word()</code> function that takes the list of words. From this point, you might choose to not pass <code>word_lst</code> into <code>main_func</code>, but instead the chosen word as a result of the <code>choose_word()</code> function.</p>\n<p>As another example, further into your <code>main_func()</code> function, you may choose to refactor the "check" code (to see if the player has correctly guessed the word) into a <code>check_guess()</code> function.</p>\n<h1>Parameter Naming</h1>\n<p>I am not sure if this is just a typo or a stylistic choice, but you should rename <code>word_lst</code> to <code>word_list</code>. In this example, other developers (and possibly yourself in future) will be able to figure out that <code>lst</code> == <code>list</code>, but some words may not be so obvious. Try not to shorten words when naming variables parameters.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T16:55:13.923",
"Id": "484768",
"Score": "2",
"body": "Ok thank you for your time, i really appreciate it. Right now I will try it out what u have said, then will post an update"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T11:21:22.703",
"Id": "247604",
"ParentId": "247603",
"Score": "5"
}
},
{
"body": "<p><strong>Readability 1</strong></p>\n<p>You mentioned splitting the code into functions, but functions should also be meaningful.</p>\n<p>I would remove the <code>def difficult_easy():</code> functions, since they just call the <code>main_func</code> anyway, and put the contents of each of those functions directly in the if-else branch in the starting() function.</p>\n<p>Like this:</p>\n<pre><code>if difficult == 1:\n main_func(['hall', 'exam', 'road', 'gate', 'debt', 'poet', 'sir', 'girl', 'food'], 14)\n</code></pre>\n<p>This makes the code more readable and shorter. These 3 functions don't add anything useful or readable. They force me to look at the bottom of the file to see what they do, when that code could be in the same place as the if-else branch.</p>\n<p><strong>Readability 2</strong></p>\n<pre><code>if letter not in alphabet:\n print('You should enter only one letter!\\n ')\n</code></pre>\n<p>I would add <code>continue</code> here on the line after <code>print</code> . It doesn't change the functionality, but it makes it clear that this is the end of the <code>while</code> loop in this branch and when reading the code I don't have to read further to see if anything more happens after the if-else branching. It also ensures that you don't accidentally execute code that you might add later on below the if-else branch.</p>\n<p><strong>Readability 3</strong></p>\n<pre><code>if letter not in alphabet:\n print('You should enter only one letter!\\n ')\nelif len(letter) != 1:\n print('You can only display 1 letter at a time\\n')\n</code></pre>\n<p>These "early exit" branches are nice and make the code more readable. You could make one more early exit in the same style, by moving the</p>\n<pre><code>if letter in guessed_letters:\n print('You have already guessed this letter!\\n\\n')\n</code></pre>\n<p>To come third here, instead of being nested at the very bottom. Logically, it doesn't change the program, but it becomes more readable and less nested, which is generally a good thing.</p>\n<p><strong>Use variables</strong></p>\n<p>You have defined the variable <code>length = len(secret_word)</code> but you're not using it, instead you are repeating <code>len(secret_word)</code> several times in the code that follows, where you could just use <code>length</code>.</p>\n<p><strong>Other 1</strong></p>\n<pre><code>output = []\n\nfor i in range(len(secret_word)):\n output.append('_')\n</code></pre>\n<p>All of this can be replaced by just one line <code>output = "_" * length</code> since Python allows multiplying a string by a number. (It has to be below the definition of <code>length</code>)</p>\n<p><a href=\"https://docs.python.org/3/library/stdtypes.html#common-sequence-operations\" rel=\"nofollow noreferrer\">https://docs.python.org/3/library/stdtypes.html#common-sequence-operations</a></p>\n<p><strong><s>Other 2</s></strong> (edit: this suggestion is not valid, we do need the index for the output. )</p>\n<pre><code>for n in range(length):\n if secret_word[n] == letter:\n output[n] = letter.upper()\n</code></pre>\n<p>The above is a very C-style loop, but in Python you don't need to loop through the indexes, you can access the characters in the string directly like this:</p>\n<pre><code>for c in secret_word:\n if c == letter:\n output[n] = letter.upper()\n</code></pre>\n<p><strong>Other 3</strong> (added after posting)</p>\n<pre><code>if again.lower() == 'yes' or again.lower() == 'y':\n</code></pre>\n<p>To avoid repeating <code>again.lower()</code> , this can be changed into</p>\n<pre><code>if again.lower() in ['yes', 'y']:\n</code></pre>\n<p>When you have more than 2 options, this becomes even more useful.</p>\n<p><strong>Final comments</strong></p>\n<p>Regarding classes and functions, I don't think you need them. This program is small enough and readable that it would just become more complex if you add classes and functions. If you want to practice, I suggest writing a bigger program instead where they would come to good use.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T23:06:35.920",
"Id": "484823",
"Score": "1",
"body": "Thank you so much for the analisys, I tried fix all that u have said. I'm really surprised in how people answer it so fast and so complete, really impressive. I'm gonna post the final result soon"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T23:19:34.063",
"Id": "484824",
"Score": "0",
"body": "Glad to help. It was not so bad to start with. Readable and structured code from the start made it easy to improve on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T23:25:50.693",
"Id": "484827",
"Score": "0",
"body": "I tried to remove the 'C' style loop but when i did it i got an error, so i'm using the range func again . `Traceback (most recent call last):\n File \"C:/Users/filip/PycharmProjects/HelloWorld/utils.py\", line 77, in <module>\n set_gamemode()\n File \"C:/Users/filip/PycharmProjects/HelloWorld/utils.py\", line 24, in set_gamemode\n execute_game(random.choice(medium_words), 10)\n File \"C:/Users/filip/PycharmProjects/HelloWorld/utils.py\", line 54, in execute_game\n output[c] = letter_input.upper()\nTypeError: list indices must be integers or slices, not str`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-08T00:12:24.210",
"Id": "484832",
"Score": "1",
"body": "@filipaugusto I made a mistake in my \"Other 2\" suggestion. You do need the index, since you are also modifying the letter in `output` at the same index. I forgot about that when suggesting the shorter version."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-08T02:58:27.753",
"Id": "484838",
"Score": "0",
"body": "Ok, i'll fix it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-08T09:04:55.720",
"Id": "484854",
"Score": "0",
"body": "For other 2 [you can use](https://book.pythontips.com/en/latest/enumerate.html) `for n, c in enumerate(secret_word): if c==letter: output[n] = letter.upper()` (with the obvious line breaks & indentation I can't include in comments)."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T22:45:58.893",
"Id": "247637",
"ParentId": "247603",
"Score": "2"
}
},
{
"body": "<p><strong>That's the final result</strong></p>\n<p>I did not do much change but i think that now it is easier to read.\nI'm practising every day and I would love to know any other small project like this or bigger! When you started learning code, what small projects did you do?\nAlso, if you know a good website for practising, please tell me in the coments.</p>\n<pre><code>import random\nimport string\n\nalphabet = string.ascii_letters\neasy_words = ['hall', 'exam', 'road', 'gate', 'debt', 'poet', 'sir', 'girl', 'food']\nmedium_words = ['customer', 'baseball', 'language', 'stranger', 'quantity',\n 'judgment', 'republic', 'proposal', 'magazine']\nhard_words = ['assumption', 'impression', 'restaurant', 'indication', 'excitement',\n 'depression', 'government', 'inspection', 'protection', 'investment']\n\n# Initialize the game\ndef set_gamemode():\n\n print('HANGMAN')\n print('To set the game mode, enter:')\n print('0. To exit')\n print('1. Easy')\n print('2. Medium')\n print('3. Hard')\n difficult = int(input('Your choice: '))\n if difficult == 1:\n execute_game(random.choice(easy_words), 12)\n elif difficult == 2:\n execute_game(random.choice(medium_words), 10)\n elif difficult == 3:\n execute_game(random.choice(hard_words), 9)\n else:\n exit('Exiting...')\n\n# Main function that executes the game by its gamemode\ndef execute_game(word, guesses_given):\n\n guessed_letters = []\n length = len(word)\n output = ['_'] * length\n print(f'Your word has {length} characters ')\n\n while '_' in output:\n letter_input = input('Enter a letter: ')\n\n if letter_input not in alphabet:\n print('You should enter only one letter!\\n ')\n continue\n elif len(letter_input) != 1:\n print('You can only display 1 letter at a time\\n')\n elif letter_input in guessed_letters:\n print('You have already guessed this letter!\\n\\n')\n else:\n guessed_letters.append(letter_input)\n\n if letter_input in word:\n for c in range(length):\n if word[c] == letter_input:\n output[c] = letter_input.upper()\n print(*output, sep=' ')\n print('\\n')\n if '_' not in output:\n print('You won!')\n\n elif letter_input not in word:\n guesses_given -= 1\n print(f"This letter is not in the secret word. REMAINING TRIES: {guesses_given}\\n")\n if guesses_given == 0:\n print(f"You lost. The secret word was '{word.upper()}'")\n break\n\n print('GAMEOVER')\n play_again()\n\n# The name says it\ndef play_again():\n again = input('Play again? (y/n)\\n')\n set_gamemode() if again.lower() in ['y', 'yes'] else exit('Exiting...')\n\n# Driver code\nif __name__ == '__main__':\n set_gamemode()\n\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-08T17:07:25.957",
"Id": "484871",
"Score": "0",
"body": "When I was first learning, I did https://codingbat.com/python and also some of the problems on https://projecteuler.net/ (good if you like math)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-10T22:56:30.017",
"Id": "485077",
"Score": "0",
"body": "yes i like maths thank you, i'm gonna try it"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T22:46:18.377",
"Id": "247638",
"ParentId": "247603",
"Score": "1"
}
},
{
"body": "<p>The biggest problem with this code is the way methods are used, in fact this causes a bug when you try to play more than 250 games.</p>\n<p>Other than <em>goto</em>-statements that can be found in Basic and other languages, methods are usually doing a thing and then returning the control flow back to where they were called from.</p>\n<pre><code>def do_three_things()\n do_first_thing()\n do_second_thing()\n do_third_thing()\n\ndef do_first_thing()\n print("I")\n\ndef do_second_thing()\n print("II")\n\ndef do_third_thing()\n print("III")\n</code></pre>\n<p>In your code every methods ends either with calling <em>exit</em> or another method.</p>\n<pre><code>def do_three_things()\n do_first_thing()\n\ndef do_first_thing()\n print("I")\n do_second_thing()\n\ndef do_second_thing()\n print("II")\n do_third_thing()\n\ndef do_third_thing()\n print("III")\n</code></pre>\n<p>Readability is one problem with this:</p>\n<p>If you look at the method <code>do_three_things</code> in the first example, you see that is very clear what "doing three things" means from the method, in the second case it only looks like is doing the first thing.</p>\n<p>The bigger problem is when you use infinite recursion. That is after the game is over you call method <em>starting</em> all over again, while it actually is still being executed. This way the interpreter has to keep the context of the first method call in memory while the second one is executed, by the moment you play 250 games, it becomes too much for the interpreter and it while throw an exception.</p>\n<p>The way to fix this is to not call <em>play_again</em> from <em>main_func</em> instead return to the main function:</p>\n<pre><code>def main_func(word_lst, guesses_given):\n secret_word = random.choice(word_lst)\n output = []\n guessed_letters = []\n alphabet = string.ascii_letters\n length = len(secret_word)\n print(f'Your word has {len(secret_word)} characters ')\n\n for i in range(len(secret_word)):\n output.append('_')\n\n while '_' in output:\n\n letter = input('Enter a letter: ')\n\n if letter not in alphabet:\n print('You should enter only one letter!\\n ')\n elif len(letter) != 1:\n print('You can only display 1 letter at a time\\n')\n else:\n if letter not in guessed_letters:\n guessed_letters.append(letter)\n\n if letter in secret_word:\n for n in range(length):\n if secret_word[n] == letter:\n output[n] = letter.upper()\n print(*output, sep=' ')\n if '_' not in output:\n print('You won!')\n\n if letter not in secret_word:\n guesses_given -= 1\n print(f"This letter is not in the secret word. REMAINING TRIES: {guesses_given}\\n")\n if guesses_given == 0:\n print(f"You lost. The secret word was '{secret_word.upper()}'")\n break\n\n else:\n print('You have already guessed this letter!\\n\\n')\n\n\n\n print('GAMEOVER')\n</code></pre>\n<p>Then you make <em>play_again</em> return a True or a False value depending on the choice made.</p>\n<pre><code>def play_again():\n again = input('Play again? (y/n)\\n')\n if again.lower() == 'yes' or again.lower() == 'y':\n return True \n else:\n return False\n</code></pre>\n<p>Now you can now have a loop in main that plays until the player has enough:</p>\n<pre><code>if __name__ == '__main__':\n starting()\n while play_again():\n starting()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-10T23:09:13.073",
"Id": "485078",
"Score": "2",
"body": "yes that was something I didn't know for sure if I was it doing right. Right now i'm writting a code for a login system (simple as this hangman game) just wanna say thank you because I was doing the same infinite function loop, but after reading your review I now corrected it!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-08T14:00:52.963",
"Id": "247654",
"ParentId": "247603",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "247637",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T10:34:47.227",
"Id": "247603",
"Score": "9",
"Tags": [
"python",
"hangman"
],
"Title": "Hangman game implemented in Python"
}
|
247603
|
<p>The goal of this code is to allow temporary RHS variables to be used in a span, specifically as an argument to a function, to be deleted later after the function completes, allowing the passing of temporaries to such span accepting functions.</p>
<p>How would I improve this code? Can I make it smaller and more readable? Is the temp_span api fine as it is to telegraph "Only put temporaries here" or is there something else I should be doing?</p>
<pre><code>#include <gsl/span>
namespace gsl{
template<typename T>
class TempSpan{
public:
T value;
explicit TempSpan(T&& t) : value(t){};
operator gsl::span<typename T::value_type>() {
return value;
}
private:
};
template<typename T>
TempSpan<std::vector<T>> temp_span(std::initializer_list<T>&& t){
return TempSpan(std::vector<T>(t));
}
template<typename T>
TempSpan<T> temp_span(T&& t){
return TempSpan(std::move(t));
}
}
#include <iostream>
void foo(gsl::span<int> values){
for(const auto& value: values){
std::cout << value << "\n";
}
}
int main(){
foo(gsl::temp_span(std::vector<int>{1,2,3}));
// 1
// 2
// 3
foo(gsl::temp_span({4,5,6}));
// 4
// 5
// 6
return 0;
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T13:42:48.673",
"Id": "247605",
"Score": "2",
"Tags": [
"c++",
"c++17",
"template-meta-programming"
],
"Title": "Getting around gsl/span's restriction on temporaries"
}
|
247605
|
<p>I have made a <a href="https://en.wikipedia.org/wiki/Snake_(video_game_genre)" rel="nofollow noreferrer">Snake</a> clone using Java 14 and JavaFX 14. My game uses an anonymous instance of the <code>AnimationTimer</code> class as the game loop. The basic UI for the start screen uses FXML, but all of the UI elements in the actual game <code>Scene</code> were added programmatically.</p>
<p>The game board is stored as both a <code>GridPane</code> and as a 2D array of <code>Square</code> objects. Each <code>Square</code> extends <code>javafx.scene.control.Label</code>. The <code>GridPane</code> is used to display the game to the user, and the 2D array is used internally to handle the game logic. Every instance of <code>Square</code> in addition to being a <code>Label</code>, also has added instance variables whose getters and setters are used in conjunction with the <code>GameLogic</code> class. An instance of the <code>GameLogic</code> class is created by the <code>GUI</code> class, which handles the UI.</p>
<p>The basic idea of the program is that each <code>Square</code> stores the direction that the snake body part on that <code>Square</code> should move in when the next frame loads. The head of <code>Snake</code> assigns these directions. The direction that the snake head assigns to the next <code>Square</code> is based on which arrow key the user has most recently pressed. The head of the snake is also used to determine the game over conditions based on whether it has hit the edge of the board or another snake body part. The tail of the snake can either leave its former <code>Square</code> empty or not depending on whether the head has "eaten" the apple. That's how the snake gets longer when an apple is eaten. The snake is defined as the <code>Square</code>s on the board that are also contained in a particular <code>List<Square></code>. The head is the <code>Square</code> in the <code>List<Square></code> located at index <code>0</code>. The tail is located at index <code>size() - 1</code>.</p>
<p>Thus, the structure of my program can be summarized as follows: At the top level is a <code>GUI</code> class which contains an instance of the <code>GameLogic</code> class which includes a 2D array of <code>Square</code> objects. The <code>GUI</code> class is called by a start screen which is controlled by a <code>Main</code> class and an FXML file called <code>start.fxml</code>.</p>
<p>I am going to outline the five files of this program. All but one, <code>start.fxml</code>, are <code>.java</code> files. Feel free to look at them all together, or just review an individual file. The main files in this game are <code>GameLogic.java</code> and <code>GUI.java</code>, which control the internal logic of the game and the user interface, respectively.</p>
<p>First, the start screen: <strong>Main.java</strong></p>
<pre class="lang-java prettyprint-override"><code>import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.io.IOException;
public class Main extends Application {
@Override
public void start(Stage stage) throws IOException {
// Stage set up
// Add title
stage.setTitle("Snake");
// Create root from FXML file
Parent root = FXMLLoader.load(getClass().getResource("start.fxml"));
// Create a Scene using that root, and set that as the Scene for the Stage
stage.setScene(new Scene(root));
// Show the Stage to the user
stage.show();
}
@FXML
private void startButtonClicked(ActionEvent actionEvent) {
// This method starts the game when the user clicks on the Button
// First we get the Button that the user clicked
Node source = (Node) (actionEvent.getSource());
// We use that button to get the Stage
Stage stage = (Stage) (source.getScene().getWindow());
// We get the game Scene from GUI.java, and set that as the Scene for the Stage
stage.setScene(GUI.getGameScene());
}
public static void main(String[] args) {
launch(args); // launch the program
}
}
</code></pre>
<p>Most of this is just JavaFX boilerplate code. This class is both the point of entry for the program, and the controller for <code>start.fxml</code>.</p>
<p>Which brings us to: <strong>start.fxml</strong></p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>
<VBox fx:controller="Main" alignment="CENTER" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="111.0" prefWidth="296.0" spacing="20.0" style="-fx-background-color: rgb(30, 30, 30);" xmlns="http://javafx.com/javafx/10.0.2-internal" xmlns:fx="http://javafx.com/fxml/1">
<Label alignment="CENTER" text="Welcome to Snake" textAlignment="CENTER" textFill="WHITE">
<font>
<Font name="Century Gothic" size="20.0" />
</font>
</Label>
<Button alignment="CENTER" mnemonicParsing="false" onAction="#startButtonClicked" style="-fx-background-color: transparent; -fx-border-color: white;" text="Start" textAlignment="CENTER" textFill="WHITE">
<font>
<Font name="Century Gothic" size="15.0" />
</font>
</Button>
</VBox>
</code></pre>
<p>I wasn't able to add comments to the code because I do not know how to write XML. This code was written with the JavaFX SceneBuilder.</p>
<hr />
<p>Now for the game itself. I'm going to work bottom up, posting <code>Square.java</code>, then <code>GameLogic.java</code> and lastly <code>GUI.java</code>. But first, I need to point out that I am using the following enum throughout the program.</p>
<p><strong>Direction.java</strong></p>
<pre class="lang-java prettyprint-override"><code>public enum Direction {
UP, DOWN, RIGHT, LEFT
}
</code></pre>
<hr />
<p><strong>Square.java</strong></p>
<pre class="lang-java prettyprint-override"><code>import javafx.scene.control.Label;
public class Square extends Label {
// Stores the Square's location in the 2D array
private final int row;
private final int column;
// The board has a checkerboard patter, some some Squares are white and some are black
private final boolean white;
// The user controls the snake and attempts to get to a special square which is an apple. This boolean determines if this is that Square
private boolean apple;
// This is the direction that the particular snake body part should travel in if it is on this square
private Direction direction;
/*The rest of the methods are the standard constructor, getters, and setters*/
public Square(int row, int column, boolean white) {
super();
this.row = row;
this.column = column;
this.white = white;
apple = false;
direction = null;
setMaxHeight(15);
setMaxWidth(15);
setMinWidth(15);
setMinHeight(15);
}
public int getRow() {
return row;
}
public int getColumn() {
return column;
}
public boolean isWhite() {
return white;
}
public boolean isApple() {
return apple;
}
public void setApple(boolean apple) {
this.apple = apple;
}
public Direction getDirection() {
return direction;
}
public void setDirection(Direction direction) {
this.direction = direction;
}
}
</code></pre>
<p>The <code>GameLogic</code> class contains both a 2D array of <code>Square</code> objects, and a special <code>List</code> of <code>Square</code> objects which identifies those <code>Square</code>s that the snake is currently on.</p>
<p><strong>GameLogic.java</strong></p>
<pre class="lang-java prettyprint-override"><code>import java.util.List;
import java.util.Random;
public class GameLogic {
// The game board
private final Square[][] board;
// The particular Squares on the game board that the snake is on
// The Square at index 0 is always the head
// The Square at index snake.size() - 1 is always the tail
private final List<Square> snake;
// Standard constructor
public GameLogic(Square[][] board, List<Square> snake) {
this.board = board;
this.snake = snake;
}
// Change the direction that the head of the snake should move in
public void changeDirection(Direction direction) {
Square head = snake.get(0);
if ((head.getDirection() == Direction.UP && direction == Direction.DOWN) ||
(head.getDirection() == Direction.DOWN && direction == Direction.UP) ||
(head.getDirection() == Direction.RIGHT && direction == Direction.LEFT) ||
(head.getDirection() == Direction.LEFT && direction == Direction.RIGHT)) return;
head.setDirection(direction);
}
// This method increments the game by performing the next move
public boolean nextMove() {
// Identify the row and column of the head
int row = snake.get(0).getRow();
int column = snake.get(0).getColumn();
// Create a variable that each square on the snake should replace itself with when the snake moves
Square nextSquare = null;
// Has the snake eaten an apple this move? Assume no at first
boolean ateTheApple = false;
// Determine which direction the snake should move in
// I will only add comments to the first case, since they all function in the exact same way
switch (snake.get(0).getDirection()) {
case UP:
// If the snake is trying to move off the board, or if the place it is moving to is on its body, game over
if (row == 0 || snake.contains(board[row - 1][column])) return false;
// Otherwise, we can now instantiate nextSquare
nextSquare = board[row - 1][column];
// Thee head is the only body part that passes its direction to nextSquare
nextSquare.setDirection(snake.get(0).getDirection());
// Set nextSquare to be the head
snake.set(0, nextSquare);
break;
case DOWN:
if (row == board.length - 1 || snake.contains(board[row + 1][column])) return false;
nextSquare = board[row + 1][column];
nextSquare.setDirection(snake.get(0).getDirection());
snake.set(0, nextSquare);
break;
case RIGHT:
if (column == board[0].length - 1 || snake.contains(board[row][column + 1])) return false;
nextSquare = board[row][column + 1];
nextSquare.setDirection(snake.get(0).getDirection());
snake.set(0, nextSquare);
break;
case LEFT:
if (column == 0 || snake.contains(board[row][column - 1])) return false;
nextSquare = board[row][column - 1];
nextSquare.setDirection(snake.get(0).getDirection());
snake.set(0, nextSquare);
break;
}
// If the nextSquare variable is an apple
if (nextSquare.isApple()) {
// We don't want this Square to be an apple in the next frame, as the snake's head is currently on it
nextSquare.setApple(false);
// We have eaten the apple
ateTheApple = true;
}
// Loop through the rest of the body parts except for the tail
for (int i = 1; i < snake.size() - 1; i++) {
switch (snake.get(i).getDirection()) {
case UP:
nextSquare = board[snake.get(i).getRow() - 1][snake.get(i).getColumn()];
break;
case DOWN:
nextSquare = board[snake.get(i).getRow() + 1][snake.get(i).getColumn()];
break;
case RIGHT:
nextSquare = board[snake.get(i).getRow()][snake.get(i).getColumn() + 1];
break;
case LEFT:
nextSquare = board[snake.get(i).getRow()][snake.get(i).getColumn() - 1];
break;
}
// Move the body part to nextSquare
snake.set(i, nextSquare);
}
// Identify the tail
Square tail = snake.get(snake.size() - 1);
switch (tail.getDirection()) {
case UP:
nextSquare = board[tail.getRow() - 1][tail.getColumn()];
break;
case DOWN:
nextSquare = board[tail.getRow() + 1][tail.getColumn()];
break;
case RIGHT:
nextSquare = board[tail.getRow()][tail.getColumn() + 1];
break;
case LEFT:
nextSquare = board[tail.getRow()][tail.getColumn() - 1];
break;
}
// Move the tail
snake.set(snake.size() - 1, nextSquare);
// If we ate the apple
if (ateTheApple) {
// Add the former tail right back to increase the length of the tail
snake.add(tail);
// Find a random spot to place the new apple
Random random = new Random();
int r, c;
while (true) {
r = random.nextInt(board.length);
c = random.nextInt(board[0].length);
if (!snake.contains(board[r][c])) {
board[r][c].setApple(true);
break;
}
}
}
// Were done. The move worked, so we return true
return true;
}
// Given the current state of the new board, repaint all the Squares
public void paintBoard() {
for (Square[] row : board) {
for (Square square : row) {
if (square == null) {
System.out.println("Square is null");
return;
}
if (snake.contains(square)) {
square.setStyle("-fx-background-color: green;");
continue;
}
if (square.isApple()) {
square.setStyle("-fx-background-color: red;");
continue;
}
square.setStyle("-fx-background-color: " + (square.isWhite()? "rgb(200, 200, 200)" : "rgb(50, 50, 50)") + ";");
}
}
}
}
</code></pre>
<p>Finally, an instance of the <code>GameLogic</code> class is created by the <code>GUI</code> class which displays the game to the user</p>
<p><strong>GUI.java</strong></p>
<pre class="lang-java prettyprint-override"><code>import javafx.animation.AnimationTimer;
import javafx.scene.Scene;
import javafx.scene.layout.GridPane;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class GUI {
public static Scene getGameScene() {
// This GridPane stores the board
GridPane grid = new GridPane();
// This 2D array also stores the board
Square[][] board = new Square[30][30];
// This identifies which Squares are on the snake
List<Square> snake = new ArrayList<>();
// Loop through the board and initialize the Squares
int count = 0, i, j;
for (i = 0; i < board.length; i++) {
for (j = 0; j < board[0].length; j++) {
board[i][j] = new Square(i, j, (i + count) % 2 == 0);
count++;
grid.add(board[i][j], j, i);
// If the Square is add the starting location, place a snake body part there
// and set its direction to be RIGHT by default
if (i == 10 && j >= 10 && j <= 12) {
board[i][j].setDirection(Direction.RIGHT);
snake.add(0, board[i][j]);
}
}
}
// Place the apple somewhere random
Random random = new Random();
int r, c;
while (true) {
r = random.nextInt(30);
c = random.nextInt(30);
if (!snake.contains(board[r][c])) {
board[r][c].setApple(true);
break;
}
}
// Create an instance of GameLogic. Pass it the board and the list of snake body parts
GameLogic snakeGame = new GameLogic(board, snake);
// Paint the initial board
snakeGame.paintBoard();
// Create a scene and add the GridPane to it
Scene scene = new Scene(grid);
// Store the user inputs
List<String> input = new ArrayList<>();
// Get the inputs to store from the scene
scene.setOnKeyPressed(keyEvent -> {
String code = keyEvent.getCode().toString();
if (input.size() == 0) {
input.add(code);
}
});
scene.setOnKeyReleased(keyEvent -> {
String code = keyEvent.getCode().toString();
input.remove(code);
});
// Start time for animation timer
final long[] lastTime = {System.nanoTime()};
// The game loop
new AnimationTimer() {
@Override
public void handle(long currentTime) {
// If the user has requested a change of direction, do it now
if (input.size() != 0) {
snakeGame.changeDirection(Direction.valueOf(input.get(0)));
}
// Calculate how much time has elapsed since the last frame
double elapsedTime = (currentTime - lastTime[0]) / 1000000000.0;
// If it is time to launch a new frame, do it
if (elapsedTime >= 0.2) {
// Reset the time
lastTime[0] = System.nanoTime();
// Attempt the move
boolean move = snakeGame.nextMove();
// Repaint the board
snakeGame.paintBoard();
// If the user got out, end the game
if (!move) {
grid.setDisable(true);
stop();
}
}
}
}.start(); // Start the game loop
// Finally, return this Scene to to the stage in Main.java
return scene;
}
}
</code></pre>
<p>That's it. I'm relatively new to JavaFX so I don't really know how game development with it is supposed to work. I used <a href="https://gamedevelopment.tutsplus.com/tutorials/introduction-to-javafx-for-game-development--cms-23835" rel="nofollow noreferrer">this article</a> as my starting point.</p>
<p>The start screen:</p>
<p><a href="https://i.stack.imgur.com/lJSDQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lJSDQ.png" alt="Start screen" /></a></p>
<p>The game in progress:</p>
<p><a href="https://i.stack.imgur.com/3VJSK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3VJSK.png" alt="The Game Screen" /></a></p>
|
[] |
[
{
"body": "<p><strong>TL;DR summary:</strong> Use less comments, use meaningful comments, use <code>Deque</code>, DRY and generalise the repetitive code (with some smarts), out-of-border checking, make <code>Square</code> abstract & paint in it's subclass, repaint only when something changes.</p>\n<hr />\n<p>Firstly, I am totally new to this StackExchange, so sorry if I misunderstood my review task or I cross any borders - I honestly don't want to be mean to you, just to point out style errors or things that can be improved in your design or implementation.</p>\n<p>I have not run your solution at all, it looks functional and I believe you it works. But I have read all the code.</p>\n<hr />\n<h2>Review</h2>\n<ol>\n<li>You have good direction of control - you are calling the core functionality from the UI. However, it could be <em>brilliant</em> if you could get rid of the dependency on JavaFX totally. The <code>GameLogic</code> should be UI-agnostic, it should be an independent module you could reuse from say a console UI. You are on a very good way here - the only thing you do with JavaFX in <code>GameLogic</code> is <code>paintBoard()</code>. And good job injecting <code>Square[][]</code>! The color of the tile, or Square as you call it, should be the responsibility of the <code>Square</code> class itself. A <strong>color</strong> is not logically the responsibilty of the game logic. The <code>GameLogic</code> can call a method of the <code>Square</code> to change it's state and it is the responsibility of the <code>Square</code> to manifest the changed state by changing it's color.</li>\n</ol>\n<p>And the <code>Square</code> can easily do this task itself, you have provided it with fields (defining the state) <code>white</code>, <code>apple</code>. So the default color can be given by <code>white</code>, and then in the <code>setApple()</code> you can change the color if needed (hurray encapsualtion with setter methods!).</p>\n<p>The only other state which has another color is when the snake is on the square.</p>\n<ul>\n<li><p>You could introduce another field marking this state (also update in setter).</p>\n</li>\n<li><p>Another solution which comes to my mind is to consider <code>Square</code> as a place where something can stand on or cover the square. This would be a good solution if you want to extend the possible entities which can be in your world (you could have poisoned apples, walls, holes...). I would implement this by introducing a new interface, f.e. <code>Placeable</code> with some method to draw the UI & the <code>Square</code> would have a field <code>Placeable placedObject</code> or something similar. This way you do not need to add more fields to the <code>Square</code> for each item and each item has its own UI responsibility.</p>\n</li>\n</ul>\n<p>The next step in making the core game logic independent is to make <code>Square</code> <strong>not</strong> extend <code>Label</code>, make it abstract. Extract the painting logic (which calls <code>setStyle</code>) into an abstract method and implement it in a subclass <code>JavaFxSquare</code> which can extend <code>Label</code>. You will probably call the <code>paint()</code> method in the setters or on demand.</p>\n<ol start=\"2\">\n<li><p>Why does <code>Square</code> extend <code>Label</code> in the first place? It does not contain any text. I vaguely remember that I had a problem with <code>javafx.scene.shape.Rectangle</code> putting it into a <code>GridPane</code> - is this the reason? Anyway: don't extend <code>Label</code>, probably extending <code>Region</code> is enough.</p>\n</li>\n<li><p>Rename <code>white</code> => <code>isWhite</code> and <code>apple</code> => <code>hasApple</code>. Usually boolean variable names are adjectives or start with <code>is</code> or <code>has</code></p>\n</li>\n<li><p>The field <code>white</code> can be calculated inside the constructor of <code>Square</code>. One could say it is his responsibility, but if you want it to be configurable, it can stay a constructor parameter.</p>\n</li>\n<li><p>You have waaaaaaaaaaaaaaay too many comments. I am not sure whether you have commented each line just for the review or you actually have so many comments. The problem is these comments have no meaning most of the time:</p>\n</li>\n</ol>\n<pre><code>// Create a scene and add the GridPane to it\nstage.setScene(new Scene(root));\n\n// Store the user inputs\nList<String> input = new ArrayList<>();\n\n// Create an instance of GameLogic. Pass it the board and the list of snake body parts\nGameLogic snakeGame = new GameLogic(board, snake);\n\n// If the nextSquare variable is an apple\n if (nextSquare.isApple()) {\n</code></pre>\n<p>A lot of code you have commented is self-explanatory and do not need comments. Some well-named variable is way better. So many comments are distracting when reading the code, because after a while I was just ignoring the comments - and this way I can miss something important! And comments should be only for the important stuff - something unusual, some bugfix which is not apparent why the implementation is that way... If you need to comment a block of code, you should probably extract it to a well-named method.</p>\n<ol start=\"6\">\n<li><p>Rename <code>i</code>, <code>j</code> to <code>row</code> and <code>col</code>.</p>\n</li>\n<li><p><code>count</code> variable has no sense, it is identical to <code>j</code> (i.e. <code>col</code>)</p>\n</li>\n<li><p>What happens if you eat 2 apples quickly? can it happen?</p>\n</li>\n<li><p>Good job with detecting if the new apple position is not inside the snake already! However:</p>\n<ul>\n<li>DRY (don't repeat yourself): it should be on 1 place, probably inside <code>GameLogic</code> (and call it in constructor)</li>\n<li>creating a <code>new Random()</code> always is not a good idea, it can produce the same values if initialised with a short interval. You should initialise it once in your constructor.</li>\n</ul>\n</li>\n<li><p><code>LinkedList</code> is <em>the perfect</em> implementation for your Snake. Manipulating the "head" and "tail" should be enough for you, so you could use the <code>Deque</code> interface. You should replace your method calls:</p>\n<ul>\n<li><code>snake.get(0)</code> => <code>snake.getFirst()</code></li>\n<li><code>snake.set(0, x)</code> => <code>snake.addFrist(x)</code></li>\n<li><code>snake.get(snake.size() - 1)</code> => <code>snake.getLast()</code></li>\n<li><code>snake.set(snake.size() - 1, nextSquare)</code> => <code>snake.addLast(nextSquare)</code></li>\n</ul>\n</li>\n</ol>\n<p>Why are you actually moving all the squares? It is enough to add a new head and remove the tail if it haven't eaten an apple. The other parts of the Snake stay untouched.</p>\n<ol start=\"12\">\n<li>Change <code>input.size() == 0</code> => <code>input.isEmpty()</code>.</li>\n</ol>\n<p>Why is <code>input</code> a list? How does your game work if you hold one arrow and then press another arrow without releasing the first? The snake does not change it's direction, does it? Is it the expected behavior? If you want to store only the most recent key pressed, it would be enough to not use a <code>List</code>.</p>\n<p>What happens if you press a non-arrow key?</p>\n<p>Instead of using a <code>String</code> you can also store the <code>KeyCode</code> (maybe later you will want to enable WASD also, so you can have a method which maps it to <code>Direction</code>).</p>\n<pre><code>- I am not sure how the threads on key pressed work, but maybe you need to `synchronise` the assignment and read of `input`\n</code></pre>\n<ol start=\"13\">\n<li>You have a hidden logic when you test</li>\n</ol>\n<pre><code>head.getDirection() == Direction.UP && direction == Direction.DOWN\n</code></pre>\n<p>How would you name it? I'd say you are checking whether the directions are opposite. I suggest you add an <code>opposite</code> field to your <code>Direction</code> like so:</p>\n<pre><code> public enum Direction {\n UP, DOWN, RIGHT, LEFT;\n\n private Direction opposite;\n\n static {\n UP.opposite = DOWN;\n DOWN.opposite = UP;\n RIGHT.opposite = LEFT;\n LEFT.opposite = RIGHT;\n }\n\n Direction getOpposite() {\n return opposite;\n }\n }\n</code></pre>\n<p>Sadly, it is a bit complicated because of <a href=\"https://stackoverflow.com/questions/5678309/illegal-forward-reference-and-enums\">Illegal forward reference</a>.</p>\n<p>This way you can change your 4 (<strong>!</strong>) conditions to this:</p>\n<pre><code>head.getDirection() == direction.opposite()\n</code></pre>\n<ol start=\"14\">\n<li>You yourself have commented:</li>\n</ol>\n<blockquote>\n<p>"since they all function in the exact same way"</p>\n</blockquote>\n<p>Again: DRY! You should generalise the following code. Most of it is identical, except for the index calculation and border checking.</p>\n<ol>\n<li>The index calculation depends on the <code>Direction</code> you take. There is a pattern in which you move by 1 in the x-y axis. You can solve the index calculation by adding 1 if you move in the direction of the axis, subtracting 1 if you move in the opposite direction, or adding 0 if you stay on that axis. So:</li>\n</ol>\n<pre><code>public enum Direction {\n UP(-1, 0),\n DOWN(1, 0),\n RIGHT(0, 1),\n LEFT(0, -1);\n\n private int rowChange;\n private int colChange;\n\n Direction(int rowChange, int colChange) {\n this.rowChange = rowChange;\n this.colChange = colChange;\n }\n\n int getRowChange() {\n return rowChange;\n }\n\n int getColChange() {\n return colChange;\n }\n}\n</code></pre>\n<p>So the resulting code is:</p>\n<pre><code>nextSquare = board[row + direction.getRowChange()][column + direction.getColChange()];\n</code></pre>\n<ol start=\"2\">\n<li>Border checking is easy if you check the nextSquare: does it have a <code>row</code> or <code>col</code> <code>< 0</code> or <code>>= size</code> ?</li>\n</ol>\n<pre><code></code></pre>\n<ol start=\"15\">\n<li><p>The <code>changeDirection()</code> comments nothing about ignoring opposite direction - THAT should be commented, it's an interesting edge case.</p>\n</li>\n<li><p><code>nextMove()</code> comment has nothing saying about the meaning of return value. The name of the method neither does help. The return type should be well documented in this case, it is not apparent - JavaDoc <code>@return</code> is just for this!</p>\n</li>\n<li><p><strike>It could be considered for <code>nextMove()</code> to be void and throw a <code>GameOverException</code> (what a cool name!). It's not necessary, just a possibility.</strike> Having a boolean returned in this case is even better, because philosophically it is the expected behaviour to hit a wall or eat your tail. However, see point 16.</p>\n</li>\n<li><p>what's this about? why should it be null?</p>\n</li>\n</ol>\n<pre><code>if (square == null) {\n System.out.println("Square is null");\n return;\n}\n</code></pre>\n<ol start=\"19\">\n<li>Is repainting of the whole board needed? repaint only what has changed, with larger grids, it can very quickly lag.</li>\n</ol>\n<p>If you implement reactive change inside <code>Square</code> upon setting <code>apple</code> for example, this is not an issue anymore.</p>\n<ol start=\"20\">\n<li><p>In your <code>UI</code> class, the size could be parameterizable. For example the user could input it. Keep it in mind and use a variable for the size, not hardcoded int literals.</p>\n</li>\n<li><p>Calculate the middle of the board for the initial position of the snake. Alternatively, you could generate it randomly. The direction could also be random.</p>\n</li>\n</ol>\n<hr />\n<p>I hope all of this helps :D I think you could do most of the points separately, so don't be intimidated by the high amount. I am very much looking forward to your next steps and development! Don't hesitate to write in case of any questions.</p>\n<hr />\n<h2>Future extensions</h2>\n<p>You could think about your solution to be flexible and extensible in the future. You could implement these in the future, or prepare your solution to be extended once. Some ideas:</p>\n<ol>\n<li>Configurable board size</li>\n<li>Performance improvement - multi-threading</li>\n<li>Other kinds of objects on the board, like walls, golden apples, laxatives, energy drink\n<ul>\n<li>think of leveraging the game aspects f.e. length of snake, score, speed of game, game over</li>\n</ul>\n</li>\n<li>Another UI support - console or some other GUI</li>\n<li>Multiplayer? :D</li>\n<li>Tracking the score, keeping a highscore</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-11T01:01:56.297",
"Id": "485093",
"Score": "0",
"body": "Thanks, you've given me a lot to think about. This is the first game I've made with graphics (I only learned how to program this year), so I'm sort of figuring it out as I go. I made `Square` extend `Label` for precisely the reason you mentioned; it just didn't work with `Rectangle`s for some reason. The comments were added in a hurry for the purpose of this review. I don't actually use comments in real life(I should probably change that). It occurs to me that they probably did more harm then good. The check for `(square == null)` was a remnant of the debugging process that I forgot to remove."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-11T09:35:56.530",
"Id": "485135",
"Score": "1",
"body": "Congrats, you are advancing very well! I think your design is good, it was a good decision to use your classes and enum.Only you need to pay attention to the dependency directions - from UI to controller to business logic to entities (see Clean Architecture). This helps extensibility - you could use another UI.\n\nImplementation-wise you should look out for repetitive code and try to simplify it.\n\nRegarding the comments - most of the time they say WHY you do something, not WHAT you do (the variable and method names should be self-explanatory). Also good idea to add JavaDocs to public methods"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T05:46:16.743",
"Id": "502843",
"Score": "0",
"body": "Hello Hawk, you have a great answer, but I would object to `2. Performance improvement - multi-threading` when talking about `JavaFX`. With the emphasis on multi-threading. Though `Threads` can be used in `JavaFX`, using something from the `Animation` API, is the best choice here."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-11T00:24:09.277",
"Id": "247745",
"ParentId": "247606",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "247745",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T14:01:05.423",
"Id": "247606",
"Score": "5",
"Tags": [
"java",
"beginner",
"snake-game",
"javafx",
"fxml"
],
"Title": "JavaFX clone of Snake game"
}
|
247606
|
<p><strong>Given:</strong></p>
<ul>
<li><code>G</code> is an arbitrary graph</li>
<li><code>partitions</code> is a list of its edges divided into (in this case) 3 sets.</li>
</ul>
<p><strong>Color generation:</strong></p>
<ul>
<li>Its purpose is to generate one distinct color for each partition.</li>
<li>The function turns a number between 0 and 1 into an RGB color.</li>
<li>For the given example, with 3 partitions, it would be called with 1/3, 2/3, and 1, and return a list of codes for green, blue, and red.</li>
<li>For other numbers it would be used to spread the different colors as widely as possible.</li>
<li>Visually, think of a circle with R, G, and B equally spaced around it.
The number is the fraction of the way around the circle from R to pick the color, so if the number is .4, the color would be between G and B, closer to the G.</li>
</ul>
<p><strong>Color assignment:</strong></p>
<ul>
<li>For each set in the partition, a different color is generated and assigned to a list of colors.</li>
<li>In this case <code>edge_color_list</code> would be 9 greens, 4 blues, and 2 reds.</li>
<li>The actual list is:
[(0, 1.0, 0.0), (0.0, 0, 1.0), (0.0, 0, 1.0), (0, 1.0, 0.0), (0, 1.0, 0.0), (0, 1.0, 0.0), (0, 1.0, 0.0), (0, 1.0, 0.0), (0, 1.0, 0.0), (0, 1.0, 0.0), (0.0, 0, 1.0), (0, 1.0, 0.0), (1.0, 0, 0.0), (1.0, 0, 0.0), (0.0, 0, 1.0)]</li>
</ul>
<p><strong>Problem:</strong>
The top and bottom sections can't really be changed, but the <code>def_color()</code> function and <code>edge_color_list</code> sections each look like they were written in C, and I think they could be done more elegantly.</p>
<p>It's obvious how I was thinking while writing it (i.e. how I would write it in C), but I'd like to know how python coders think.</p>
<p>I'm having trouble writing python without a heavy C accent (I wrote C for decades).</p>
<p>I understand the python language fairly well (or know how to recognize what I don't know and how to look it up).</p>
<p>And I've reached the stage where what I've written <em>feels</em> wrong.</p>
<p>But I still don't seem to <em>think</em> in native python:</p>
<pre><code>#!/usr/bin/env python3
import matplotlib.pyplot as plot
import networkx as nx
G = nx.petersen_graph()
partitions = [{0, 3, 4, 5, 6, 7, 8, 9, 11}, {1, 2, 10, 14}, {12, 13}]
def get_color(fraction):
if fraction < 1/3:
color = (1-3*fraction, 3*fraction, 0)
elif fraction < 2/3:
fraction -= 1/3
color = (0, 1-3*fraction, 3*fraction)
else:
fraction -= 2/3
color = (3*fraction, 0, 1-3*fraction)
return color
edge_color_list = [None] * len(G.edges())
for i in range(len(partitions)):
items = list(partitions[i]) # convert from set
for j in range(len(items)):
edge_color_list[items[j]] = get_color((i+1)/len(partitions))
nx.draw(G, with_labels=True, pos=nx.circular_layout(G), width=2,
node_color='pink', edge_color=edge_color_list)
plot.show()
</code></pre>
<p>Any suggestions about how I could have thought differently while writing the above would be appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T14:56:14.203",
"Id": "484754",
"Score": "5",
"body": "Please tell us more about the purpose of the code. What does it do and what prompted you to write it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T15:52:29.933",
"Id": "484760",
"Score": "1",
"body": "@Mast, I've added more details about the code."
}
] |
[
{
"body": "<p>I would change this</p>\n<pre><code>for i in range(len(partitions)):\n items = list(partitions[i]) # convert from set\n for j in range(len(items)):\n edge_color_list[items[j]] = get_color((i+1)/len(partitions)\n</code></pre>\n<p>to:</p>\n<pre><code>for idx, partition in enumerate(partitions): # I personally do it your way \n items = list(partition) # convert from set\n for item in items: \n edge_color_list[items] = get_color((idx+1)/len(partitions) \n # idx is the `i` from before \n</code></pre>\n<p>I referenced <a href=\"https://stackoverflow.com/a/522578/5728614\">this</a>.</p>\n<p>There might be a linting plugin to help align your code towards being pythonic</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T16:29:30.663",
"Id": "484763",
"Score": "0",
"body": "feel free to edit/expand. I'm no expert..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T16:29:40.057",
"Id": "484764",
"Score": "0",
"body": "This results in an error. Additionally how is this better than the OP's code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-08T21:27:24.700",
"Id": "484877",
"Score": "0",
"body": "\"feel free to edit/expand\". The original title was \"Writing python without a C accent\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-20T07:27:35.017",
"Id": "531010",
"Score": "0",
"body": "furthermore, `enumerate` is the pythonic manner, while `range(len(partitions))` is the C style"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T16:27:41.477",
"Id": "247614",
"ParentId": "247609",
"Score": "-2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T14:41:19.620",
"Id": "247609",
"Score": "4",
"Tags": [
"python",
"python-3.x"
],
"Title": "Highlighting partitions in distinct color"
}
|
247609
|
<p>For learning purposes, I have written a small calculator app on Python, tkinter.
I want to check if my design is on best practices for OOP, And seek advice on Nested functions</p>
<p>For easy readability, I have only included the Addition functionality, same logic can be applied to Subtract, Multiply etc..with few changes to the #calculations.py</p>
<hr />
<p>My entry:</p>
<pre><code>#app.py
from tkinter import Tk
from all_tabs import AllmyTabs
class App:
def __init__(self, app):
self.app = app
app.title('My Calculator')
# app['bg'] = '#f8bbd0'
app['bg'] = '#ff80ab'
app.minsize(325, 200)
app.maxsize(325, 200)
tab_addition = AllmyTabs(app)
root = Tk()
my_app = App(root)
root.mainloop()
</code></pre>
<hr />
<p>Next I'm setting tabs for each window, this snippet will include a Add and Subtract Tab, more can be added if needed</p>
<pre><code>#all_tabs.py
from tkinter import ttk
from calculations import my_addition
class AllmyTabs(ttk.Frame):
def __init__(self, app):
super().__init__(app)
self.app = app
s = ttk.Style()
s.configure('TFrame', background='#f8bbd0', )
#===========================================#
self.tab_pannel = ttk.Notebook(self.master,)
self.tab_pannel.grid(pady =40, padx=10)
#===========================================#
self.addition_tab = ttk.Frame(self.tab_pannel, width=250, height=250, padding=10 )
self.tab_pannel.add(self.addition_tab, text=' Add ',)
my_addition(self.addition_tab)
#===========================================#
self.subtraction_tab = ttk.Frame(self.tab_pannel,padding=10)
self.tab_pannel.add(self.subtraction_tab, text=' Subtract ')
my_subtraction(self.subtraction_tab)
</code></pre>
<hr />
<p>Now This is where I'm having the troubles, <code>my_addition()</code> function works as expected, but if you check, you can see that I have used nested functions. So I decided to ask for help on how can I manage without coming up with extra nests.</p>
<p>Closures are great to continue where needed, but in my case I think it adds up extra complexity to the code and it gets harder to read.</p>
<pre><code>#calculations.py
import tkinter as tk
from tkinter import N, E, S, W, NSEW, IntVar, StringVar
def my_addition(app):
def now_adding():
if len(addition_entry.get()) == 0:
out_put_number.set('Enter a number')
elif len(addition_no.get()) == 0:
out_put_number.set('2 numbers are needed')
else:
result = int(addition_entry.get()) + int(addition_no.get())
out_put_number.set(result)
addition_entry.delete(0, 'end')
addition_no.delete(0, 'end')
def only_numbers(char):
return char.isdigit()
vcmd = app.register(only_numbers)
addition_entry = tk.Entry(app, validatecommand=(vcmd, '%S'))
addition_entry['validate'] = 'key'
addition_entry.grid(column=1, row=0,)
plus_lbl = tk.Label(app, text=' + ', bg='#f8bbd0')
plus_lbl['font'] = 20
plus_lbl.grid(column=2, row=0, )
addition_no = tk.Entry(app, validate="key", validatecommand=(vcmd, '%S'))
addition_no.grid(column=3, row=0, sticky=E)
result_label = tk.Label(app, text='Result: ', bg='#f8bbd0')
result_label.grid(column=1, row=1, sticky=W)
out_put_number = StringVar()
result_output = tk.Label(app, bg='#f8bbd0', textvariable=out_put_number)
result_output['font'] = 20
result_output.grid(column=1, row=1, columnspan=3,)
addition_btn = tk.Button(app, text='Add', command=now_adding, state='normal')
addition_btn.grid(column=3, row=1, pady=10, sticky=E )
#===============================================================================#
#===============================================================================#
def my_subtraction(app):
pass
</code></pre>
<p>I have tried using classes on the #calculation.py module, but then again extra complexity comes up.</p>
<p>Because I'm learning and trying to understand the underlying principle of OOP, the more readable a code, the more easily I can comprehend it</p>
<p>Is there a way to refactor the code and keep it simple as possible??</p>
<p>Any Advice is much appreciated.</p>
<p>Thanks.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T15:21:08.967",
"Id": "484757",
"Score": "1",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T15:26:12.093",
"Id": "484758",
"Score": "0",
"body": "thanks for the tip"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T21:21:19.350",
"Id": "484815",
"Score": "0",
"body": "\"more can be added if needed\" Could you simply share the full (unedited) thing with us? Keep it structured like it is, dump the full thing at the bottom of the question. There's a limit of 65k and a bit characters, I'm sure you'll stay under that. But the extra context may help with better answers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-08T09:03:18.417",
"Id": "484853",
"Score": "0",
"body": "@Mast, the above code will work and run perfectly, the part which I have excluded will follow the same logic. for example. if you check the `#all_tabs.py`: `addition_tab` and `subtraction_tab` have a similar structure, same structure can be applied to a `multiply_tab` or a `division_tab` etc...my problem rises in `#calculations.py`, where I have written my full code, I stopped on `my_addition()` because its the function that I want to simplify, once it is simplified the the same structure will be applied to 'my_subtraction()` with few changes, Hope I made myself clear, thanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-08T09:05:21.973",
"Id": "484855",
"Score": "0",
"body": "Your question is at the brink of getting closed for lack of context."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-08T09:15:33.860",
"Id": "484856",
"Score": "0",
"body": "I'm sorry it lack context,But My full code is exactly as #app.py and #all_tabs.py, I'm trying to implement, A FUNCTION AT A TIME, not to write the whole thing, since am still learning it helps me to debug easily.."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T15:02:39.170",
"Id": "247610",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"object-oriented",
"tkinter",
"closure"
],
"Title": "A Tabbed calculator in python with tkinter"
}
|
247610
|
<p>I was wondering why we people don't use a generic interface instead of error type. You can see this pattern a lot in the Golang community:</p>
<pre><code>func Division(a int, b int) (int, error) {
if b == 0 {
return 0, errors.New("divided by zero error")
}
return a / b, nil
}
</code></pre>
<p><strong>error</strong> is not like exception (in Java), so we usually have a chain of conditional statements to check the error and stuff. In this sample I just used a generic interface for both the result and the error itself (I don't need the error type here! just nil is enough)</p>
<pre><code>func Division1(a int, b int) interface{} {
if b == 0 {
return nil
}
return a / b
}
</code></pre>
<p>Or we can have a struct for the return type, this is more clean than to have many return types.</p>
<pre><code>type Output struct {
Result interface{}
Error error
}
func Division(a int, b int) Output {
if b == 0 {
return Output{
Error: errors.New("divided by zero error"),
}
}
return Output{
Result: a / b,
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-09T10:31:34.537",
"Id": "484900",
"Score": "0",
"body": "In your question you should explain whether you already read [Effective Go](https://golang.org/doc/effective_go.html#errors), and if so, what your particular criticism is. What are the benefits and drawbacks of your approaches? After you did that, you will probably receive some more insights in the answers. Right now the question doesn't reveal what you already know and what you don't."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-10T20:30:33.450",
"Id": "485056",
"Score": "0",
"body": "Thanks @RolandIllig, Yeah I read the effective Go. The problem is that the community use this style a lot and this can not be always good. When we don't need the error details and just a nil is enough there is no need to use error for return. and also when we need error + result then there is no need to have two return types one struct is enough (in terms of clean code)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-10T20:55:29.290",
"Id": "485058",
"Score": "0",
"body": "I said \"in your question\" intentionally. Having this information in a comment alone has no value."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-10T20:58:31.353",
"Id": "485059",
"Score": "1",
"body": "And please explain _in detail_ why you think that a struct would be cleaner than two return values. Just saying \"I know it\" or \"this book says it\" does not count."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-11T19:23:42.717",
"Id": "485199",
"Score": "0",
"body": "returning interface{} is problematic because you need that many additional conditional statements to figure what was returned. returning a user defined struct as you did work but it just does not take advantages of the language capabilities. Your Output type, as of now, can not provide a standard way to handle errors, it offers no contract surface to build an api upon. Consider that maintainers and creators of this language tries to provide standard ways to write program that every body can learn and apply to share and grab code with/from others."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T12:08:35.417",
"Id": "486424",
"Score": "0",
"body": "@RolandIllig a struct has \"clean code\" benefit, when we have more than 2 arguments it's really hard to read and maintain the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T15:44:41.687",
"Id": "486443",
"Score": "0",
"body": "No, it isn't. Why would it be hard to read? I find \"result, err\" much easier to read than \"struct { result int, err error } { result, err }\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T15:47:12.243",
"Id": "486444",
"Score": "0",
"body": "By the way, when I said _in detail_ above, I really meant it. Your previous comment is exactly the \"I know it\" that lacks any detail or insight and is this useless."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T15:46:47.017",
"Id": "247612",
"Score": "0",
"Tags": [
"go"
],
"Title": "Golang Error handling by a generic interface"
}
|
247612
|
<p>i get an array of authors from json response and i have to display authors name in TextView(android) in proper format like =>Viraj, Chetan and George R. R. Martin
my code work fine, but it's a mess....</p>
<pre><code>public class SeprateAuthors {
public static void main(String[] args) {
String[] authors0 = {"a", "b"};
String[] authors1 = {"a", "b", "c"};
String[] authors2 = {"a", "b", "c","d"};
String[] authors3 = {"a", "b", "c","d","e","f"};
System.out.println(displayAuthors(authors0));
System.out.println(displayAuthors(authors1));
System.out.println(displayAuthors(authors2));
System.out.println(displayAuthors(authors3));
}
public static String displayAuthors(String[] authors) {
StringBuilder stringBuilder = new StringBuilder();
String stringAuthors="";
String prefixComma = ", ";
String prefixAnd = " and ";
if ((authors != null) && (authors.length > 0)) {
for (int i = 0; i < authors.length; i++) {
if (i < authors.length - 2) {
stringBuilder.append(authors[i]).append(prefixComma);
} else {
stringBuilder.append(authors[i]).append(prefixAnd);
}
}
// Java Remove extra Characters("and ") from String
stringAuthors = stringBuilder.substring(0, stringBuilder.length() - 4);
}
return stringAuthors;
}
</code></pre>
<p>}</p>
|
[] |
[
{
"body": "<p>Welcome to Code Review, I have some hints about your code, starting from your <code>main</code> method:</p>\n<pre><code>public static void main(String[] args) {\n String[] authors0 = {"a", "b"};\n String[] authors1 = {"a", "b", "c"};\n String[] authors2 = {"a", "b", "c","d"};\n String[] authors3 = {"a", "b", "c","d","e","f"};\n \n System.out.println(displayAuthors(authors0));\n System.out.println(displayAuthors(authors1));\n System.out.println(displayAuthors(authors2));\n System.out.println(displayAuthors(authors3)); \n}\n</code></pre>\n<p>You have defined several arrays forcing the multiple print , you can obtain the same result defining an 2d array storing arrays of different dimensions like below :</p>\n<pre><code>public static void main(String[] args) {\n String[][] authors = { {"a"},\n {"a", "b"},\n {"a", "b", "c"},\n {"a", "b", "c","d"},\n {"a", "b", "c","d","e","f"}};\n \n for (String[] row : authors) {\n System.out.println(displayAuthors(row));\n } \n}\n</code></pre>\n<p>About the print of the authors array you can distinguish three cases :</p>\n<ol>\n<li>array with zero elements : you will print the <code>""</code> empty string.</li>\n<li>array with one element : you will print the unique element of the\narray.</li>\n<li>array with more than one element : you will print elements with <code>", "</code>\nas separator except for the penultimate element and the last one\nthat will be separated by <code>"and"</code>.</li>\n</ol>\n<p>You can rewrite your <code>displayAuthors</code> method in this way:</p>\n<pre><code>public static String displayAuthors(String[] authors) {\n if (authors == null) { return ""; }\n \n switch (authors.length) {\n case 0: return "";\n case 1: return authors[0];\n default: return helperDisplayAuthors(authors);\n }\n}\n</code></pre>\n<p>I defined a new method called <code>helperDisplayAuthors</code> :</p>\n<pre><code>private static String helperDisplayAuthors(String[] authors) {\n final int length = authors.length;\n String result = "";\n \n for (int i = 0; i < length - 2; ++i) {\n result += authors[i] + ", ";\n }\n \n return String.format("%s%s and %s", result, \n authors[length - 2], authors[length - 1]);\n }\n\n}\n\n</code></pre>\n<p>The method <code>String.format</code> helps you to compose the final string. Here the code of your class:</p>\n<pre><code>public class SeparateAuthors {\n\n public static void main(String[] args) {\n\n String[][] authors = {{"a"},\n {"a", "b"},\n {"a", "b", "c"},\n {"a", "b", "c", "d"},\n {"a", "b", "c", "d", "e", "f"}};\n\n for (String[] row : authors) {\n System.out.println(displayAuthors(row));\n }\n }\n \n public static String displayAuthors(String[] authors) {\n if (authors == null) { return ""; }\n \n switch (authors.length) {\n case 0: return "";\n case 1: return authors[0];\n default: return helperDisplayAuthors(authors);\n }\n }\n\n private static String helperDisplayAuthors(String[] authors) {\n final int length = authors.length;\n String result = "";\n \n for (int i = 0; i < length - 2; ++i) {\n result += authors[i] + ", ";\n }\n \n return String.format("%s%s and %s", result, \n authors[length - 2], authors[length - 1]); \n }\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-08T10:47:40.283",
"Id": "484859",
"Score": "0",
"body": "Are you sure that you want to use the inefficient `String + String` in your answer?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-08T12:23:58.993",
"Id": "484862",
"Score": "0",
"body": "@RolandIllig Hello, I decided to use it to simplify how the string is built without use of `StringBuilder` even loosing in performance, probably not the best choice considering OP already used `StringBuilder' in the proposed approach."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-08T08:07:39.693",
"Id": "247649",
"ParentId": "247615",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T17:01:38.223",
"Id": "247615",
"Score": "2",
"Tags": [
"java",
"strings",
"array"
],
"Title": "Add comma/and between string array in java"
}
|
247615
|
<pre><code>bool is_prime(int num)
{
if(num == 0 || num == 1 || (num != 2 && num % 2 == 0)
return false;
int sq = sqrt(num);
for(int i = 3; i <= sq; ++i, ++i)
if(num % i == 0)
return false;
return true;
}
</code></pre>
<p>We only need to check upto square root.
Proof -> <a href="https://math.stackexchange.com/questions/3783176/proof-that-if-one-divisor-is-smaller-than-square-root-of-the-dividend-then-othe">https://math.stackexchange.com/questions/3783176/proof-that-if-one-divisor-is-smaller-than-square-root-of-the-dividend-then-othe</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T17:56:55.570",
"Id": "484789",
"Score": "3",
"body": "Please tag your question with a programing language."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T18:07:07.237",
"Id": "484790",
"Score": "2",
"body": "Does not compile."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T18:24:03.230",
"Id": "484791",
"Score": "0",
"body": "What are the error messages? I don't have a computer right now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T19:13:36.373",
"Id": "484805",
"Score": "2",
"body": "You only need to test other primes.If you have a list of primes you can use that as your starting point."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T19:55:24.183",
"Id": "484809",
"Score": "0",
"body": "If you need to ask, then the answer is \"no\" :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T23:59:17.993",
"Id": "484830",
"Score": "0",
"body": "There are faster than `Θ(n)` methods to find all all primes up to `n`. So you can use such method to go over all primes up to `sqrt(n)` to check whether `n` is divisible by one of them. This makes an asymptomatically faster method than `Θ(sqrt(n))`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-08T10:50:33.543",
"Id": "484861",
"Score": "3",
"body": "Stop editing your code now that you have answers. This is against site policy."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-08T14:23:12.867",
"Id": "484864",
"Score": "0",
"body": "There is a logic bug that no one has seemed to mention, although @MartinYork 's answer removes the bug. Namely, `is_prime(-1)` would incorrectly return `true`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-08T16:15:33.377",
"Id": "484870",
"Score": "0",
"body": "Do we test negative integers for primality?!!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-09T13:31:45.007",
"Id": "484907",
"Score": "0",
"body": "QA engineer enters a bar, orders a beer. Orders -99999 beers. Orders a lizard. Orders a hzwxzyck... ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-09T13:37:38.260",
"Id": "484908",
"Score": "1",
"body": "Trying to make sense of the timeline here, looks like this specific question would be better off abandoned (& eventually cleaned-up); it's on hold for broken code but has answers that would be invalidated if the OP is edited to fix it now - simplest would be to make a new post, this time putting up code that is review-ready and working as intended (incorrectness in unexpected edge cases might still get pointed out by reviewers, but the idea is that your code works as intended to begin with), that way it's easier to avoid editing questions after they receive answers. Cheers!"
}
] |
[
{
"body": "<p>First of all, the indentation is weird following the first <code>return false;</code>, as well as some incorrect parentheses, which leads to the code being impossible to compile.</p>\n<p>You need to include cmath in order to have access to the <code>sqrt</code> function.</p>\n<p>You don't need two <code>++i</code>s in your for loop.</p>\n<p>You can group together the case that the number is even (and not a 2) at the end.</p>\n<p>Altogether, I came up with this example:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include<cmath>\nbool is_prime(int num)\n{\n if(num == 0 || num == 1)\n return false;\n if(num == 2)\n return true;\n int sq = sqrt(num);\n\n for(int i = 2; i <= sq; ++i)\n if(num % i == 0)\n return false;\n\n return true;\n}\n</code></pre>\n<p>And to answer your question, this is not the fastest way. You might want to do some research on</p>\n<ul>\n<li><a href=\"https://en.wikipedia.org/wiki/Primality_test#Fast_deterministic_tests\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Primality_test#Fast_deterministic_tests</a></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T18:26:26.807",
"Id": "484792",
"Score": "0",
"body": "@parv I can't comment on the original post (low reputation) but the error messages can be found here: [pastebin](https://pastebin.com/BLayh3x0) (the file was named test.cpp)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T18:55:34.457",
"Id": "484802",
"Score": "3",
"body": "If you see a comment indicating the question is off-topic or it might be better not to answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T18:59:43.740",
"Id": "484804",
"Score": "1",
"body": "Welcome to code review, you made some good observations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T19:22:56.413",
"Id": "484808",
"Score": "0",
"body": "@pacmaninbw Just to make sure, in the future, should I not improve dysfunctional code like this on Code Review?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T20:05:59.340",
"Id": "484811",
"Score": "3",
"body": "If it won't obviously compile, ignore it or put it in a comment. Be wary of questions that have a negative score. If you see a comment like Zeta's or mine don't answer. Other than that feel free to help improve code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-09T13:28:51.253",
"Id": "484906",
"Score": "0",
"body": "@EricChen it's a matter of scoping and single responsibility: each site on the network has a well-defined scope & purpose; questions involving coding issues and broken code should be asked as a \"minimal reproducible example\"; users that want to help others fix their code go to Stack Overflow. CR wants to see the real, working, review-ready code (would you submit a pull request with it?), see [A Guide to CR for SO users](https://codereview.meta.stackexchange.com/q/5777/23788) for all the details. Welcome aboard!"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T18:22:24.647",
"Id": "247618",
"ParentId": "247616",
"Score": "4"
}
},
{
"body": "<h2>Fix your indentation.</h2>\n<p>Your indentation is messed up.</p>\n<hr />\n<p>This is silly:</p>\n<pre><code>++i, ++i\n</code></pre>\n<p>Make it readable:</p>\n<pre><code>i += 2\n</code></pre>\n<hr />\n<p>You jump by two (as you know all even numbers, except 2, are not prime). But you can improve that by jumping by 2 or 4. This is because we know that all multiples of 2 and 3 are not prime and every third 2 lines up with every second 3 but this makes a pattern so you can jump by 2 then 4 then 2 then 4 etc.</p>\n<pre><code> bool isPrime(int val)\n {\n if (val == 2 || val == 3) {\n return true;\n }\n if (val < 2 || val % 2 == 0 || val % 3 == 0) {\n return false;\n }\n\n int sq = sqrt(val);\n int step = 4;\n for(int i = 5; i <= sq; i += step)\n {\n if (num % i == 0) {\n return false;\n }\n step = 6 - step;\n }\n return true;\n }\n</code></pre>\n<hr />\n<p>This is fine for small numbers. But once you start looking at large primes you need to use the "Sieve of Eratosthenes".</p>\n<p>Basically you don't need to try every number you just need to try all the primes below your number. So keep track of all the numbers you have thrown away (because they are multiples of a lower prime) and check those against your numbers.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T21:25:50.467",
"Id": "484817",
"Score": "0",
"body": "Have you missed division by 7?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-08T06:39:25.127",
"Id": "484842",
"Score": "0",
"body": "@bipll: No. Its subtle. `step = 4` outside the loop. The first iteration of the loop sets `step = 6 - step;` which makes `step = 2`. Now the increment operation kicks in. `i += step` => `i = i + step` => `i = 5 + 2`. So the second iteration is `i = 7`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-08T06:50:01.627",
"Id": "484844",
"Score": "1",
"body": "@anki: Fixed. :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-08T10:14:03.243",
"Id": "484858",
"Score": "0",
"body": "The constant flipping between 2 and 4 can also be solved using a step of 6. I've more commonly seen it expressed as: \\$6n-1\\$, \\$6n + 1\\$, \\$1 \\le n\\$."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-09T07:31:02.607",
"Id": "484893",
"Score": "0",
"body": "@MartinYork oh, sorry, I've missed it."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T19:23:01.093",
"Id": "247623",
"ParentId": "247616",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T17:15:36.897",
"Id": "247616",
"Score": "-3",
"Tags": [
"c++",
"primes"
],
"Title": "Is this the fastest way of testing the primality of a number"
}
|
247616
|
<p>I want to transform a UCI-move into bitboard.</p>
<p>for example a2a3 -> 32768, 8388608</p>
<p>I need to assign [7,6,...,0] to [a,b,...,h] so that for each letter i have the assigned number(n) to calculate 2^n</p>
<p>Which I can then left shift by the value in uci[1] or uci[3] *8 depending on start- or endfield.</p>
<p>This is my approach and it doesn't look very nice and redundant.</p>
<pre><code>def ucitoBit(uci):
if uci[0] == 'a':
mask1 = 2 ** 7
if uci[0] == 'b':
mask1 = 2 ** 6
if uci[0] == 'c':
mask1 = 2 ** 5
if uci[0] == 'd':
mask1 = 2 ** 4
if uci[0] == 'e':
mask1 = 2 ** 3
if uci[0] == 'f':
mask1 = 2 ** 2
if uci[0] == 'g':
mask1 = 2 ** 1
if uci[0] == 'h':
mask1 = 2 ** 0
mask1 = mask1 << 8 * (int(uci[1]) - 1)
if uci[2] == 'a':
mask2 = 2 ** 7
if uci[2] == 'b':
mask2 = 2 ** 6
if uci[2] == 'c':
mask2 = 2 ** 5
if uci[2] == 'd':
mask2 = 2 ** 4
if uci[2] == 'e':
mask2 = 2 ** 3
if uci[2] == 'f':
mask2 = 2 ** 2
if uci[2] == 'g':
mask2 = 2 ** 1
if uci[2] == 'h':
mask2 = 2 ** 0
mask2 = mask2 << 8 * (int(uci[3]) - 1)
bitstring = [np.uint64(mask1), np.uint64(mask2)]
return bitstring
</code></pre>
|
[] |
[
{
"body": "<h3>Option 1:</h3>\n<p>The most basic thing I can suggest is that if you have a <strong>mapping</strong> from one thing to another, and if that mapping is fixed, you should be using a mapping data type.</p>\n<p>The mapping data type in python is the <a href=\"https://docs.python.org/3/library/stdtypes.html?highlight=dict#mapping-types-dict\" rel=\"nofollow noreferrer\"><code>dict</code></a>, which can be written in-line like so:</p>\n<pre><code>uci_bit = {\n 'a': 2**7, 'b': 2**6, 'c': 2**5, 'd': 2**4,\n 'e': 2**3, 'f': 2**2, 'g': 2**1, 'h': 2**0,\n}\n</code></pre>\n<p>Alternatively, the <code>dict()</code> function returns a dictionary, and takes keyword arguments:</p>\n<pre><code>uci_bit = dict(a=2**7, b=2**6, c=2**5, d=2**4, \n e=2**3, f=2**2, g=2**1, h=2**0)\n</code></pre>\n<p>Same result either way. You could then access the dict using the standard square-bracket notation:</p>\n<pre><code>ch = uci[0]\nmask1 = uci_bit[ch]\n</code></pre>\n<p>Or as a single expression:</p>\n<pre><code>mask1 = uci_bit[uci[0]]\n</code></pre>\n<h3>Option 2:</h3>\n<p>However, there's another approach that has some potential. Looking things up in a dictionary has a cost. It's technically <span class=\"math-container\">\\$O(n)\\$</span> but maybe there's a constant or two in there. So ...</p>\n<p>Because the two components of the uci location are fixed-width ('a' and '2') you might be able to look them up in a string using the <a href=\"https://docs.python.org/3/library/stdtypes.html?highlight=str%20index#str.index\" rel=\"nofollow noreferrer\"><code>str.index</code></a> method and get better performance.</p>\n<p><strong>Note:</strong> I wrote "might be". The way to know for sure is to write both bits of code and run a timing test on the alternatives. Look up the <a href=\"https://docs.python.org/3/library/timeit.html?highlight=timeit#module-timeit\" rel=\"nofollow noreferrer\"><code>timeit</code></a> module in the standard distribution.</p>\n<p>Something like:</p>\n<pre><code>UCI_CHARS = 'hgfedcba'\n\nmask1 = 2 ** UCI_CHARS.index(uci[0])\nmask2 = 2 ** UCI_CHARS.index(uci[2])\n</code></pre>\n<p>You might also want to check the result of using <code>dict</code> versus <code>str.index</code> versus the <code>int()</code> function on the single-digit part of uci decoding.</p>\n<h3>Option 3:</h3>\n<p>It's not clear how many of these operations you are performing. If you are doing a single game, and there might be two dozen uci to bit operations, then it probably doesn't matter. But if you're doing a lot of games at the same time, it might behoove you to generate a dictionary containing <em>all</em> the UCI letter/number combinations, and do the lookup as a single operation. Something like:</p>\n<pre><code>for ch in 'abcdefgh':\n for digit in '12345678':\n uci = ch + digit\n bit = # whatever computation\n uci_bit[uci] = bit\n</code></pre>\n<p>This would let you decode 'a2' -> bits in a single step at the cost of the up-front loop.</p>\n<h3>Other considerations</h3>\n<p>I asked the Duck about bitboard, and was immediately presented with the fact that there is no single standard representation. Instead, there are different representations for different purposes and different CPU architectures.</p>\n<p>A result of this is that you should definitely be doing this inside a class or function, and there should definitely be a "name" given to the kind of bitboard you want to compute, so that readers will understand which of the several options you are choosing. Rank-major versus File-major and big- versus little- endian representations are all valid, so make sure to include this information either in the class or function name, or in the commentary.</p>\n<pre><code>def uci_to_bitboard_lsf(uci: str) -> int:\n """ Convert UCI notation to bitboard(LSF, little-endian) """\n\n ...\n</code></pre>\n<p>Also, I suspect that using <code>*</code> may be a bug, and you should be using <code>+</code> instead. (It really should be a bitwise or, the <code>|</code> operator, but <code>+</code> will work.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-08T00:31:24.343",
"Id": "484834",
"Score": "0",
"body": "There are only 64 combinations. Unless you are resource constrained, use option 3."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T18:44:49.290",
"Id": "247621",
"ParentId": "247617",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "247621",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T17:50:59.817",
"Id": "247617",
"Score": "4",
"Tags": [
"python",
"chess"
],
"Title": "Transforming UCI-move into bitboard, chess"
}
|
247617
|
An XML variant to be used with the JavaFX application framework for defining the user interface of a JavaFX application instead of using procedural code.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-07T18:25:35.680",
"Id": "247620",
"Score": "0",
"Tags": null,
"Title": null
}
|
247620
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.