body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I have integrate aad authentication using <a href="https://www.npmjs.com/package/react-adal" rel="nofollow noreferrer">react-adal</a> client and secure paths using private routes method</p>
<p>I'm not satisfied with the code structure so I would like to improve it.</p>
<p>Here's the code</p>
<p><strong>index.js</strong></p>
<pre><code>import { runWithAdal } from 'react-adal';
import { authContext } from './auth.js';
const DO_NOT_LOGIN = true;
runWithAdal(authContext, () => {
console.log("authcontext", authContext)
// eslint-disable-next-line
require('./indexApp.js');
}, DO_NOT_LOGIN);
</code></pre>
<p><strong>indexApp.js</strong></p>
<pre><code>import React from 'react';
...
import ReactDOM from 'react-dom';
import App from './App';
import {
BrowserRouter as Router,
Route,
} from "react-router-dom";
import Welcome from './components/WelcomeComponent/WelcomeComponent'
import PrivateRoute from './components/PrivateRouteComponent/PrivateRouteComponent'
ReactDOM.render(
<Router>
<React.StrictMode>
<ProviderNorth theme={teamsTheme}>
<Provider store={store}>
<PrivateRoute exact path="/" component={App}></PrivateRoute>
<Route exact path="/welcome" component={Welcome}>
</Route>
</Provider>
</ProviderNorth>
</React.StrictMode>
</Router>,
document.getElementById('root')
);
serviceWorker.unregister();
</code></pre>
<p>First as I'm making logging via a button is there a way to get rid of <code>indexApp</code> ? I tried to eliminate it but when I login, the <code>welcome</code>path does not redirect to <code>/</code> anymore and stays in <code>/welcome</code>.</p>
<p><strong>Welcome.js</strong></p>
<p>Here I check if user is loggedin first then redirect to <code>/</code> or not</p>
<pre><code>...
import { authContext } from '../../auth'
import {
Redirect,
} from "react-router-dom";
import React from 'react';
function Welcome(props) {
const isLogged = authContext.getCachedUser();
return (
isLogged === null ? (
<div>
<Header as="h1" content="Welcome to Heedify Reports Page" />
<Header as="h2" content="Login" />
<Flex gap="gap.smaller">
<Button content="Login" primary onClick={() => {
authContext.login().then(data => {
console.log("log in", data)
})
}} />
</Flex>
</div>) : <Redirect
to={{
pathname: "/"
}}
/>
)
}
export default Welcome
</code></pre>
<p><strong>PrivateRoute</strong></p>
<p>import React from 'react';
import {
Redirect,
Route,
} from "react-router-dom";
import { authContext } from '../../auth';</p>
<pre><code>const PrivateRoute = ({ component: Component, ...rest }) => {
return (
<Route
{...rest}
render={props => {
return authContext.getCachedUser() !== null ? (
<Component {...props} />
) : (
<Redirect
to={{
pathname: "/welcome"
}}
/>
)
}}></Route>)
}
export default PrivateRoute
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T00:54:11.380",
"Id": "250731",
"Score": "1",
"Tags": [
"javascript",
"react.js"
],
"Title": "React Private Routes implementation with adal"
}
|
250731
|
<p>I am a beginner at coding with Python. I am excited because I wrote a program that works in JupyterLab, but I know I can make it shorter. For example, I feel I should not need to write so many boolean operators, and print statements. Also, I am not sure if the break I put at the end is ideal. Can you advise me?</p>
<p>Purpose: This program computes and displays information for a company that leases vehicles to its customers. The program will compute and display the amount of money charged for that customer's vehicle rental for a specified customer. The program will run until Q or q is chosen to quit. The customer has two classification codes b or d and if any other code is entered, an error should appear but the program continues to run. Also, if the ending odometer reading is less than or equal to the starting odometer reading then an error should appear but the program continues to run.</p>
<pre><code>Name = str(input("Enter the customer's first and last name: "))
while True:
ClassCode = str(input("Enter the customer's classification code (b or d) or enter q to quit: "))
DaysRented = int(input("Enter the number of days the vehicle was rented: "))
Start_Odometer = int(input("Enter the vehicle's six-figure odometer reading at the start of the rental period: "))
End_Odometer = int(input("Enter the vehicle's six-figure odometer reading at the end of the rental period: "))
if End_Odometer <= Start_Odometer:
print()
print("\033[1m" + "Please enter an ending odometer reading greater than the starting odometer reading")
if ClassCode.upper() == "B" :
DaysCost = (DaysRented * 40)
DistanceCost = ((End_Odometer - Start_Odometer) * 0.25)
Bill = DaysCost + DistanceCost
FullClassCode = "Budget"
print()
print('\033[4m{}\033[0m'.format('Welcome to JDB Car Rental Service'))
print("Customer Bill (",(Name),")")
print()
print("\t\tClassification code is ",ClassCode,"(",FullClassCode,"):")
print("\t\tRented the vehicle for ", DaysRented,"days")
print("\t\tThe vehicle's odometer reading at the start of the rental period is: ",Start_Odometer)
print("\t\tThe vehicle's odometer reading at the end of the rental period is: ",End_Odometer)
print("\t\tThe number of miles driven during the rental period is: ",End_Odometer - Start_Odometer)
print("\t\tTotal summary for the rental period is: ", "($",DaysCost, " for ",DaysRented," days and $", DistanceCost, " for ", End_Odometer - Start_Odometer, " miles = $",Bill,")")
elif ClassCode.upper() == "D" and End_Odometer - Start_Odometer <= 150 :
DaysCost = (DaysRented * 60)
DistanceCost = 0
Bill = DaysCost + DistanceCost
FullClassCode = "Daily"
print()
print('\033[4m{}\033[0m'.format('Welcome to JDB Car Rental Service'))
print("Customer Bill (",(Name),")")
print()
print("\t\tClassification code is ",ClassCode,"(",FullClassCode,"):")
print("\t\tRented the vehicle for ", DaysRented,"days")
print("\t\tThe vehicle's odometer reading at the start of the rental period is: ",Start_Odometer)
print("\t\tThe vehicle's odometer reading at the end of the rental period is: ",End_Odometer)
print("\t\tThe number of miles driven during the rental period is: ",End_Odometer - Start_Odometer)
print("\t\tTotal summary for the rental period is: ", "($",DaysCost, " for ",DaysRented," days and $", DistanceCost, " for ", End_Odometer - Start_Odometer, " miles = $",Bill,")")
elif ClassCode.upper() == "D" and End_Odometer - Start_Odometer >= 150 :
DaysCost = (DaysRented * 60)
DistanceCost = (((End_Odometer - Start_Odometer) - 150) * 0.3)
Bill = DaysCost + DistanceCost
FullClassCode = "Daily"
print()
print('\033[4m{}\033[0m'.format('Welcome to JDB Car Rental Service'))
print("Customer Bill (",(Name),")")
print()
print("\t\tClassification code is ",ClassCode,"(",FullClassCode,"):")
print("\t\tRented the vehicle for ", DaysRented,"days")
print("\t\tThe vehicle's odometer reading at the start of the rental period is: ",Start_Odometer)
print("\t\tThe vehicle's odometer reading at the end of the rental period is: ",End_Odometer)
print("\t\tThe number of miles driven during the rental period is: ",End_Odometer - Start_Odometer)
print("\t\tTotal summary for the rental period is: ", "($",DaysCost, " for ",DaysRented," days and $", DistanceCost, " for ", End_Odometer - Start_Odometer, " miles = $",Bill,")")
elif ClassCode.upper() == "Q" :
break
elif ClassCode.upper() != "B" :
FullClassCode = "Error"
DaysCost = (DaysRented * 0)
DistanceCost = (((End_Odometer - Start_Odometer) - 150) * 0)
Bill = DaysCost + DistanceCost
print()
print()
print("\033[1m" + "Please enter b for Budget, d for Daily or q to Quit")
print()
print()
elif ClassCode.upper() != "D" :
FullClassCode = "Error"
DaysCost = (DaysRented * 0)
DistanceCost = (((End_Odometer - Start_Odometer) - 150) * 0)
Bill = DaysCost + DistanceCost
print()
print()
print("\033[1m" + "Please enter b for Budget, d for Daily or q to Quit")
print()
print()
elif ClassCode.upper() != "Q" :
FullClassCode = "Error"
DaysCost = (DaysRented * 0)
DistanceCost = (((End_Odometer - Start_Odometer) - 150) * 0)
Bill = DaysCost + DistanceCost
print()
print()
print("\033[1m" + "Please enter b for Budget, d for Daily or q to Quit")
print()
print()
else :
break
</code></pre>
<p><strong>Author: Peter Jr</strong></p>
|
[] |
[
{
"body": "<h3>Variable Name</h3>\n<p>From <a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"nofollow noreferrer\">PEP 8 -- Style Guide for Python Code</a></p>\n<blockquote>\n<p>Function names should be lowercase, with words separated by\nunderscores as necessary to improve readability.</p>\n<p>Variable names follow the same convention as function names.</p>\n<p>mixedCase is allowed only in contexts where that's already the\nprevailing style (e.g. threading.py), to retain backwards\ncompatibility.</p>\n</blockquote>\n<p>Variable names in your code, for example <code>ClassCode</code> should changed to <code>class_code</code></p>\n<h3>input() Function</h3>\n<p>The <code>input()</code> function return <code>string</code>, you don't need to user <code>str</code> to force convert it. <a href=\"https://docs.python.org/3/library/functions.html#input\" rel=\"nofollow noreferrer\">Here</a> is the doc</p>\n<p>But on the other hand, force convert to <code>int</code> is not safe, it might crash when user input something can't be converted to integer.</p>\n<p>You can use <code>try/except</code> to prevent it, or use <a href=\"https://docs.python.org/3/library/stdtypes.html#str\" rel=\"nofollow noreferrer\">str.isdigit()</a> to filter first</p>\n<pre class=\"lang-py prettyprint-override\"><code>days_rented = input("Enter the number of days the vehicle was rented: ")\n\n# use try/except\ntry:\n days_rented = int(days_rented)\nexcept:\n # Illegal input\n\n# use str.isdigit()\n\nif not days_rented.isdigit():\n # Illegal input\nelse:\n days_rented = int(days_rented)\n\n</code></pre>\n<h3>The if/else statement logic</h3>\nCodes in <code>elif ClassCode.upper() != "D" :</code> <code>elif ClassCode.upper() != "Q" :</code> and <code>else :</code> will never run as\n<pre class=\"lang-py prettyprint-override\"><code>if ClassCode.upper() == "B" :\n ...\nelif ClassCode.upper() != "B" :\n ...\n</code></pre>\n<p>already cover all conditions</p>\nAnd I guess this is also an illegal input statement, so you miss <code>continue</code> or <code>break</code>\n<pre><code>if End_Odometer <= Start_Odometer:\n print()\n print("\\033[1m" + "Please enter an ending odometer reading greater than the starting odometer reading")\n</code></pre>\nIn <code>elif ClassCode.upper() != "B"</code> part\n<pre class=\"lang-py prettyprint-override\"><code>FullClassCode = "Error"\nDaysCost = (DaysRented * 0)\nDistanceCost = (((End_Odometer - Start_Odometer) - 150) * 0) \nBill = DaysCost + DistanceCost\nprint()\nprint()\nprint("\\033[1m" + "Please enter b for Budget, d for Daily or q to Quit")\nprint()\nprint()\n</code></pre>\n<p>These variables have not be used: <code>FullClassCode</code>, <code>DaysCost</code>, <code>DistanceCost</code>, <code>Bill</code>, maybe just remove them.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T09:57:55.790",
"Id": "493239",
"Score": "0",
"body": "`except Exception` compared to `except`. try doing Cntl + C when using `excpetion`, it will catch that as an error"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T15:42:42.787",
"Id": "493291",
"Score": "4",
"body": "`isdigit` returns true for some cases generally not considered digits, and for which `int` raises an exception. One example is `str.isdigit(\"²\") == True`. `str.isdecimal` does not have this problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T22:09:26.040",
"Id": "493436",
"Score": "0",
"body": "Thank you everyone for your reply. I appreciate it a lot and I am grateful for the advice because I learned a lot."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T08:29:55.503",
"Id": "250742",
"ParentId": "250739",
"Score": "5"
}
},
{
"body": "<h1>About <code>print()</code></h1>\n<p>If you are trying to simply print a new line, you should use <code>'\\n'</code> compared to empty <code>print()</code> statements.</p>\n<pre class=\"lang-py prettyprint-override\"><code>print("Hello, World! \\n\\n")\n</code></pre>\n<p>The code will print <code>Hello, World!</code> followed by <strong>two newlines</strong> as I have printed <code>'\\n'</code> twice.</p>\n<h1>Converting <code>input()</code> to different data types</h1>\n<p>By default, the data taken by <code>input()</code> is in the string form, or <code>str()</code>. This means that</p>\n<pre class=\"lang-py prettyprint-override\"><code>name = str(input()) # is the same as name = input()\n</code></pre>\n<p>But in some situations, you might want to take an integer value like the age of someone, here you need to convert the input.</p>\n<pre class=\"lang-py prettyprint-override\"><code>age = int(input()) # is not equal to age = input()\n</code></pre>\n<p>All good, but what if the user enters a <em>string</em> by mistake? We can catch this error using <code>try</code> and <code>except</code>. <br><a href=\"https://www.w3schools.com/python/python_try_except.asp\" rel=\"noreferrer\">Try and Except in Python</a></p>\n<pre class=\"lang-py prettyprint-override\"><code>try:\n age = int(input())\nexcept Exception:\n print("Error! Invalid input for age")\n age = None\n</code></pre>\n<p>This is a safe method, ensures that your program won't give unexpected results if the user's input is wrong</p>\n<h1>Formatting strings</h1>\n<p>Use <a href=\"https://realpython.com/python-f-strings/\" rel=\"noreferrer\">f-strings</a> in Python 3 to format strings in the cleanest way.</p>\n<pre class=\"lang-py prettyprint-override\"><code>age = 14\nname = "Monkey"\n\nprint(f"Hey {name}, you are {age} years old!")\n</code></pre>\n<p>This way you can add multiple variables, without making your code look <em>strange</em></p>\n<h1>Logic 1</h1>\n<p>you are doing</p>\n<pre class=\"lang-py prettyprint-override\"><code>classcode = input("prompt..")\n\nif classcode.upper() == 'D':\n ...\nif classcode.upper() == 'B':\n ...\n</code></pre>\n<p>Instead of calling <code>.upper()</code> for every statement, why not just do it once during <code>input()</code>?</p>\n<pre class=\"lang-py prettyprint-override\"><code>classcode = input("prompt...").upper()\n\nif classcode == 'D':\n ...\nif classcode == 'B':\n ...\n</code></pre>\n<h1>Logic 2</h1>\n<p>If you have <code>EndOdometer</code> and <code>StartOdometer</code>, instead of doing <code>EndOdometer - StartOdometer</code> every time you would need distance, make a new variable called distance\nand assign it to <code>EndOdometer - StartOdometer</code>.</p>\n<h1>Use functions</h1>\n<p>The immediate requirement for this program is the use of <a href=\"https://www.w3schools.com/python/python_functions.asp\" rel=\"noreferrer\">functions</a>.</p>\n<blockquote>\n<p>A function is a block of code that only runs when it is called.</p>\n<p>You can pass data, known as parameters, into a function.</p>\n<p>A function can return data as a result.</p>\n</blockquote>\n<p>You need to split different tasks into respective functions so that your code is more readable to other people. Currently, there is only 1 huge segment where all the tasks take place</p>\n<ul>\n<li>Move taking input into a separate function, wich will ask the user for the start and end odometer readings and other information</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>def take_input():\n ... take input, the same as previous time\n return start_odometer, end_odometer, class_code, days_rented\n</code></pre>\n<p>This way in your main loop, it would look like</p>\n<pre class=\"lang-py prettyprint-override\"><code>start_odometer, end_odometer, class_code, days_rented = take_input()\n</code></pre>\n<p>The same applies to all other tasks, as the idea is only to split the work into separate functions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T22:09:15.077",
"Id": "493435",
"Score": "1",
"body": "Thank you everyone for your reply. I appreciate it a lot and I am grateful for the advice because I learned a lot."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T09:46:18.990",
"Id": "250744",
"ParentId": "250739",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "250744",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T06:54:58.183",
"Id": "250739",
"Score": "7",
"Tags": [
"python",
"beginner"
],
"Title": "A simple car leasing company"
}
|
250739
|
<p>I am trying to deal with some calculations on nested vector data in C++. The nested vector data may be like <code>std::vector<long double></code>, <code>std::vector<std::vector<long double>></code>, or <code>std::vector<std::vector<std::vector<long double>>></code>. I want to focus on summation here, and the calculation of summation could be done with the <code>Sum</code> function implemented here. Is there any possible improvement of this code?</p>
<p>The function declaration part is as below.</p>
<pre><code>template <class T>
static long double Sum(const std::vector<T> inputArray);
static long double Sum(long double inputNumber);
</code></pre>
<p>The function implementation part is as below.</p>
<pre><code>template<class T>
inline long double Sum(const std::vector<T> inputArray)
{
long double sumResult = 0.0;
for (auto& element : inputArray)
{
sumResult += Sum(element);
}
return sumResult;
}
inline long double Sum(long double inputNumber)
{
return inputNumber;
}
</code></pre>
<p>Test for this sum function:</p>
<pre class="lang-cpp prettyprint-override"><code>std::vector<long double> testVector1;
testVector1.push_back(1);
testVector1.push_back(1);
testVector1.push_back(1);
std::cout << std::to_string(Sum(testVector1)) + "\n";
std::vector<std::vector<long double>> testVector2;
testVector2.push_back(testVector1);
testVector2.push_back(testVector1);
testVector2.push_back(testVector1);
std::cout << std::to_string(Sum(testVector2)) + "\n";
std::vector<std::vector<std::vector<long double>>> testVector3;
testVector3.push_back(testVector2);
testVector3.push_back(testVector2);
testVector3.push_back(testVector2);
std::cout << std::to_string(Sum(testVector3)) + "\n";
</code></pre>
<p><strong>Oct 18, 2020 Update</strong></p>
<p>Reference:</p>
<ul>
<li><p>The follow-up question:</p>
<p><a href="https://codereview.stackexchange.com/q/250790/231235">A Summation Function For Various Type Arbitrary Nested Iterable Implementation in C++</a></p>
</li>
<li><p>The further implementation with c++-concepts:</p>
<p><a href="https://stackoverflow.com/q/64414869/6667035">https://stackoverflow.com/q/64414869/6667035</a></p>
</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T10:03:37.070",
"Id": "493240",
"Score": "1",
"body": "How is this template meta programming? please remove the tag"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T13:06:17.823",
"Id": "493260",
"Score": "2",
"body": "`long double` can be very inefficient on x86 and x86_64, since it will use the 80-bit floating point format, which doesn't fit in SSE registers and thus the compiler then cannot use SSE instructions. Also, what if `T` is a `std::complex<float>`? There are many types that you can sum but which don't convert to `long double`."
}
] |
[
{
"body": "<p>The template seems reasonable, although <code>inputArray</code> is a misnomer. However, there is a major drawback that can be remedied with a single <code>&</code>: <strong>use call-by-reference instead of call-by-value</strong> (see <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rf-in\" rel=\"noreferrer\">guidelines</a>):</p>\n<pre><code>template<class T>\ninline long double Sum(const std::vector<T> &inputArray)\n{ \n ...\n}\n</code></pre>\n<p>Other than that it's perfectly fine for summing arbitrary nested <code>std::vector<double></code>.</p>\n<p>That being said, there is some room for further experiments:</p>\n<ul>\n<li>enable <code>Sum</code> for anything that has <code>begin()</code> and <code>end()</code></li>\n<li>enable <code>Sum</code> for other types than <code>double</code> (e.g. <code>int</code>)</li>\n</ul>\n<p>Also, I'm a little bit concerned by the comment that declaration and definition were split. While it's possible, it's usually <em>not</em> intended.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T22:03:55.177",
"Id": "493326",
"Score": "0",
"body": "Thank you for answering. Is there any better suggestion about the naming to the input parameter of the template function `Sum` here? On the other hand, is it a good idea to enable `Sum` for other types by adding `inline int Sum(int inputNumber)`, `inline unsigned int Sum(unsigned int inputNumber)` and so on separately?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T07:51:14.530",
"Id": "493354",
"Score": "1",
"body": "@JimmyHu you could call it `numbers` instead of `inputArray`. But naming is hard. For your other question, you want to use SFINAE together with `enable_if` on `is_arithmetic`. A (poor) proof of concept can be found here: https://ideone.com/PLVF9E. However, I'm not that familiar with SFINAE. You probably want to tinker on that IDEONE code a little bit more and ask for another review if you want to use it in more serious projects or in production. (Especially since I didn't rename the input...)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T13:26:48.677",
"Id": "493386",
"Score": "0",
"body": "Thank you for providing the useful comments. I'm trying to figure out how's `template<class Container, typename = typename Container::value_type>` (in your example) work. I am not familiar with this usage. If there is any useful information please let me know."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T17:02:57.257",
"Id": "493404",
"Score": "1",
"body": "@JimmyHu that's SFINAE, as well as an anonymous second template parameter. `Container::value_type` \"only\" works on containers. `value_type` is a type, but the compiler needs an additional `typename` here, thus `typename Container::value_type`. The last `typename = ` is an anonymous template parameter. I could also write `template <class C, class V = typename C::value_type>`. If the `C::value_type` substitution fails, we don't get a compiler error (that's the SFINAE part), but instead another template is considered, in this case the one `is_arithmetic`."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T12:08:40.403",
"Id": "250749",
"ParentId": "250743",
"Score": "5"
}
},
{
"body": "<p>I'd suggest a more generic approach:</p>\n<pre><code>template<typename T, typename = void>\nstruct is_container : std::false_type {};\n\ntemplate<typename T>\nstruct is_container<T,\n std::void_t<decltype(std::declval<T>().begin()),\n decltype(std::declval<T>().end()),\n typename T::value_type\n >> : std::true_type {\n};\n\n// empty\nconstexpr long double Sum() {\n return 0.0;\n}\n\n// a number (arithmetic)\ntemplate<typename T, typename std::enable_if<std::is_arithmetic<T>::value, T>::type* = nullptr>\nconstexpr long double Sum(const T& item) {\n return item;\n}\n\n// container\ntemplate<typename Container,\n typename std::enable_if<is_container<Container>::value, Container>::type* = nullptr>\nconstexpr long double Sum(const Container& container) {\n return std::accumulate(container.begin(), container.end(), Sum(), [](auto&& sum, const auto& item) {\n return sum + Sum(item);\n });\n}\n\n// tuple\ntemplate<typename...Args>\nconstexpr long double Sum(const std::tuple<Args...>& tuple) {\n return std::apply([](const auto& ... values) {\n return (Sum(values) + ...);\n }, tuple);\n}\n\n// 2 or more args\ntemplate<typename T1, typename T2, typename ... Args>\nconstexpr long double Sum(const T1& item1, const T2& item2, const Args& ...args) {\n return Sum(item1) + Sum(item2) + (Sum(args) + ...);\n}\n</code></pre>\n<p>Then you can do something like this:</p>\n<pre><code>int main() {\n std::array a{ 0.1, 0.2, 0.3 };\n std::vector v{ 0.4, 0.5, 0.6 };\n std::list l{ 0.7, 0.8, 0.9 };\n std::vector vv{\n std::vector{ 0.0, 0.1, 0.2 },\n std::vector{ 1.0, 2.1, 2.2 },\n std::vector{ 2.0, 2.1, 2.2 },\n };\n std::vector vvv{ std::vector{ std::vector{ 3.0, 3.1, 3.2 }}};\n std::tuple t{ .1, 42, unsigned(1), 'c', std::vector{ 4.0, 4.1, 4.2, 4.3 }};\n std::cout << Sum(.1, 42, l, a, v, vv, vvv, t) << "\\n";\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T14:26:40.713",
"Id": "493490",
"Score": "0",
"body": "Thank you for your answer. The example of usage you provided in `main` is impressive. However, it seems to be still hard to deal with `std::complex`. I am trying to dig into new solution with C++20's concepts. The further info is at https://codereview.stackexchange.com/a/250792/231235"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T17:54:11.587",
"Id": "493508",
"Score": "3",
"body": "You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T13:47:51.393",
"Id": "250832",
"ParentId": "250743",
"Score": "0"
}
},
{
"body": "<p>As @Zeta pointed out, to enable nested sum for other scalar types, a possible implementation of <code>Sum</code> could be:</p>\n<pre><code>#include <iostream>\n#include <vector>\n\ntemplate <typename T>\ninline void Sum(const T &inputArrayElement, T &runningSum) {\n runningSum += inputArrayElement;\n}\n\ntemplate <typename T, typename U>\ninline void Sum(const T &inputArray, U &runningSum) {\n for (const auto &element : inputArray) {\n Sum(element, runningSum);\n }\n}\n</code></pre>\n<p>Test example</p>\n<pre><code>std::vector<std::vector<std::vector<double>>> v = {{{1.0, 3.0}, {2.0}},\n {{2.0}, {3.0}}};\n\ndouble sum = 0.0;\nSum(v, sum);\n\nstd::cout << sum << std::endl;\n</code></pre>\n<p>There might be other ways of doing this using type comparison as discussed <a href=\"https://stackoverflow.com/questions/11861610/decltype-comparison\">here</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T19:54:55.377",
"Id": "493612",
"Score": "1",
"body": "As Mast said on the other answer: You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process. This will also prevent downvotes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T05:34:28.810",
"Id": "493656",
"Score": "0",
"body": "@Zeta. The only improvement I had thought about was using const& instead of const (which you had already pointed out in your answer). My solution was an example of templatizing the scalar type. I didn't give details of scalar type deduction since it was discussed in a more general manner in the stackoverflow link I had included."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T03:24:33.210",
"Id": "250854",
"ParentId": "250743",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "250749",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T09:33:35.610",
"Id": "250743",
"Score": "7",
"Tags": [
"c++",
"recursion"
],
"Title": "A Summation Function For Arbitrary Nested Vector Implementation In C++"
}
|
250743
|
<p>I have this task where I have to make my robot find the shortest way when I enter a destination point. I've created some functions to assign numbers (distances) for each square and counts its way back to my robot by deleting the other options. Then the robot should only follow the numbers. Here's also a screenshot of the map it navigates in:</p>
<p><img src="https://i.stack.imgur.com/ZzM52.jpg" alt="Here's also a screenshot of the map it navigates in:
" /></p>
<p>My code works so far, however I think I should be able to reach the same outcome by using less for loops and with a more efficient writing. I believe if I see different ways of thinking in my earlier stages, I can have a broader perspective in the future. So, any ideas on how to reach my goal with a shorter code?</p>
<pre><code>#Your Code Starts Here
"""
for x in range(0, map.width):
for y in range(0, map.height):
if map.blocked(x, y):
map.value[x, y] = -1
else:
map.value[x, y] = 0
"""
def fill_around(n,m,number):
for x in range (n-1,n+2):
for y in range (m-1,m+2):
if map.value[x,y] != 0:
pass
elif x==n+1 and y==m+1 or x==n-1 and y==m-1 or x==n-1 and y==m+1 or x==n+1 and y==m-1:
pass
elif map.blocked(x,y) == True:
map.value[x,y]= -1
elif x==n and y==m:
map.value[x,y]= number
else:
map.value[x,y]= number+1
def till_final(final_x,final_y):
final_x=9
final_y=1
fill_around(1,1,1)
for p in range(2,17):
for k in range(0, map.width):
for l in range(0, map.height):
if map.value[final_x,final_y] ==0 and map.value[k,l]==p:
fill_around(k,l,p)
def delete_duplicates(final_x,final_y):
for k in range(0, map.width):
for l in range(0, map.height):
if map.value[k,l] == map.value[final_x,final_y] and k != final_x and l != final_y:
map.value[k,l] = 0
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T12:28:53.630",
"Id": "493258",
"Score": "1",
"body": "Please fix your indentation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T13:26:09.523",
"Id": "493262",
"Score": "0",
"body": "Indentation is very important in Python. I've attempted a fix. Please double-check that this is indeed the code you have locally."
}
] |
[
{
"body": "<h2><code>if</code> structure</h2>\n<pre><code> if map.value[x,y] != 0:\n pass\n elif x==n+1 and y==m+1 or x==n-1 and y==m-1 or x==n-1 and y==m+1 or x==n+1 and y==m-1:\n pass\n elif map.blocked(x,y) == True:\n map.value[x,y]= -1 \n elif x==n and y==m:\n map.value[x,y]= number\n else:\n map.value[x,y]= number+1\n</code></pre>\n<p>is a little awkward. Rephrase <code>if; pass</code> into <code>if not</code>, delete <code>== True</code> since it's redundant, and you have:</p>\n<pre><code>if map.value[x, y] == 0 and not (\n (x==n+1 or x==n-1) and \n (y==m+1 or y==m-1)\n): \n if map.blocked(x, y):\n map.value[x, y] = -1 \n elif x == n and y == m:\n map.value[x, y] = number\n else:\n map.value[x, y] = number + 1\n</code></pre>\n<p>You can further simplify by checking for coordinate difference in a set membership operation, though I haven't tested its performance:</p>\n<pre><code>if map.value[x, y] == 0 and not (\n {x - n, y - m} <= {-1, 1}\n): \n # ...\n</code></pre>\n<h2>General</h2>\n<p>You have heavily nested loops that iterate over a matrix-like structure. That's a job for <code>numpy</code>. Vectorization may or may not make your code shorter, but it will definitely speed it up.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T14:11:12.350",
"Id": "250752",
"ParentId": "250748",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T11:12:19.717",
"Id": "250748",
"Score": "4",
"Tags": [
"python",
"pathfinding"
],
"Title": "Navigating the robot by finding the shortest way"
}
|
250748
|
<p>This is a problem from Hackerrank (<a href="https://www.hackerrank.com/challenges/2d-array/problem" rel="nofollow noreferrer">https://www.hackerrank.com/challenges/2d-array/problem</a>). We're given a 6x6 (always) 2D array and asked to compute the sums of all the hourglass patterns in the array. An hourglass pattern is of the shape</p>
<pre><code>1 1 1
1
1 1 1
</code></pre>
<p>where the 1's form the hourglass. In this case the sum is 7, but it could be any integer from -63 to 63, the constraints being: <code>-9 <= arr[i][j] <= 9</code>. There are 16 hourglasses in each 6x6 2D array, and we're asked to return the greatest hourglass value.</p>
<p>As an example, the following 2D array has a maximum hourglass value of 28:</p>
<pre><code>-9 -9 -9 1 1 1
0 -9 0 4 3 2
-9 -9 -9 1 2 3
0 0 8 6 6 0
0 0 0 -2 0 0
0 0 1 2 4 0
</code></pre>
<p><strong>My code</strong>:</p>
<pre><code>def hourglassSum(arr):
max_hourglass = -63
for column in range(len(arr)-2):
for row in range(len(arr)-2):
max_hourglass = max(arr[row][column] + arr[row][column+1] + arr[row][column+2] \
+ arr[row+1][column+1] + arr[row+2][column] + arr[row+2][column+1] \
+ arr[row+2][column+2], max_hourglass)
return max_hourglass
</code></pre>
<p>Is there any way to make this faster / more efficient? I'm reusing a lot of the same numbers in my calculations, which seems wasteful; is there a dynamic programming solution I'm not seeing, anything else? I appreciate any comments or optimization opportunities on my code, thank you.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T18:33:39.567",
"Id": "493311",
"Score": "3",
"body": "Please add a link to the original Hackerrank problem."
}
] |
[
{
"body": "<p>Drat. My super pretty NumPy solution which is probably efficient doesn't get accepted because HackerRank apparently doesn't support NumPy here. Oh well, here it is anyway, maybe interesting/amusing for someone.</p>\n<pre><code>import sys\nimport numpy as np\n\na = np.loadtxt(sys.stdin, dtype=np.int8)\n\nh = a[0:4, 0:4] + a[0:4, 1:5] + a[0:4, 2:6] + \\\n a[1:5, 1:5] + \\\n a[2:6, 0:4] + a[2:6, 1:5] + a[2:6, 2:6]\n\nprint(h.max())\n</code></pre>\n<p>Or with less code repetition:</p>\n<pre><code>import sys\nimport numpy as np\n\na = np.loadtxt(sys.stdin, dtype=np.int8)\n\ni, j, k = (slice(i, i+4) for i in range(3))\n\nh = a[i,i] + a[i,j] + a[i,k] + \\\n a[j,j] + \\\n a[k,i] + a[k,j] + a[k,k]\n\nprint(h.max())\n</code></pre>\n<p>The 4x4 submatrix <code>a[0:4, 0:4]</code> contains the top-left value for each of the 16 hourglasses, <code>a[0:4, 1:5]</code> contains the top-<em>middle</em> value for each of the 16 hourglasses, etc. So adding them computes a 4x4 matrix containing the 16 hourglass sums.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T19:15:46.980",
"Id": "493314",
"Score": "1",
"body": "@Emma LeetCode does, and HackerRank does have a [NumPy section](https://www.hackerrank.com/domains/python/numpy/page/1)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T20:27:57.153",
"Id": "493321",
"Score": "1",
"body": "Could you explain what it's doing? Does numpy loop automatically over the entire matrix?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T01:25:33.970",
"Id": "493336",
"Score": "1",
"body": "@jeremyradcliff Kinda, yes. I mean, `a[0:4, 0:4]` for example is the top-left 4x4 submatrix. That holds the top-left value for each of the 16 hourglasses. And `a[0:4, 1:5]` holds the top-middle value for each of the 16 hourglasses. And so on. What I do is I get those seven 4x4 submatrices and have NumPy add them for me (NumPy does the looping required for that). So I'm building all 16 hourglass sums at the same time, at NumPy speed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T21:31:16.133",
"Id": "493434",
"Score": "0",
"body": "That's incredible. Thanks for explaining, I'm going to play with it today and try to integrate it"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T18:52:35.923",
"Id": "250758",
"ParentId": "250755",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "250758",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T17:45:11.387",
"Id": "250755",
"Score": "7",
"Tags": [
"python",
"algorithm",
"array",
"matrix"
],
"Title": "Computing sums of weird pattern in 2D array as efficiently as possible"
}
|
250755
|
<p>I'm a beginner developer and I'm building a calendar for smartphones. I'm using <strong>HTML, CSS and JS.</strong> I'm not entirely done with the project yet, however, I have the feeling that I'm making a <strong>messy</strong> code. I'll be posting the link to the git + the code in here, so you can better read it/clone, and help me with design patterns, etc...</p>
<p>P.S.: The project was developed using the <strong>IPhoneX resolution</strong> (375 x 812). It is not responsive yet, so <strong>I would recommend running the code using the resolution above.</strong></p>
<p><strong>Git link:</strong> <a href="https://github.com/LucasBiazi/Mobile_Calendar_HTML_CSS_JS" rel="nofollow noreferrer">https://github.com/LucasBiazi/Mobile_Calendar_HTML_CSS_JS</a></p>
<h3>HTML:</h3>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Calendar</title>
<script src="../script/script.js"></script>
<link rel="stylesheet" href="../css/style.css" />
</head>
<!-- As soon as the page loads, fulfills the table. -->
<body onload="load_DB(new Date().getFullYear(), new Date().getMonth())">
<div class="main">
<div class="title">
<span class="year_title" id="year_title"></span>
<span class="month_title" id="month_title"></span>
</div>
<div class="calendar">
<div id="month_days" class="month_days">
<table id="days">
<tr>
<th style="color: lightsalmon">Sun</th>
<th class="even">Mon</th>
<th>Tue</th>
<th class="even">Wed</th>
<th>Thu</th>
<th class="even">Fri</th>
<th style="color: lightsalmon">Sat</th>
</tr>
</table>
</div>
<!-- Future implementations. -->
<div class="data">
<div class="data_content">
<p style="color: black; font-size: 20px">No content.</p>
</div>
</div>
</div>
<div class="buttons">
<!-- Reteats a month. -->
<button
style="
animation: display_button_back 1s ease;
position: relative;
"
onclick="retreat_month(parseInt(document.getElementById('year_title').textContent),
identify_month(document.getElementById('month_title').textContent))"
>
<img
src="../../media/left-arrow-line-symbol.svg"
style="width: 35px; height: 35px"
alt="back"
/>
</button>
<!-- Shows current month. -->
<button
style="animation: display_opacity_zoom 1s ease-out;"
onclick="advance_month(new Date().getFullYear(), new Date().getMonth() - 1)"
>
T
</button>
<!-- Advances a month. -->
<button
style="
animation: display_button_next 1s ease;
position: relative;
"
onclick="advance_month(parseInt(document.getElementById('year_title').textContent),
identify_month(document.getElementById('month_title').textContent))"
>
<img
src="../../media/right-arrow-angle.svg"
style="width: 35px; height: 35px"
alt="next"
/>
</button>
</div>
</div>
</body>
</html>
</code></pre>
<h3>CSS:</h3>
<pre><code>* {
padding: 0px;
margin: 0px;
font-family: Verdana, Geneva, Tahoma, sans-serif;
font-weight: lighter;
}
body {
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
background-image: url(../../media/grass.jpg);
/* Blurring the background. Applies behind the element... */
backdrop-filter: blur(9px);
background-size: cover;
}
@keyframes display_data {
0% {
transform: scale3d(0.25, 0, 1);
}
25% {
transform: scale3d(0.5, 0, 1);
}
50% {
transform: scale3d(0.1, 0, 1);
}
75% {
transform: scale3d(0.1, 1.2, 1);
}
100% {
transform: scale3d(1, 1, 1);
}
}
@keyframes display_month_days {
from {
opacity: 0%;
}
to {
opacity: 100%;
}
}
@keyframes display_button_back {
0% {
right: 25px;
transform: scale3d(0.75, 0.75, 1);
}
100% {
right: 0px;
transform: scale3d(1, 1, 1);
}
}
@keyframes display_button_next {
0% {
left: 25px;
transform: scale3d(0.75, 0.75, 1);
}
100% {
left: 0px;
transform: scale3d(1, 1, 1);
}
}
@keyframes display_opacity_zoom {
from {
opacity: 0%;
transform: scale3d(0.5, 0.5, 1);
}
to {
opacity: 100%;
transform: scale3d(1, 1, 1);
}
}
.main {
width: 100vw;
height: 100vh;
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: flex-start;
color: white;
background-color: rgba(0, 0, 0, 0.65);
}
.title {
margin-top: 7%;
height: 80px;
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-evenly;
animation: display_opacity_zoom 1s ease-out;
}
.year_title {
margin-left: 5px;
font-size: 40px;
letter-spacing: 5px;
color: lightsalmon;
text-align: center;
}
.month_title {
margin-left: 15px;
font-size: 25px;
letter-spacing: 15px;
text-align: center;
}
.calendar {
height: 75%;
width: 100%;
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: center;
}
.month_days {
margin-top: 10px;
width: 100%;
height: 50%;
animation: display_month_days 1s ease-in-out;
}
table {
margin-top: 20px;
width: 100%;
font-size: 22px;
}
tr,
th,
td {
background-color: none;
}
th {
width: 14%;
text-align: center;
color: white;
}
td {
width: 2.38em;
height: 2.38em;
color: white;
text-align: center;
border-radius: 50%;
}
td:hover {
background-color: black;
}
.data {
display: flex;
justify-content: center;
align-items: center;
width: 95%;
height: 30%;
background-color: rgba(255, 255, 255, 0.9);
border: none;
border-radius: 5px;
animation: display_data 0.8s ease;
}
.data_content {
width: 95%;
height: 95%;
}
.other_month {
background: none;
color: rgba(175, 175, 175, 0.45);
}
.buttons {
width: 100vw;
height: 70px;
display: flex;
justify-content: space-around;
align-items: flex-start;
}
button {
width: 60px;
height: 60px;
display: flex;
justify-content: center;
align-items: center;
background: none;
border: none;
font-size: 35px;
font-weight: 400;
color: white;
}
</code></pre>
<h3>JS:</h3>
<pre><code>// Returns the day of the week in which the month starts.
starting_day = (year, month) => new Date(year, month, 1).getDay();
// Returns the amount of days in a month.
total_month_days = (year, month) => new Date(year, month + 1, 0).getDate();
// Set the background color of the cell that contains today's day.
function is_today(months, cell) {
if (
new Date().getFullYear() ==
parseInt(document.getElementById("year_title").textContent) &&
months[new Date().getMonth()].month ==
document.getElementById("month_title").textContent &&
cell.textContent == new Date().getDate()
) {
cell.style.background = "rgba(255, 160, 122, 0.8)";
}
}
// Changes color if it is a weekend.
color_weekend = (let_value, cell) => {
if (let_value == 6 || let_value == 0) cell.style.color = "lightsalmon";
};
// Populates the DB.
function load_DB(year, month) {
let counter = 1;
const table = document.getElementById("days");
const date_object = new Date(year, month);
// Array containing months names, starting_day()_+ total_month_days().
const months = [
{
// Month 0
month: "January",
first_day: starting_day(date_object.getFullYear(), 0),
days: Array(total_month_days(date_object.getFullYear(), 0)),
},
{
// Month 1
month: "February",
first_day: starting_day(date_object.getFullYear(), 1),
days: Array(total_month_days(date_object.getFullYear(), 1)),
},
{
// Month 2
month: "March",
first_day: starting_day(date_object.getFullYear(), 2),
days: Array(total_month_days(date_object.getFullYear(), 2)),
},
{
// Month 3
month: "April",
first_day: starting_day(date_object.getFullYear(), 3),
days: Array(total_month_days(date_object.getFullYear(), 3)),
},
{
// Month 4
month: "May",
first_day: starting_day(date_object.getFullYear(), 4),
days: Array(total_month_days(date_object.getFullYear(), 4)),
},
{
// Month 5
month: "June",
first_day: starting_day(date_object.getFullYear(), 5),
days: Array(total_month_days(date_object.getFullYear(), 5)),
},
{
// Month 6
month: "July",
first_day: starting_day(date_object.getFullYear(), 6),
days: Array(total_month_days(date_object.getFullYear(), 6)),
},
{
// Month 7
month: "August",
first_day: starting_day(date_object.getFullYear(), 7),
days: Array(total_month_days(date_object.getFullYear(), 7)),
},
{
// Month 8
month: "September",
first_day: starting_day(date_object.getFullYear(), 8),
days: Array(total_month_days(date_object.getFullYear(), 8)),
},
{
// Month 9
month: "October",
first_day: starting_day(date_object.getFullYear(), 9),
days: Array(total_month_days(date_object.getFullYear(), 9)),
},
{
// Month 10
month: "November",
first_day: starting_day(date_object.getFullYear(), 10),
days: Array(total_month_days(date_object.getFullYear(), 10)),
},
{
// Month 11
month: "December",
first_day: starting_day(date_object.getFullYear(), 11),
days: Array(total_month_days(date_object.getFullYear(), 11)),
},
];
// Prints the name of the current month and year.
document.getElementById("year_title").textContent = date_object.getFullYear();
document.getElementById("month_title").textContent =
months[date_object.getMonth()].month;
// Month days that will appear in the first row.
const number_of_cells_in_the_first_row =
7 - months[date_object.getMonth()].first_day;
// Month days that will appear after the first row.
let normal_days = number_of_cells_in_the_first_row + 1;
// Creates + populates the 5 last rows.
for (let r = 0; r < 5; r++) {
let row = table.insertRow(r + 1);
let cell;
// Creates + populates 7 cells in each row.
for (let x = 0; x < 7; x++) {
cell = row.insertCell(x);
cell.textContent = normal_days;
is_today(months, cell);
color_weekend(x, cell);
normal_days++;
// Filling the rest of the table with the days of the next month(gray days).
if (normal_days > months[date_object.getMonth()].days.length + 1) {
// Next month days are always lowlighted.
if (x == 6 || x == 0) cell.style.color = "rgba(175, 175, 175, 0.45)";
cell.textContent = counter++;
cell.className = "other_month";
}
}
}
// Creates + populates the 1 row.
for (let i = 0; i < 1; i++) {
let row = table.insertRow(i + 1);
let cell;
let number_of_blank_cells = 7 - number_of_cells_in_the_first_row;
// Populates it.
for (let y = 0; y < number_of_cells_in_the_first_row; y++) {
cell = row.insertCell(0);
cell.textContent = number_of_cells_in_the_first_row - y;
is_today(months, cell);
color_weekend(y, cell);
}
// Filling the rest of the table (next month days).
for (let w = 0; w < number_of_blank_cells; w++) {
cell = row.insertCell(0);
if (months[date_object.getMonth() - 1]) {
cell.textContent = months[date_object.getMonth() - 1].days.length--;
cell.className = "other_month";
} else {
cell.textContent = months[date_object.getMonth() + 11].days.length--;
cell.className = "other_month";
}
}
}
}
// Converts the month name to the month number (January = 0).
function identify_month(string) {
const all_months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
let i = 0;
while (string != all_months[i]) {
i++;
}
return i;
}
// Advancecs a month.
function advance_month(year, month) {
// Cleaning table.
const table = document.getElementById("days");
for (let i = 0; i < 6; i++) {
table.deleteRow(1);
}
// Add new data.
month++;
load_DB(year, month);
}
// Retreats a month.
function retreat_month(year, month) {
// Cleaning table.
const table = document.getElementById("days");
for (let i = 0; i < 6; i++) {
table.deleteRow(1);
}
month--; // Add new data.
load_DB(year, month);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T19:43:10.527",
"Id": "493319",
"Score": "1",
"body": "Welcome to the Code Review Site, it is best to wait until the code is finished, but we can help with this. Remember not to change any part of the question after you have an answer."
}
] |
[
{
"body": "<h1>Variables</h1>\n<p>Always use a variable declaration when first declaring your variable. <a href=\"https://stackoverflow.com/questions/6888570/declaring-variables-without-var-keyword\">If you don't your variable will be put into the global scope</a>, which is almost never what you want. It also makes it more clear that you don't want to re-assign to an already existing global variable.</p>\n<p>So for <code>starting_day</code>, for example, put a <code>var</code>, <code>let</code>, or <code>const</code> in front of it.</p>\n<h1>HTML Attributes</h1>\n<p>Instead of using attributes like <code>onclick</code> or <code>onload</code> to do event handling (these are also known as inline handlers), it is generally considered best practice to handle these events in your JavaScript itself. It helps to separate your HTML/JavaScript.</p>\n<p>For example, to replace the <code>onload</code> attribute, you could instead use the following JS function:</p>\n<pre><code>function ready(func) {\n if (document.readyState !== 'loading') {\n func();\n } else {\n document.addEventListener('DOMContentLoaded', func);\n }\n}\n</code></pre>\n<p>You could declare a function called <code>main</code> for example, where you would put any code that you want to run when the DOM is ready to be worked with, and then call <code>ready(main);</code>.</p>\n<p>To replace the <code>onclick</code> attributes, you should add some CSS classes/ids to them to be used as selectors in the JavaScript code. You would then select them using something like <code>const backButton = document.querySelector('calendarBack');</code>. Then, you can <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener\" rel=\"noreferrer\">attach an event listener</a> to that element like so:</p>\n<pre><code>backButton.addEventListener("click", () => {\n // The code you want to run when the button is clicked goes here\n});\n</code></pre>\n<h1>Code Refactorings</h1>\n<h2><code>months</code></h2>\n<p>The <code>months</code> variable declaration is rather repetitive and there is only one thing changing for each month, the 'index' of it. This makes it a perfect candidate to roll into a loop/array map.</p>\n<p>I would do it like this using the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map\" rel=\"noreferrer\"><code>map</code> function</a>:</p>\n<pre><code>// This would ideally not be in load_DB but be a top level declaration, since you could then reference this again in the identify_month function instead of rewriting the months\nconst monthNames = [\n "January",\n "February",\n "March",\n "April",\n "May",\n "June",\n "July",\n "August",\n "September",\n "October",\n "November",\n "December",\n];\n\n// Saving this in a variable for brevity and since it doesn't change\nconst fullYear = date_object.getFullYear();\n\nconst months = monthNames.map((monthName, index) => {\n return {\n month: monthName,\n first_day: starting_day(fullYear, index),\n days: Array(total_month_days(fullYear, index)),\n };\n});\n</code></pre>\n<p>One thing that I'm not sure of is the <code>days</code> property and why it is an array to begin with. The only places it is being referenced in code is to check its length. Is this part of the unfinished code that you mentioned? If it isn't, then I would just replace the line with days: <code>Array(total_month_days(fullYear, index)),</code> instead.</p>\n<h2><code>identify_month</code></h2>\n<p>The original implementation of this function should work, although it is a long way of saying "get the index of the month from the <code>monthNames</code> array".</p>\n<p>Here is how I would rewrite it:</p>\n<pre><code>// Converts the month name to the month number (January = 0).\nfunction identify_month(string) {\n return monthNames.indexOf(string);\n}\n</code></pre>\n<h2>Current month code</h2>\n<p>The original code is rather hard to read because of the repeated lookups of the month object found in the <code>months</code> array. Place them into a variable to improve readability and remove unneeded additional array accesses.</p>\n<pre><code>const currentMonth = date_object.getMonth();\n\nconst currentMonthObj = months[currentMonth];\n\n// Prints the name of the current month and year.\ndocument.getElementById("year_title").textContent = fullYear;\ndocument.getElementById("month_title").textContent = currentMonthObj.month;\n\n// Month days that will appear in the first row.\nconst number_of_cells_in_the_first_row = 7 - currentMonthObj.first_day;\n</code></pre>\n<p>I will try to come back and add some more thoughts later :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T21:42:39.673",
"Id": "250765",
"ParentId": "250759",
"Score": "6"
}
},
{
"body": "<p>Welcome to Code Review. The CSS looks quite good. I haven’t seen too many style sheets with color <code>lightsalmon</code> . Below are some suggestions.</p>\n<h2>Cache DOM references</h2>\n<p><a href=\"https://i.stack.imgur.com/ybMID.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ybMID.jpg\" alt=\"bridge toll\" /></a></p>\n<blockquote>\n<p><em>”...DOM access is actually pretty costly - I think of it like if I have a bridge - like two pieces of land with a toll bridge, and the JavaScript engine is on one side, and the DOM is on the other, and every time I want to access the DOM from the JavaScript engine, I have to pay that toll”</em><br>\n - John Hrvatin, Microsoft, MIX09, in <a href=\"https://channel9.msdn.com/Events/MIX/MIX09/T53F\" rel=\"nofollow noreferrer\">this talk <em>Building High Performance Web Applications and Sites</em></a> at 29:38, also cited in the <a href=\"https://books.google.com/books?id=ED6ph4WEIoQC&pg=PA36&lpg=PA36&dq=John+Hrvatin+%22DOM%22&source=bl&ots=2Wrd5G2ceJ&sig=pjK9cf9LGjlqw1Z6Hm6w8YrWOio&hl=en&sa=X&ved=2ahUKEwjcmZ7U_eDeAhVMGDQIHSfUAdoQ6AEwAnoECAgQAQ#v=onepage&q=John%20Hrvatin%20%22DOM%22&f=false\" rel=\"nofollow noreferrer\">O'Reilly <em>Javascript</em> book by Nicholas C Zakas Pg 36</a>, as well as mentioned in <a href=\"https://www.learnsteps.com/javascript-increase-performance-by-handling-dom-with-care/\" rel=\"nofollow noreferrer\">this post</a></p>\n</blockquote>\n<p>Bearing in mind that was stated more than 10 years ago and browsers likely have come along way since then, it is still wise to be aware of this. Store references to DOM elements - e.g. <code>document.getElementById("year_title")</code> in variables- this could happen in a callback to the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event\" rel=\"nofollow noreferrer\"><code>DOMContentLoaded</code> event</a>.</p>\n<pre><code>let titleEl;\nwindow.addEventListener('DOMContentLoaded', (event) => {\n titleEl = document.getElementById("year_title");\n});\n</code></pre>\n<p>As Joshua mentioned, event handlers in HTML are frowned upon by today’s standards, and that callback would be an appropriate place to have the code currently in the <code>onload</code> attribute of the body element.</p>\n<h2>month names</h2>\n<p>As Joshua already mentioned the code for the months is quite repetitive. Instead of storing the month names <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString\" rel=\"nofollow noreferrer\"><code>Date.prototype.toLocaleDateString()</code></a> could be used to generate the month names dynamically, possibly in a language specified by the user and/or <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/NavigatorLanguage/language\" rel=\"nofollow noreferrer\"><code>navigator.language</code></a> if it is available.</p>\n<h2>More readable function name</h2>\n<blockquote>\n<pre><code>// Set the background color of the cell that contains today's day.\nfunction is_today(months, cell) {\n</code></pre>\n</blockquote>\n<p>Judging by the name I would guess the function would return a Boolean that indicates if some value is today, though given the comment and the implementation that is not the case. A more appropriate name might be <code>style_todays_date_cell</code>.</p>\n<h2>Strict equality</h2>\n<p><a href=\"https://softwareengineering.stackexchange.com/q/126585/244085\">It is a good habit to use strict comparison operators</a> - i.e. <code>===</code> and <code>!==</code> when possible - e.g. for this comparison within <code>load_DB()</code>:</p>\n<blockquote>\n<pre><code>if (x == 6 || x == 0) cell.style.color = "rgba(175, 175, 175, 0.45)";\n</code></pre>\n</blockquote>\n<h2>Pre-fix increment</h2>\n<p>These lines:</p>\n<blockquote>\n<pre><code>month++;\nload_DB(year, month);\n</code></pre>\n</blockquote>\n<p>Can be combined when the value of <code>month</code> is incremented before the call using the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Increment#Description\" rel=\"nofollow noreferrer\">prefix increment operator</a>:</p>\n<pre><code> load_DB(year, ++month);\n</code></pre>\n<h2>redundant inline styles -> CSS</h2>\n<p>The images within the buttons have inline styles- i.e.</p>\n<blockquote>\n<pre><code> style="width: 35px; height: 35px"\n</code></pre>\n</blockquote>\n<p>That can be moved to the stylesheet:</p>\n<pre><code>button img {\n width: 35px;\n height: 35px;\n}\n</code></pre>\n<h2>Inline styles for table headers</h2>\n<p>The first and last cells have inline styles to override the default <code>th</code> rule:</p>\n<blockquote>\n<pre><code><th style="color: lightsalmon">Sun</th>\n</code></pre>\n</blockquote>\n<p>That can be moved to the stylesheet as well using more specific selectors- e.g. pseudo-selectors <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/:first-child\" rel=\"nofollow noreferrer\"><code>:first-child</code></a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/:last-child\" rel=\"nofollow noreferrer\"><code>:last-child</code></a>:</p>\n<pre><code>th:first-child,\nth:last-child {\n color: lightsalmon;\n}\n \n</code></pre>\n<p>Alternatives include <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/:first-of-type\" rel=\"nofollow noreferrer\"><code>:first-of-type</code></a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/:last-of-type\" rel=\"nofollow noreferrer\"><code>:last-of-type</code></a>\nThat technique could also be used to move the line above out of the JavaScript and into the style sheet using <code>td</code> instead of <code>tr</code>:</p>\n<pre><code>if (x == 6 || x == 0) cell.style.color = "rgba(175, 175, 175, 0.45)";\n</code></pre>\n<p>P.S.: The answer was composed using the <strong>IPhone VII+</strong></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T05:28:08.243",
"Id": "250778",
"ParentId": "250759",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "250778",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T19:16:52.153",
"Id": "250759",
"Score": "7",
"Tags": [
"javascript",
"html",
"css",
"ecmascript-6",
"event-handling"
],
"Title": "Animated Calendar using HTML + CSS + JS"
}
|
250759
|
<p>I have an algorithm that I use to render a text GUI using Swing's Canvas, it looks like this in practice:</p>
<p><a href="https://i.stack.imgur.com/5hgej.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/5hgej.gif" alt="enter image description here" /></a></p>
<p>My goal is to reach <code>60</code> frames per second for a full HD grid with <code>8x8</code> (in pixel) tiles. Right now a full-screen grid composed of <code>16x16</code> tiles (1920x1080) renders with <code>60</code>, but <code>8x8</code> tiles have abysmal speed.</p>
<p>I profiled my algorithm and fixed the bottlenecks but now I've reached the limits of Swing itself. This application works with layers composed of <code>Tile</code> objects (with a corresponding <code>Position</code>) so you can imagine a whole thing as a 3D map composed of <code>Tile</code>s with <code>x</code>, <code>y</code> and <code>z</code> coordinates.</p>
<p>My current algorithm works like this:</p>
<ul>
<li>I fetch the <code>Renderable</code> objects. These are text gui components, layers, etc.</li>
<li>I render them onto a <code>FastTileGraphics</code> object (this uses arrays for speed).</li>
<li>I divide them into chunks according to the parallelism parameter to achieve parallel decomposition of work.</li>
<li>I group the <code>Tile</code>s into vertical vectors (I do this because I need to support transparency and tiles can be rendered on top of each other).</li>
<li>If an opaque tile is encountered I overwrite the list since in that case I only need to render a single <code>Tile</code> at that position.</li>
<li>I render the tiles onto <code>BufferedImage</code>s in parallel.</li>
<li>Then I render these images onto the <code>Canvas</code>.</li>
</ul>
<p>The implementation looks like this:</p>
<pre class="lang-kotlin prettyprint-override"><code>override fun render() {
val now = SystemUtils.getCurrentTimeMs()
val bs: BufferStrategy = canvas.bufferStrategy // this is a regular Swing Canvas object
val parallelism = 4
val interval = tileGrid.width / (parallelism - 1)
val tilesToRender = mutableListOf<MutableMap<Position, MutableList<Pair<Tile, TilesetResource>>>>()
0.until(parallelism).forEach { _ ->
tilesToRender.add(mutableMapOf())
}
val renderables = tileGrid.renderables // TileGrid supplies the renderables that contain the tiles
for (i in renderables.indices) {
val renderable = renderables[i]
if (!renderable.isHidden) {
val graphics = FastTileGraphics(
initialSize = renderable.size,
initialTileset = renderable.tileset,
initialTiles = emptyMap()
)
renderable.render(graphics)
graphics.contents().forEach { (tilePos, tile) ->
val finalPos = tilePos + renderable.position
val idx = finalPos.x / interval
tilesToRender[idx].getOrPut(finalPos) { mutableListOf() }
if (tile.isOpaque) {
tilesToRender[idx][finalPos] = mutableListOf(tile to renderable.tileset)
} else {
tilesToRender[idx][finalPos]?.add(tile to renderable.tileset)
}
}
}
}
canvas.bufferStrategy.drawGraphics.configure().apply {
color = Color.BLACK
fillRect(0, 0, tileGrid.widthInPixels, tileGrid.heightInPixels)
tilesToRender.map(::renderPart).map { it.join() }.forEach { img ->
drawImage(img, 0, 0, null)
}
dispose()
}
bs.show()
lastRender = now
}
private fun renderPart(
tilesToRender: MutableMap<Position, MutableList<Pair<Tile, TilesetResource>>>
): CompletableFuture<BufferedImage> = CompletableFuture.supplyAsync {
val img = BufferedImage(
tileGrid.widthInPixels,
tileGrid.heightInPixels,
BufferedImage.TRANSLUCENT
)
val gc = img.graphics.configure()
for ((pos, tiles) in tilesToRender) {
for ((tile, tileset) in tiles) {
renderTile(
graphics = gc,
position = pos,
tile = tile,
tileset = tilesetLoader.loadTilesetFrom(tileset)
)
}
}
img
}
private fun Graphics.configure(): Graphics2D {
this.color = Color.BLACK
val gc = this as Graphics2D
gc.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF)
gc.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED)
gc.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE)
gc.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF)
gc.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_OFF)
gc.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED)
gc.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY)
return gc
}
private fun renderTile(
graphics: Graphics2D,
position: Position,
tile: Tile,
tileset: Tileset<Graphics2D>
) {
if (tile.isNotEmpty) {
tileset.drawTile(tile, graphics, position)
}
}
</code></pre>
<p><code>Renderable</code> looks like this, it just accepts a <code>TileGraphics</code> for rendering:</p>
<pre class="lang-kotlin prettyprint-override"><code>interface Renderable : Boundable, Hideable, TilesetOverride {
/**
* Renders this [Renderable] onto the given [TileGraphics] object.
*/
fun render(graphics: TileGraphics)
}
</code></pre>
<p><code>TileGraphics</code> looks like this:</p>
<pre class="lang-kotlin prettyprint-override"><code>interface TileGraphics {
val tiles: Map<Position, Tile>
fun draw(
tile: Tile,
drawPosition: Position
)
}
</code></pre>
<p>and <code>Tileset</code> is an object that loads the textures from the filesystem and draws individual tiles on a surface (<code>Graphics2D</code> in our case):</p>
<pre class="lang-kotlin prettyprint-override"><code>interface Tileset<T : Any> {
fun drawTile(tile: Tile, surface: T, position: Position)
}
</code></pre>
<p><code>surface</code> here represents the grapics object we use to draw. This is necessary because there is also a LibGDX renderer that works differently. There are also multiple kinds of <code>Tileset</code>s, this is how a regular monospace font is rendered:</p>
<pre class="lang-kotlin prettyprint-override"><code>override fun drawTile(tile: Tile, surface: Graphics2D, position: Position) {
val s = tile.asCharacterTile().get().character.toString()
val fm = surface.getFontMetrics(font)
val x = position.x * width
val y = position.y * height
surface.font = font
surface.color = tile.backgroundColor.toAWTColor()
surface.fillRect(x, y, resource.width, resource.height)
surface.color = tile.foregroundColor.toAWTColor()
surface.drawString(s, x, y + fm.ascent)
}
</code></pre>
<p>This algorithm runs for <code>~22ms</code>.</p>
<p>I've profiled the whole thing and a major bottleneck is the <strong>drawing</strong> part:</p>
<pre class="lang-kotlin prettyprint-override"><code>tilesToRender.map(::renderPart).map { it.join() }.forEach { img ->
drawImage(img, 0, 0, null)
}
</code></pre>
<p>If I remove those 3 lines I get <code>~5ms</code> runtime (so drawing takes <code>~17ms</code>).</p>
<p>I also noticed that parallel decomposition doesn't help at all. If I remove all parallelism I get similar results. Increasing parallelism results in an FPS drop.</p>
<p>The second biggest bottleneck is the <strong>grouping</strong> code (the <code>graphics.contents().forEach { (tilePos, tile) -></code> part), it takes around <code>~4.5ms</code>.</p>
<p>The numbers in total:</p>
<pre><code>21.696576799999985 <-- all
5.328403500000007 <-- without drawing
4.575503500000005 <-- without any java 2d graphics operations
0.08593370000000009 <-- without grouping
</code></pre>
<p>How can I optimize this algorithm? The only part that's mandatory is rendering the renderables: <code>renderable.render(graphics)</code> but I already optimized it and it only takes <code>~0.8ms</code>, so that's negligible.</p>
|
[] |
[
{
"body": "<p>You could either use the real Java console, but that would mean you have to recreate your entire application.</p>\n<p>If you really insist to use Swing, I would do it in another way. Create some custom <code>print()</code> methode for printing ASCII-symbols into a buffered-image, scale this image and use it as background for just a single AWT/Swing component. After that you create a custom actionListener for this AWT/Swing component. Now you've created a simple terminal, which will perform much faster. By the way, you also have to rewrite most of your application in this scenario.</p>\n<p>PS your application looks cool ;-)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T07:16:05.540",
"Id": "493349",
"Score": "2",
"body": "The application is written in a way that it doesn't matter **how** I render. I could write a terminal application with no problem if I wanted. How would this `print` method look like? I already render into a `BufferImage` that I then draw onto the `Canvas`. Why would this be faster? I don't want to scale the image because I want to preserve the crispness of my glyphs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T07:39:25.063",
"Id": "493350",
"Score": "1",
"body": "You are using a ton of objects, just for one screen. The print `method()` would be some kind of copy of `System.out.print()`, but instead of printing out to console, it draws directly onto a buffered image in a well defined way (You have to define it to your targeted look&feel.). The important thing is, it does that without using any object, (besides 1 graphics object). For example _your_ `print()` would draw each character in a 7pixel x 5pixel rectangular with some custom font. You draw 80 characters in one line, do this for 25 lines and voila you have some kind of vt-100-terminal dimension."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T07:47:55.087",
"Id": "493352",
"Score": "2",
"body": "PS resizing an image in a linear way lets your image remain its \"crispness\". Just use a scale factor which is a natural number. https://en.wikipedia.org/wiki/Nearest-neighbor_interpolation PPS to answer your question _\"Why would this be faster?\"_ - You are reducing a lot of overhead, which you've created by using tons of objects for rendering a simple image. \"Drawing\" a simple `int` is faster than calculating, rendering, drawing an entire _object_."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T07:51:13.570",
"Id": "493353",
"Score": "0",
"body": "Right now there is literally no overhead by creating all these objects (`~0.06ms`). You can see that the 2 bottlenecks are the **grouping** and the **rendering**. I would be happy if I could optimize the rendering part, but I'm not sure how your suggestion would apply to my code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T08:09:11.107",
"Id": "493357",
"Score": "0",
"body": "My suggestion don't apply to your code. Your chosen way is unfortunately an inefficient way to achieve your task. You may try to use AWT-components instead of Swing and may also override their `paint()` method. AWT is faster than Swing but has less features. For example you need to implement a double-image-buffer by yourself. This would be doable in less effort, because Swing is mostly compatible to AWT. AWT-components are also able to be **hardware accelerated** (Swing too, but it has still more overhead.), but this makes your app often also platform dependet. **Also use an IndexColorModel.**"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T08:15:44.933",
"Id": "493358",
"Score": "0",
"body": "So first, try to use **hardware acceleration** for your current program. After that try to implement an **IndexColorModel** with maximal 256 different colors, this may increase speed. After that you may try to use **AWT** instead of **Swing**. You may override `paint()` method directly too. Otherwise do like in my first answers and create some kind of virtual terminal without tons of objects."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T08:39:47.723",
"Id": "493365",
"Score": "0",
"body": "Do you have a code example for this?"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T00:59:20.623",
"Id": "250772",
"ParentId": "250764",
"Score": "2"
}
},
{
"body": "<p>Example for an <strong>IndexColorModel</strong>.</p>\n<pre><code>/* START */\npublic static final class GUI {\n public static final Color BLACK = new Color(0x00, 0x00, 0x00); \n public static final Color MAROON = new Color(0x80, 0x00, 0x00);\n public static final Color GREEN = new Color(0x00, 0x80, 0x00);\n public static final Color OLIVE = new Color(0x80, 0x80, 0x00);\n public static final Color NAVY = new Color(0x00, 0x00, 0x80);\n public static final Color PURPLE = new Color(0x80, 0x00, 0x80);\n public static final Color TEAL = new Color(0x00, 0x80, 0x80);\n public static final Color SILVER = new Color(0xC0, 0xC0, 0xC0);\n public static final Color GRAY = new Color(0x80, 0x80, 0x80);\n public static final Color RED = new Color(0xFF, 0x00, 0x00);\n public static final Color LIME = new Color(0x00, 0xFF, 0x00);\n public static final Color YELLOW = new Color(0xFF, 0xFF, 0x00);\n public static final Color BLUE = new Color(0x00, 0x00, 0xFF);\n public static final Color FUCHSIA = new Color(0xFF, 0x00, 0xFF);\n public static final Color AQUA = new Color(0x00, 0xFF, 0xFF);\n public static final Color WHITE = new Color(0xFF, 0xFF, 0xFF);\n \n public static final Color[] COLOR_ARRAY = {\n BLACK, MAROON, GREEN, OLIVE, NAVY, PURPLE, TEAL, SILVER,\n GRAY, RED, LIME, YELLOW, BLUE, FUCHSIA, AQUA, WHITE\n };\n \n public static final byte[] COLOR_ARRAY_RED_COMPONENTS = {\n (byte)COLOR_ARRAY[0].getRed(),\n (byte)COLOR_ARRAY[1].getRed(),\n (byte)COLOR_ARRAY[2].getRed(),\n (byte)COLOR_ARRAY[3].getRed(),\n (byte)COLOR_ARRAY[4].getRed(),\n (byte)COLOR_ARRAY[5].getRed(),\n (byte)COLOR_ARRAY[6].getRed(),\n (byte)COLOR_ARRAY[7].getRed(),\n (byte)COLOR_ARRAY[8].getRed(),\n (byte)COLOR_ARRAY[9].getRed(),\n (byte)COLOR_ARRAY[10].getRed(),\n (byte)COLOR_ARRAY[11].getRed(),\n (byte)COLOR_ARRAY[12].getRed(),\n (byte)COLOR_ARRAY[13].getRed(),\n (byte)COLOR_ARRAY[14].getRed(),\n (byte)COLOR_ARRAY[15].getRed()\n };\n public static final byte[] COLOR_ARRAY_GREEN_COMPONENTS = {\n (byte)COLOR_ARRAY[0].getGreen(),\n (byte)COLOR_ARRAY[1].getGreen(),\n (byte)COLOR_ARRAY[2].getGreen(),\n (byte)COLOR_ARRAY[3].getGreen(),\n (byte)COLOR_ARRAY[4].getGreen(),\n (byte)COLOR_ARRAY[5].getGreen(),\n (byte)COLOR_ARRAY[6].getGreen(),\n (byte)COLOR_ARRAY[7].getGreen(),\n (byte)COLOR_ARRAY[8].getGreen(),\n (byte)COLOR_ARRAY[9].getGreen(),\n (byte)COLOR_ARRAY[10].getGreen(),\n (byte)COLOR_ARRAY[11].getGreen(),\n (byte)COLOR_ARRAY[12].getGreen(),\n (byte)COLOR_ARRAY[13].getGreen(),\n (byte)COLOR_ARRAY[14].getGreen(),\n (byte)COLOR_ARRAY[15].getGreen()\n };\n public static final byte[] COLOR_ARRAY_BLUE_COMPONENTS = {\n (byte)COLOR_ARRAY[0].getBlue(),\n (byte)COLOR_ARRAY[1].getBlue(),\n (byte)COLOR_ARRAY[2].getBlue(),\n (byte)COLOR_ARRAY[3].getBlue(),\n (byte)COLOR_ARRAY[4].getBlue(),\n (byte)COLOR_ARRAY[5].getBlue(),\n (byte)COLOR_ARRAY[6].getBlue(),\n (byte)COLOR_ARRAY[7].getBlue(),\n (byte)COLOR_ARRAY[8].getBlue(),\n (byte)COLOR_ARRAY[9].getBlue(),\n (byte)COLOR_ARRAY[10].getBlue(),\n (byte)COLOR_ARRAY[11].getBlue(),\n (byte)COLOR_ARRAY[12].getBlue(),\n (byte)COLOR_ARRAY[13].getBlue(),\n (byte)COLOR_ARRAY[14].getBlue(),\n (byte)COLOR_ARRAY[15].getBlue()\n };\n \n public static final IndexColorModel INDEX_COLOR_MODEL = new IndexColorModel(\n 4, 16, /* 4bit color range, 16 unique colors */\n COLOR_ARRAY_RED_COMPONENTS,\n COLOR_ARRAY_GREEN_COMPONENTS,\n COLOR_ARRAY_BLUE_COMPONENTS\n );\n}\n/* END */\n</code></pre>\n<p>For example this IndexColorModel uses only 16 different colors, while using 4bit per color and a 24bit color palette.\nWhen applied onto a BufferedImage, like:</p>\n<p><code>new BufferedImage(640, 480, TYPE_BYTE_INDEXED, INDEX_COLOR_MODEL)</code></p>\n<p>It reduces maximal color space to 4bit per color and the chosen 16 different colors. Effectively reducing image data size and thus increasing performance.</p>\n<p>An advantage of this INDEX_COLOR_MODEL for your application would be, that you would've just to change the color palette to adjust your application colors. Which is much faster, than to repaint all components in a different color from 24bit RGB-color-space (24bit RGB-color-space is a defacto standard for using BufferedImage in Java.).</p>\n<p>You may draw in any color to this INDEX_COLOR_MODEL BufferedImage, your chosen color will be automaticly adjusted to the colorspace of your BufferedImage. But it's adviceable to directly use the colors of your colorspace in the first place, because that's a bit faster.</p>\n<p>I suggest you read the Java API documentation regarding this feature:\n<a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.desktop/java/awt/image/IndexColorModel.html\" rel=\"nofollow noreferrer\">https://docs.oracle.com/en/java/javase/11/docs/api/java.desktop/java/awt/image/IndexColorModel.html</a></p>\n<p>The other functions (<strong>hardware acceleration</strong>, <strong>AWT</strong>, overriding <code>paint()</code>) are more or less easy to implement. Search and read some tutorials.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T21:34:14.713",
"Id": "493622",
"Score": "0",
"body": "This doesn't work at all for me. All I see is a black screen and no error message. The problem is that I need to support transparency and dynamic colors since my users can choose their own colors."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T19:57:58.617",
"Id": "493726",
"Score": "0",
"body": "I suggest you read about what a color palette is. For what do you need transparency? Your users may choose their own colors too, by changing the color palette. `public static final Color BLACK = new Color(0x00, 0x00, 0x00);` <- this is a 24bit color. Just use something like `public static Color userColor = new Color(0x12, 0x34, 0x56);`. When you use a \"limited/indexed\" color space, your \"input\" colors may become \"deformed\". What this means: If your \"input\" color is very dark, it might become just _BLACK_ in the \"limited/indexed\" color space. Try to use the predefined colors, instead of custom."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T07:01:27.147",
"Id": "493788",
"Score": "0",
"body": "I tried your example but it didn't work. I just saw an empty black screen without error messages."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T01:00:54.387",
"Id": "250817",
"ParentId": "250764",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T21:37:15.803",
"Id": "250764",
"Score": "9",
"Tags": [
"java",
"swing",
"kotlin",
"canvas"
],
"Title": "Optimize a tile rendering algorithm for Swing Canvas"
}
|
250764
|
<p>This code takes a user input number which is a positive integer, and outputs a string representation of the number in binary. For example, input <code>2</code> outputs <code>'10'</code> and input <code>25</code> outputs <code>'11001'</code>. As far as I can tell it works correctly.</p>
<p>Please review it for good style and organization, and I'm especially looking for a critique of the algorithm and level of documentation. My goals are correctness and that it is obvious what the code is doing. My experience level is I've been using Python for about 7 years, hobbyist, haven't collaborated with other programmers ever, and I'm now in a Comp Sci degree program.</p>
<p>I chose the log2 function and the for loop to calculate how long to run, rather than trying to guess if the calc is over on each pass of the loop, but I assume there is a cleaner/simpler way to do that.</p>
<pre><code>from math import log2, floor
def integer_to_binary_string(int_value):
'''Converts integer to a string of base-2 bits,
example: 20 becomes '10100'
'''
rev_str = integer_to_reverse_binary(int_value)
forward_str = reverse_string(rev_str)
return forward_str
def integer_to_reverse_binary(int_value):
'''returns a string, not a numerical'''
out_s = ''
if int_value == 0:
#to avoid ValueError on the log2 call
return '0'
#find length of bin string
bin_digits = floor(log2(int_value)) + 1
for i in range(bin_digits):
out_s = out_s + str(int_value // 2**i % 2)
return out_s
def reverse_string(s):
return s[::-1] #start:stop:step slice notation
if __name__ == '__main__':
user_input = int(input())
print(integer_to_binary_string(user_input))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T22:11:53.560",
"Id": "493327",
"Score": "1",
"body": "I assume you're [reinventing-the-wheel] intentionally, and don't want to just use the `bin(...)` function, so I've added that tag. Please correct me if I'm wrong..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T22:16:59.160",
"Id": "493328",
"Score": "0",
"body": "@AJNeufeld thanks for adding that, you are correct. I didn't know about that tag. (and anyhow, I'd have to strip the leading `'0b'` from the output of `bin(i)` to satisfy the automated test, but that's trivial)"
}
] |
[
{
"body": "<p>Your implementation seems fine at a glance, but Python actually provides two <em>really</em> easy ways to do this:</p>\n<ul>\n<li><a href=\"https://docs.python.org/3/library/string.html#formatspec\" rel=\"nofollow noreferrer\"><code>string.format</code></a></li>\n<li><a href=\"https://docs.python.org/3/library/functions.html#bin\" rel=\"nofollow noreferrer\"><code>bin</code></a></li>\n</ul>\n<p>Your function would then become:</p>\n<pre><code>def integer_to_binary_string(int_value):\n '''Converts integer to a string of base-2 bits,\n \n example: 20 becomes '10100'\n \n '''\n return f"{int_value:b}"\n # or \n # return bin(int_value)[2:]\n</code></pre>\n<p>The advantages of this are numerous:</p>\n<ul>\n<li>Obvious what is happening & idiomatic Python</li>\n<li>Doesn't require someone to understand the math behind it</li>\n<li>Way faster (<a href=\"https://docs.python.org/3/library/timeit.html\" rel=\"nofollow noreferrer\"><code>timeit</code></a> with 1,000,000 iterations clocks at 0.23s for my method, 1.82s for yours)</li>\n</ul>\n<p>Now to actually review your code (the <kbd>reinventing-the-wheel</kbd> tag was added after I started writing this):</p>\n<ul>\n<li>Generally, I prefer <a href=\"https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions\" rel=\"nofollow noreferrer\">list comprehensions</a> over an explicit loop; they're often faster</li>\n<li>Creating a function called <code>reverse_string</code> is unnecessary - the idiomatic/Pythonic way to do this is using the slice notation you mentioned - hiding it behind a method is just going to confuse experienced Python users.</li>\n<li>Repeatedly appending to strings/lists/things is generally not the best from a performance perspective (this has to do with how memory is allocated). Instead, use <a href=\"https://docs.python.org/3/library/stdtypes.html#str.join\" rel=\"nofollow noreferrer\"><code>str.join</code></a>, as it will do better from a memory allocation perspective</li>\n</ul>\n<p>What I would end up with looks like this:</p>\n<pre><code>def integer_to_binary_string2(int_value):\n """Converts integer to a string of base-2 bits,\n\n example: 20 becomes '10100'\n\n """\n if int_value == 0:\n return "0"\n bin_digits = floor(log2(int_value)) + 1\n return "".join([\n str(int_value // 2 ** i % 2) \n for i in range(bin_digits)\n ])[::-1]\n</code></pre>\n<p>You can use a <a href=\"https://stackoverflow.com/questions/364802/how-exactly-does-a-generator-comprehension-work\">generator comprehension</a> instead of a list comprehension, but as pointed out by <a href=\"https://codereview.stackexchange.com/users/98493/graipher\">@Graipher</a> in the comments, in CPython <code>str.join</code> turns arbitrary iterables into lists as the very first step, negating any potential benefits. Generally speaking I prefer generator comprehensions to list comprehensions because they can be more memory efficient & are lazily evaluated, but they add no benefit here.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T20:19:13.020",
"Id": "493615",
"Score": "0",
"body": "Thank you to all who posted answers, all very helpful (I didn't know about type hinting in Python, especially). I chose this one because it especially focused on the algorithm and demo'd the `timeit` info and revised non-trivial code, and I think pointing out my need to study list/generator comprehensions is very helpful."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T22:26:27.407",
"Id": "250767",
"ParentId": "250766",
"Score": "6"
}
},
{
"body": "<ul>\n<li><p>According to <a href=\"https://www.python.org/dev/peps/pep-0008/#string-quotes\" rel=\"nofollow noreferrer\">PEP8</a>, docstrings should use <code>"""</code> instead of <code>'''</code></p>\n</li>\n<li><p>Both <code>integer_to_reverse_binary</code> and <code>reverse_string</code> are only used once.\nI'd just replace the usage with the body of the functions.</p>\n</li>\n<li><p>Instead of <code>integer_to_binary_string</code>, I would prefer a shorter name such as <code>int_to_bin</code>.</p>\n</li>\n<li><p><code>log2</code> is inaccurate for large values and should be avoided if possible. <code>int</code> has an in-built function called <code>bit_length</code> which, as you could probably guess, returns the bit length of an integer.</p>\n<p>This function can replace <code>floor(log2(int_value)) + 1</code>.</p>\n</li>\n<li><p><code>rev_str += some_value</code> is the proper (and marginally faster) way for inplace addition.</p>\n</li>\n<li><p><code>rev_str += str(int_value // 2 ** i % 2)</code> can be replaced to <code>rev_str += str((int_value >> i) & 1)</code> by using bitwise operators to be made faster.</p>\n</li>\n</ul>\n<p>Now, the function looks something like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def int_to_bin(int_value):\n """\n Converts integer to a string of base-2 bits\n Example: 20 becomes '10100'\n """\n\n if int_value == 0:\n return '0'\n\n rev_str = ''\n bin_digits = int_value.bit_length()\n for i in range(bin_digits):\n rev_str += str((int_value >> i) & 1)\n\n forward_str = rev_str[::-1]\n return forward_str\n</code></pre>\n<hr />\n<p>Now, the above is good enough, but it can be made shorter and faster, though it's probably not recommended.</p>\n<ul>\n<li><p><code>bin_digits</code> and <code>forward_str</code> can be turned into inline statements, thus removing the variables.</p>\n</li>\n<li>\n<pre class=\"lang-py prettyprint-override\"><code>rev_str = ''\nfor i in range(int_value.bit_length()):\n rev_str += str((int_value >> i) & 1)\n</code></pre>\n<p>If you use <code>''.join()</code>, this can be changed to a one-liner as follows.<br />\n<code>rev_str = ''.join(str((int_value >> i) & 1) for i in range(int_value.bit_length()))</code></p>\n</li>\n</ul>\n<p>Now, the code has been reduced to:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def int_to_bin(int_value):\n """\n Converts integer to a string of base-2 bits\n Example: 20 becomes '10100'\n """\n\n if int_value == 0:\n return '0'\n\n return ''.join(str((int_value >> i) & 1) for i in range(int_value.bit_length()))[::-1]\n</code></pre>\n<p>I hope this helped!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T10:57:44.910",
"Id": "250786",
"ParentId": "250766",
"Score": "5"
}
},
{
"body": "<p>Several general hints:</p>\n<ul>\n<li><strong>Formatting</strong>: Use an auto-formatter. I recommend <a href=\"https://pypi.org/project/black/\" rel=\"nofollow noreferrer\">black</a>. It's wide-spread, maintained by the Python Software Foundation, allows little configuration so the style is consistent among projects (no configuration is good in this case)</li>\n<li><strong>Linting</strong>: Use linters. I recommend <a href=\"https://pypi.org/project/flake8/\" rel=\"nofollow noreferrer\">flake8</a> with <a href=\"https://pypi.org/project/flake8-bugbear/\" rel=\"nofollow noreferrer\"><code>flake8-bugbear</code></a>, <a href=\"https://pypi.org/project/flake8-comprehensions/\" rel=\"nofollow noreferrer\"><code>flake8-comprehensions</code></a>, <a href=\"https://pypi.org/project/flake8_implicit_str_concat/\" rel=\"nofollow noreferrer\"><code>flake8_implicit_str_concat</code></a>, <a href=\"https://pypi.org/project/flake8-simplify/\" rel=\"nofollow noreferrer\"><code>flake8-simplify</code></a> as plugins. See also: <a href=\"https://towardsdatascience.com/static-code-analysis-for-python-bdce10b8d287\" rel=\"nofollow noreferrer\">Static code analysis for Python</a></li>\n<li><strong>Type Annotations</strong>: They are awesome. Use them. See also: <a href=\"https://medium.com/analytics-vidhya/type-annotations-in-python-3-8-3b401384403d\" rel=\"nofollow noreferrer\">Type annotations in Python 3.6+</a></li>\n<li><strong>Docstring style</strong>: There are two which are good (<a href=\"https://numpydoc.readthedocs.io/en/latest/format.html\" rel=\"nofollow noreferrer\">Numpy doc</a> and <a href=\"https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings\" rel=\"nofollow noreferrer\">Google Style</a>) and another one which is wide-spread (<a href=\"https://sphinx-rtd-tutorial.readthedocs.io/en/latest/docstrings.html\" rel=\"nofollow noreferrer\">Sphinx Style</a>). I like to use something very similar to numpy doc as it is easy to read.</li>\n<li><strong>Doctests</strong>: <a href=\"https://docs.python.org/3/library/doctest.html\" rel=\"nofollow noreferrer\"><code>doctest</code></a> makes your documentation double as a unit test. So your documentation is actually tested!</li>\n<li>(you are aware of this as there is the <a href=\"/questions/tagged/reinvent-the-wheel\" class=\"post-tag\" title=\"show questions tagged 'reinvent-the-wheel'\" rel=\"tag\">reinvent-the-wheel</a>, but this is super important in general: <strong>Use built-ins</strong>: Use built format or bin as shown <a href=\"https://stackoverflow.com/a/21732313/562769\">here</a>. Code you don't write is code you don't need to test / maintain.)</li>\n</ul>\n<p>Applied to this case, it gives:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def integer_to_binary_string(number: int) -> str:\n """\n Convert an integer to a string of base-2 bits.\n\n Examples\n --------\n >>> integer_to_binary_string(20)\n '10100'\n >>> integer_to_binary_string(-20)\n '-10100'\n\n Examples\n --------\n """\n return format(number, "b")\n\n\nif __name__ == "__main__":\n import doctest\n\n doctest.testmod()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T13:39:30.143",
"Id": "493387",
"Score": "2",
"body": "Every point here is valid, except for the last one. The question is tagged `reinventing-the-wheel`, and the OP probably already knows about the builtins"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T15:04:37.653",
"Id": "493389",
"Score": "2",
"body": "Good point! I havent seem that. I've adjusted the answer :-)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T12:15:21.823",
"Id": "250788",
"ParentId": "250766",
"Score": "5"
}
},
{
"body": "<p>I only have a few points to add to <a href=\"https://codereview.stackexchange.com/a/250767/1581\">Dannnno's</a>, <a href=\"https://codereview.stackexchange.com/a/250786/1581\">Sriv's</a>, and <a href=\"https://codereview.stackexchange.com/a/250788/1581\">Martin Thoma's</a> excellent answers.</p>\n<h1>Consistency</h1>\n<p>Sometimes, you abbreviate string as "str", sometimes as "s", sometimes not at all. Sometimes, you put the type in the identifier, sometimes not. When you put the type in the identifier, you sometimes put it as a prefix, sometimes as a suffix.</p>\n<p>You should choose one style and stick with it. If you are editing some existing code, you should adapt your style to be the same as the existing code. If you are part of a team, you should adapt your style to match the rest of the team.</p>\n<p>In general, if you use two different ways to write the exact same thing, the reader will think that you want to convey a message with that. So, you should only use two different ways of writing the same thing IFF you actually want to convey some extra information.</p>\n<h1>Vertical whitespace</h1>\n<p>Your code is all bunched up together. Some empty lines would allow the code room to breathe, for example in the <code>integer_to_reverse_binary</code> function. The function is clearly separated into a series of steps: setup, compute, return. Some whitespace would help draw attention to those steps:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def integer_to_reverse_binary(int_value):\n '''returns a string, not a numerical'''\n\n out_s = ''\n\n if int_value == 0:\n #to avoid ValueError on the log2 call\n return '0'\n\n #find length of bin string\n bin_digits = floor(log2(int_value)) + 1\n for i in range(bin_digits):\n out_s = out_s + str(int_value // 2**i % 2)\n\n return out_s\n</code></pre>\n<h1>Naming</h1>\n<p>Let's look at these names:</p>\n<ul>\n<li><code>int_value</code></li>\n<li><code>rev_str</code></li>\n<li><code>forward_str</code></li>\n<li><code>out_s</code></li>\n<li><code>s</code></li>\n</ul>\n<p><code>rev_str</code>, <code>forward_str</code>, <code>s</code>, and <code>out_s</code> all contain strings. And yet, two of them are named <code>str</code> and two of them are named <code>s</code>. <code>forward_str</code> and <code>rev_str</code> are right next to each other in the code, they conceptually do the same thing (naming a temporary string), yet the word <code>forward</code> is spelled out, the word <code>rev</code>erse is abbreviated.</p>\n<p>Some of the names are very cryptic (e.g. <code>s</code>) and some very detailed (e.g. <code>integer_to_reverse_binary</code>).</p>\n<p>Names are important. <a href=\"https://karlton.org/2017/12/naming-things-hard/\" rel=\"nofollow noreferrer\">Names are also <em>hard</em></a>.</p>\n<p>A <em>good name</em> should be <em>intention-revealing</em>. They should convey <em>meaning</em>.</p>\n<p><code>int_value</code>, for example, does not convey much meaning. You can only pass values as arguments, so <em>every</em> argument is <em>always</em> a value. Thus, the word "value" doesn't tell me anything I don't already know. And <code>int</code> only tells me what it is, but not what it does and what it's for, how it is used, why it is there.</p>\n<p>Compared to <code>int_value</code>, even just <code>n</code> would be a better name, since it <em>does</em> actually tell the reader something: "this is just a number, and there's nothing special about it, so it doesn't deserve a name".</p>\n<p>It is also not quite correct. In the question, you write [<strong>bold</strong> emphasis mine]:</p>\n<blockquote>\n<p>This code takes a user input number which is a <strong>positive</strong> integer</p>\n</blockquote>\n<p>So, <code>int</code> is actually not a restrictive enough description. In another sense, however, it is <em>too</em> restrictive, because your code will not just work with positive <code>int</code>s but with <em>any</em> positive whole number type that implements <code>__floordiv__</code>, <code>__rpow__</code>, and <code>__rdivmod__</code>.</p>\n<p>The name <code>bin_digits</code> is actively misleading: it <em>does not</em> contain the binary digits. It contains the <em>number of</em> binary digits.</p>\n<p>Oh, and also, the term "<strong>bi</strong>nary dig<strong>it</strong>" is usually shortened to "bit".</p>\n<p>So, it should be called <code>bit_length</code> or <code>number_of_bits</code>.</p>\n<h1>Not naming</h1>\n<p>As I wrote above, naming is hard, and names are important. However, there is a flip side to that: <em>because</em> naming is hard and names are important, that means <em>when you give something a name, that thing is important</em>.</p>\n<p>If I see something with a name, I think "naming is hard work, so if the author put in the hard work to come up with a name for this thing, then this must be an important thing".</p>\n<p>I think at least some of the slightly awkward names in your code are caused by trying to come up with names for things that shouldn't have names or maybe shouldn't even exist. For example, I think that <code>out_s</code> shouldn't be necessary.</p>\n<h1>Comments</h1>\n<p>Generally speaking, comments are a <a href=\"https://martinfowler.com/bliki/CodeSmell.html\" rel=\"nofollow noreferrer\"><em>code smell</em></a>. Mostly, comments should not exist:</p>\n<ul>\n<li>If your code is so complex that you need to explain it in a comment, you should rather try to refactor your code to be less complex.</li>\n<li>If you have a comment that explains what something is, you can rather give it a name.</li>\n<li>If you have a comment that explains how the code does something, just delete it: the code explains how the code does something.</li>\n</ul>\n<p>The only acceptable thing for a comment is to explain <em>why</em> the code does something in a specific non-obvious way. So, for example, there is an obvious way that looks like it <em>should</em> work, but you tried it and it didn't work for a non-obvious reason. Then you can add a comment explaining that you are specifically using solution B even though it looks like much simpler solution A should also work, but it actually doesn't work because of issue X. Ideally, you would add a link to the pull request / code review / bug ticket where this issue is discussed in greater detail and maybe a link to a wiki page with a detailed explanation.</p>\n<p>I will give a couple of examples:</p>\n<pre class=\"lang-python prettyprint-override\"><code>#find length of bin string\nbin_digits = floor(log2(int_value)) + 1\n</code></pre>\n<p>I talked before about how I think the name <code>bin_digits</code> is not a very good name. And I think the comment reinforces that. Instead of using the comment to clarify the unclear name of the variable, we can <em>rename</em> the variable to just say that in the first place:</p>\n<pre class=\"lang-python prettyprint-override\"><code>bit_length = floor(log2(int_value)) + 1\n</code></pre>\n<p>Here is another example:</p>\n<pre class=\"lang-python prettyprint-override\"><code>return s[::-1] #start:stop:step slice notation\n</code></pre>\n<p>This comment is basically useless.</p>\n<p>If I know Python, I know slice notation, so this comment tells me nothing. If I don't know Python, I have no idea what "slice notation" means, so this comment tells me nothing.</p>\n<p><code>[::-1]</code> is <em>the</em> standard Python idiom for reversing a sequence. This idiom is so well-known that even I know it, even though I am not actually a Python programmer. It really needs no explanation.</p>\n<p>For a Python programmer, the "letters" <code>[::-1]</code> are actually no different from the letters <code>reverse</code>.</p>\n<h1>Type annotations</h1>\n<p>There are several places in your code, where you put types either in comments or in names. If you think the types are important enough to write down <em>at all</em>, don't you think they shouldn't be hidden away in comments or in names? Why not write the type as a … type?</p>\n<p>For example, this</p>\n<pre class=\"lang-python prettyprint-override\"><code>def integer_to_binary_string(int_value):\n</code></pre>\n<p>could become this:</p>\n<pre class=\"lang-python prettyprint-override\"><code>def integer_to_binary(n: int) -> str:\n</code></pre>\n<p>Or here, where for some strange reason you put the type not in the name but in the documentation, even though the situation is exactly the same as above:</p>\n<pre class=\"lang-python prettyprint-override\"><code>def integer_to_reverse_binary(int_value):\n '''returns a string, not a numerical'''\n</code></pre>\n<p>becomes</p>\n<pre class=\"lang-python prettyprint-override\"><code>def integer_to_reverse_binary(n: int) -> str:\n</code></pre>\n<h1>Iteration Patterns</h1>\n<p>A lot of stuff we do in programming is iteration. We are iterating over data structures, over user inputs, you can think of a reactive program as iterating over a stream of events, etc. It is no wonder that the collections framework is the centerpiece of any language's core libraries.</p>\n<p>There are a couple of <em>fundamental</em> iteration patterns that occur over and over again. Some of the more well-known are <a href=\"https://wikipedia.org/wiki/Fold_(higher-order_function)\" rel=\"nofollow noreferrer\"><em>fold</em></a> ("folding" a collection into a single value using a binary operation) and <a href=\"https://wikipedia.org/wiki/Map_(higher-order_function)\" rel=\"nofollow noreferrer\"><em>map</em></a> (transforming each individual element of the collection). Then there is <a href=\"https://wikipedia.org/wiki/Prefix_sum#Scan_higher_order_function\" rel=\"nofollow noreferrer\"><em>scan</em></a> aka <em>prefix-sum</em>, <a href=\"https://wikipedia.org/wiki/Filter_(higher-order_function)\" rel=\"nofollow noreferrer\"><em>filter</em></a>, and so on.</p>\n<p>Of these, <em>fold</em> has an interesting property: it is <a href=\"http://www.cs.nott.ac.uk/%7Epszgmh/fold.pdf\" rel=\"nofollow noreferrer\">universal and expressive</a>, meaning that <em>all the other ones</em> I listed and many more (in fact, <em>everything</em> that can be expressed by iterating over a collection, i.e. by using Python's <code>for</code> / <code>in</code>) can be expressed as a <em>fold</em>.</p>\n<p>What does this have to do with this problem? Well, in turns out, fold has a <em>dual</em>, which is typically called <a href=\"https://wikipedia.org/wiki/Anamorphism\" rel=\"nofollow noreferrer\"><em>unfold</em></a>. Where fold "folds" a collection into a single value using a function that takes two arguments and returns one value, <em>unfold</em> does the exact dual of that: it "unfolds" a single value into a collection using a function that takes one argument and returns two values.</p>\n<p>Doesn't that sound <em>exactly</em> what we are trying to do? Unfold a single number into a collection of ones and zeroes?</p>\n<p>Python implements many recursion patterns in its library and even in the language. For example, <a href=\"https://docs.python.org/3/library/functools.html#functools.reduce\" rel=\"nofollow noreferrer\"><code>functors.reduce</code></a> is <em>fold</em>, <a href=\"https://docs.python.org/3/library/itertools.html#itertools.accumulate\" rel=\"nofollow noreferrer\"><code>itertools.accumulate</code></a> is <em>scan</em> comprehensions are a powerful combination of <em>map</em> and <em>filter</em>.</p>\n<p>Unfold, however, is unfortunately missing. But it is easy to write (or, as I did, <a href=\"https://reddit.com/r/programming/comments/65bpf/unfold_in_python/c02vvrz/\" rel=\"nofollow noreferrer\">google</a>):</p>\n<pre class=\"lang-python prettyprint-override\"><code>from typing import Callable, Iterable, Optional, Tuple, TypeVar\n\nA = TypeVar("A")\nB = TypeVar("B")\n\n\ndef unfold(f: Callable[[B], Optional[Tuple[A, B]]], initial: B) -> Iterable[A]:\n """\n Unfold a seed into an iterable.\n\n Unfold an initial seed value into a potentially infinite iterable by\n repeatedly applying a function for generating the next element.\n\n Implementation inspired by:\n https://reddit.com/r/programming/comments/65bpf/unfold_in_python/c02vvrz/\n\n :param f: a callable that takes the current seed as argument and\n returns a tuple of the next value and the next seed (or None to\n stop the generation).\n :param initial: the initial seed value\n :yields: a potentially infinite interable of values generated from the seed\n by repeatedly applying f.\n """\n intermediate = f(initial)\n while intermediate:\n element, initial = intermediate\n yield element\n intermediate = f(initial)\n</code></pre>\n<p>With this definition in scope, we can express the operation very succinctly, in my opinion:</p>\n<pre class=\"lang-python prettyprint-override\"><code>def integer_to_binary(n: int) -> str:\n """\n Convert a non-negative integer into binary representation.\n\n :param n: a non-negative integer.\n :returns: the binary representation of n.\n """\n if n < 0:\n raise ValueError(n)\n\n return "".join(unfold(lambda n: (str(n % 2), n // 2) if n else None, n))[::-1]\n</code></pre>\n<p>There seem to be differing opinions in the Python community about whether or not functional programming and recursion patterns are idiomatic or not. For someone who is used to working with recursion patterns, the code here is understandable and succinct (but not dense).</p>\n<p>Others may disagree. One way to get around this would be to possibly turn the anonymous lambda into a named nested function.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T19:04:33.167",
"Id": "250841",
"ParentId": "250766",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "250767",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T21:44:19.393",
"Id": "250766",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"strings",
"reinventing-the-wheel",
"binary"
],
"Title": "Convert Integer to Binary String"
}
|
250766
|
<p>I don't know if this is acceptable, but I would love to thank the community for their advice concerning my previous post on this project</p>
<p><strong>This is a beginner's project</strong>.</p>
<p>Library management system aims to handle the basic housekeeping of a functional library, so far I have implemented the BookItem class and with advice from the community, also implemented a Date class( not with full funtionalities )</p>
<p>Librarian class though not completed yet is also functional...
I used a list to store the books in the library. I saw some post where vectors are suggested as the goto data structure, I feel list best suit this case, If vectors would be better I would appreciate if you highlight the reasons.</p>
<p>Note am a beginner and have no knowledge about C++ advanced topics yet.</p>
<p>Here is the code</p>
<p><strong>Date.hh</strong></p>
<pre><code>#ifndef DATE_HH
#define DATE_HH
/*****************************************************************
* Name: Date.hh
* Author: Samuel Oseh
* Purpose: Date class method-function prototype
* ***************************************************************/
#include <iostream>
class Date {
friend std::ostream &operator<<( std::ostream &, const Date & );
private:
/* data-member */
unsigned int month;
unsigned int day;
unsigned int year;
// utility function
unsigned int checkDay( int ) const;
public:
static const unsigned int monthsPerYear = 12;
// ctors
Date() : Date( 1, 1, 1970 ){}
Date( int m, int d, int y ) { setDate( m, d, y );}
Date( int m ) : Date( m, 1, 1970 ){}
Date( int m, int d ) : Date( m, d, 1970 ) {}
// copy operations
Date( const Date &d ) { *this = std::move(d); }
Date &operator=( const Date &d ) { month = d.month; day = d.day; year = d.year; return *this; }
/* method-functions */
void setDate( int m, int d, int y );
void setMonth( int m );
void setDay( int d );
void setYear( int y );
unsigned int getMonth() const;
unsigned int getDay() const;
unsigned int getYear() const;
void nextDay();
// dtor
~Date(){};
};
#endif
</code></pre>
<p><strong>Date.cc</strong></p>
<pre><code>/*****************************************************************
* Name: Date.cc
* Author: Samuel Oseh
* Purpose: Date class method-function definitions
* ***************************************************************/
#include <iostream>
#include <stdexcept>
#include <array>
#include "Date.hh"
void Date::setDate( int m, int d, int y) {
setMonth( m );
setDay( d );
setYear( y );
}
void Date::setDay( int d ) {
day = checkDay( d );
}
void Date::setMonth( int m ) {
if ( m >= 1 && m < 13 )
month = m;
else
throw std::invalid_argument( "Month must be between 1-12" );
}
void Date::setYear( int y ) {
if ( y >= 1970 )
year = y;
else
throw std::invalid_argument( "year must be greater than 1969" );
}
void Date::nextDay() {
day += 1;
try {
checkDay( day );
} catch ( std::invalid_argument &e ) {
month += 1;
day = 1;
}
if ( month % 12 == 0 ) {
year += 1;
month = 1;
}
}
std::ostream &operator<<( std::ostream &os, const Date &d ) {
os << d.month << "/" << d.day << "/" << d.year << " ";
return os;
}
// utility function
unsigned int Date::checkDay( int testDay ) const {
static const std::array < int, monthsPerYear + 1 > daysPerMonth = { 0,31,28,31,30,31,30,31,31,30,32,30,31};
if ( testDay > 0 && testDay <= daysPerMonth[ month ] )
return testDay;
if ( month == 2 && testDay == 29 && ( year % 400 == 0 || ( year % 4 == 0 && year % 100 != 0 ) ) )
return testDay;
throw std::invalid_argument( "Invalid day for current month and year" );
}
</code></pre>
<p><strong>BookItem.hh</strong></p>
<pre><code>#ifndef BOOKITEM_HH
#define BOOKITEM_HH
/*****************************************************************
* Name: BookItem.hh
* Author: Samuel Oseh
* Purpose: BookItem class method-function prototype
* ***************************************************************/
#include <string>
#include "Date.hh"
enum class BookStatus : unsigned { RESERVED, AVAILABLE, UNAVAILABLE, REFERENCE, LOANED, NONE };
enum class BookType : unsigned { HARDCOVER, MAGAZINE, NEWSLETTER, AUDIO, JOURNAL, SOFTCOPY };
class BookItem {
private:
/* data-members */
std::string title;
std::string author;
std::string category;
Date pubDate;
std::string isbn;
BookStatus status;
BookType type;
public:
// ctor
BookItem() = default;
BookItem( const std::string &title, const std::string &author, const std::string &cat, const Date &pubDate, \
const std::string &isbn, const BookStatus status, const BookType type );
// copy operations
const BookItem& operator=( const BookItem &bookItem );
BookItem( const BookItem &bookItem ) { *this = std::move(bookItem); }
/* method-functions */
void setStatus( BookStatus s ) { status = s; };
void setType( BookType t ) { type = t;};
std::string getStatus() const;
std::string getType() const;
std::string getTitle() const { return title; }
std::string getAuthor() const { return author; }
Date &getPubDate() { return pubDate; }
void printPubDate() const { std::cout << pubDate; }
std::string getIsbn() const { return isbn; }
void setCategory( const std::string &c ) { category = c; }
std::string getCategory() const { return category; };
// dtor
~BookItem(){}
};
#endif
</code></pre>
<p><strong>BookItem.cc</strong></p>
<pre><code>/*****************************************************************
* Name: BookItem.cc
* Author: Samuel Oseh
* Purpose: BookItem class method-function definitions
* ***************************************************************/
#include <iostream>
#include "BookItem.hh"
BookItem::BookItem( const std::string &t, const std::string &a, const std::string &c, const Date &d, \
const std::string &i, const BookStatus s, const BookType ty ) {
title = t, author = a, category = c, pubDate = d, isbn = i;
setStatus( s );
setType( ty );
}
const BookItem &BookItem::operator=( const BookItem &bookItem ) {
title = bookItem.title;
author = bookItem.author;
category = bookItem.category;
pubDate = bookItem.pubDate;
isbn = bookItem.isbn;
status = bookItem.status;
type = bookItem.type;
return *this;
}
std::string BookItem::getStatus() const {
if ( status == BookStatus::AVAILABLE )
return "AVAILABLE";
else if ( status == BookStatus::REFERENCE )
return "REFERENCE";
else if ( status == BookStatus::UNAVAILABLE )
return "UNAVAILABLE";
else if ( status == BookStatus::LOANED )
return "LOANED";
else if ( status == BookStatus::RESERVED )
return "RESERVED";
else
return "NONE";
}
std::string BookItem::getType() const {
if ( type == BookType::AUDIO )
return "AUDIO";
if ( type == BookType::HARDCOVER )
return "HARDCOVER";
if ( type == BookType::JOURNAL )
return "JOURNAL";
if ( type == BookType::MAGAZINE )
return "MAGAZINE";
if ( type == BookType::NEWSLETTER )
return "NEWSLETTER";
if ( type == BookType::SOFTCOPY )
return "SOFTCOPY";
else
return "NONE";
}
</code></pre>
<p><strong>Librarian.hh</strong></p>
<pre><code>#ifndef LIBRARIAN_HH
#define LIBRARIAN_HH
/*****************************************************************
* Name: Librarian.hh
* Author: Samuel Oseh
* Purpose: Librarian class method-function prototype
* ***************************************************************/
#include <iostream>
#include <string>
#include "BookItem.hh"
#include <list>
class Librarian {
private:
/* data-member */
std::string name;
Date dateOfHire;
std::list<BookItem> *books = new std::list<BookItem>;
public:
// ctor
Librarian() = default;
Librarian( const std::string &name, const Date &dateOfHire );
/* basic method-functions */
void setName( const std::string &name );
void setDateOfHire( const Date &date );
std::string getName() const { return name; };
Date &getDateOfHire() { return dateOfHire; }
void printDateOfHire() const { std::cout << dateOfHire; }
/* core functionalities */
void addBook( const BookItem &book );
void auditLibrary() const;
// dtor
~Librarian(){}
};
#endif
</code></pre>
<p><strong>Librarian.cc</strong></p>
<pre><code>/*****************************************************************
* Name: Librarian.cc
* Author: Samuel Oseh
* Purpose: Librarian class method-function definitions
* ***************************************************************/
#include <iostream>
#include "Librarian.hh"
Librarian::Librarian( const std::string &n, const Date &d ) {
name = n;
dateOfHire = d;
}
void Librarian::setName( const std::string &n ) {
name = n;
}
void Librarian::setDateOfHire( const Date &d) {
dateOfHire = d;
}
void Librarian::addBook( const BookItem &book ) {
if ( books->empty() ) {
books->push_front( book );
return;
}
for ( auto bk = books->begin(); bk != books->end(); ++bk ) {
if( book.getTitle() <= bk->getTitle() ) {
books->insert(bk, book);
return;
}
}
books->push_back( book );
}
void Librarian::auditLibrary() const {
std::cout << "Librarian: " << name << ", Date of hire: " << dateOfHire;
std::cout << "\n\nBooks:";
for ( auto bk = books->begin(); bk != books->end(); ++bk ) {
std::cout << "\nName of book: " << bk->getTitle();
std::cout << "\nAuthor of book: " << bk->getAuthor();
std::cout << "\nBook category: " << bk->getCategory();
std::cout << "\nPublication date: ";
bk->printPubDate();
std::cout << "\nISBN number: " << bk->getIsbn();
std::cout << "\nStatus of book: " << bk->getStatus();
std::cout << "\nType of book: " << bk->getType();
std::cout << "\n\n";
}
}
</code></pre>
|
[] |
[
{
"body": "<pre><code>unsigned int month;\nunsigned int day;\nunsigned int year;\n</code></pre>\n<p>may also be written in one line</p>\n<pre><code>unsigned int month, day, year;\n</code></pre>\n<p>You use unsigned int, that's ok, but you should nevertheless\nuse int, especially for small numbers.\nunsigned int is mostly used for transfering data from and\nto storage devices / network streams.\nsigned int is better portable, because some other\nprogramming languages doesn't support unsigned int.\nsigned int allows often easier debugging,\nbecause a -1 is often easier to detect than a 4294967295.</p>\n<pre><code>std::string BookItem::getStatus() const { \n if ( status == BookStatus::AVAILABLE )\n return "AVAILABLE";\n else if ( status == BookStatus::REFERENCE )\n return "REFERENCE";\n else if ( status == BookStatus::UNAVAILABLE )\n return "UNAVAILABLE";\n else if ( status == BookStatus::LOANED )\n return "LOANED";\n else if ( status == BookStatus::RESERVED )\n return "RESERVED";\n else\n return "NONE";\n}\n</code></pre>\n<p>This may also be written as:</p>\n<pre><code>std::string BookItem::getStatus() const { \n if ( status == BookStatus::AVAILABLE ) return "AVAILABLE";\n if ( status == BookStatus::REFERENCE ) return "REFERENCE";\n if ( status == BookStatus::UNAVAILABLE ) return "UNAVAILABLE";\n if ( status == BookStatus::LOANED ) return "LOANED";\n if ( status == BookStatus::RESERVED ) return "RESERVED";\n return "NONE";\n}\n</code></pre>\n<p>You may also just use a switch/case.</p>\n<p>.</p>\n<p>When using:</p>\n<pre><code>std::cout << "\\nAuthor of book: " << bk->getAuthor();\nstd::cout << "\\nBook category: " << bk->getCategory();\n</code></pre>\n<p>Better do it this way:</p>\n<pre><code>std::cout << "Author of book: " << bk->getAuthor() << std::endl;\nstd::cout << "Book category: " << bk->getCategory() << std::endl;\n</code></pre>\n<p>Otherwise your code looks good at the first view.\nMaybe add some additional header text description.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T05:38:41.550",
"Id": "493341",
"Score": "0",
"body": "Thanks... I felt a negative value for dates aren't logical, lol"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T07:07:18.610",
"Id": "493346",
"Score": "5",
"body": "@paladin Why are you giving everything in one block of code? You can also write text outside and not through comments"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T07:15:42.593",
"Id": "493348",
"Score": "0",
"body": "I'm a lazy ass. Sorry :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T09:54:38.440",
"Id": "493372",
"Score": "4",
"body": "I really had a hard time reading it though"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T11:47:11.237",
"Id": "493381",
"Score": "1",
"body": "Please read through all of our FAQ's in the [help center](https://codereview.stackexchange.com/help). Code only alternate solutions are considered poor answers on code review. This answer is currently in the `Low Quality Post` queue which is used for deleting answers that don't meet Code Review guidelines. I didn't put it there, but I agree with the low quality."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T11:56:37.583",
"Id": "493382",
"Score": "3",
"body": "I recommend that you use some of the 10 answers on your question as a basis for writing answers, the ones that contain more text and less code are the ones that are more highly voted. Move the comments out of the code in this answer and put them before the code and you will have a pretty good answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T01:38:49.453",
"Id": "493444",
"Score": "0",
"body": "Maybe the user interface of this site just sucks and writing an answer in _kate_ is easier, even when using c++ comments? But thanks for the downvotes, next time I'll prefer to not give any answer. Please, if you think deleting an answer will help OP, you are welcomed ;-) (I'm a bit sad, because of your critic, even if it's valid :p) Hey, couldn't you just also edit my answer?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T11:46:53.630",
"Id": "493473",
"Score": "1",
"body": "@paladin `Hey, couldn't you just also edit my answer?` We could do that, but then you wouldn't have learned how to write a good answer on Code Review. You are making contributions to the Code Review community, we are trying to improve the quality so that they are good contributions. That way you can become a valued member of the community."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T00:39:46.147",
"Id": "250771",
"ParentId": "250769",
"Score": "-2"
}
},
{
"body": "<h2><code>constexpr</code></h2>\n<p>Since <code>monthsPerYear</code> is a compile time constant, you should declare it <code>constexpr</code> instead of <code>const</code>. <a href=\"https://stackoverflow.com/questions/14116003/difference-between-constexpr-and-const\">See this answer for more details about <code>constexpr</code></a></p>\n<h2><code>Date</code> constructors</h2>\n<p>Your <code>Date</code> constructors take <code>int</code> whereas your data members are <code>unsigned int</code>.</p>\n<p>Your constructors are calling another constructor of the same class, which in turn calls <code>setDate</code> method, which just seems like a pointless route. Typically, you would initialize your data members like this:</p>\n<pre><code>Date():\n d{1}, m{1}, y{1970}\n{\n /// EMPTY\n}\n\nDate(unsigned int d, unsigned int m, unsigned int y):\n d{d}, m{m}, y{y}\n{\n /// EMPTY\n} \n</code></pre>\n<p>Notice that the call to <code>setDate</code> method is now redundant? While it doesn't matter much for builtin types, it might degrade your performance if you have heavy user-defined types since they will be default constructed. <a href=\"https://stackoverflow.com/questions/926752/why-should-i-prefer-to-use-member-initialization-lists\">More about member initialization lists</a></p>\n<p>The call to <code>setDate</code> could be replaced by call to a method called <code>validateDate()</code>, whose sole purpose is to validate the date, instead of validating AND setting the values of the data member. A lot of your member functions can be simplified by just using <code>validateDate()</code>.</p>\n<p>On another note, I question the purpose of the last two user provided types. Ask yourself what's the use case of setting just the day or day/month?</p>\n<p>Since your class only contains builtin types, you could omit the body and simply declare it as <code>default</code>.</p>\n<pre><code>Date(const Date& rhs) = default;\n</code></pre>\n<p><a href=\"https://stackoverflow.com/questions/6502828/what-does-default-mean-after-a-class-function-declaration\">See here for what <code>default</code> does</a>.</p>\n<p>Same goes for the copy assignment operator.</p>\n<p>Your use of <code>std::move</code> is pretty much pointless when it comes to builtin types. Anyway, you probably don't want to use <code>std::move</code> in a copy constructor.</p>\n<h2><code>checkDay</code></h2>\n<p>You're using the value of <code>year</code> before setting it.</p>\n<p>I would put the condition to check if it's a leap year inside its own method.</p>\n<pre><code>bool isLeapYear() const\n{\n return year % 400 == 0 || ( year % 4 == 0 && year % 100 != 0 );\n}\n</code></pre>\n<p>Then your <code>checkDay</code> condition can be written more succinctly as</p>\n<pre><code>if((testDay <= daysPerMonth[month]) || (isLeapYear() && month == 2 && testDay == 29))\n</code></pre>\n<p>Putting <code>isLeapYear()</code> first helps in short circuit evaluation, meaning if <code>isLeapYear()</code> fails, the rest of the conditions won't be checked.</p>\n<p>Also, consider returning a bool whether the test succeeds or not, and let the caller of the method decide what to do if it the test fails (such as throw an invalid argument exception).</p>\n<h2><code>BookItem</code></h2>\n<p>Again, use member initialization lists to set your data members. Use <code>default</code> for the copy constructor and copy assignment operator.</p>\n<h2>Use <code>switch</code> statements</h2>\n<p>In your getStatus and getType methods, use switch statements. They lend well to this kind of scenario and look much cleaner.</p>\n<pre><code>switch(status)\n{\n case BookStatus::AVAILABLE:\n return "AVAILABLE";\n case BookStatus::Reference:\n return "REFERENCE";\n ...\n default:\n return "NONE";\n}\n</code></pre>\n<h2>Use <code>default</code> for destructor</h2>\n<p>Since your <code>BookItem</code> destructor isn't doing any non-trivial, you should just declare it <code>default</code> and let the compiler handle it.</p>\n<pre><code>~BookItem() = default;\n</code></pre>\n<h2>Return <code>const std::string&</code> or <code>std::string_view</code></h2>\n<p>Your getter methods return a copy of a <code>std::string</code>, which isn't something you always want (especially for getters). <code>std::string</code> allocates on the heap (well, sometimes it doesn't; look up Small String Optimization if you're interested), which means every time you call a getter, odds are memory is being allocated and deallocated on the heap. If you're not going to change the data, you're just wasting time constructing a new string.</p>\n<p>Consider returning a const reference <code>const std::string&</code>, or if you have C++17 compliant compiler, a <code>std::string_view</code>. <a href=\"https://stackoverflow.com/questions/20803826/what-is-string-view\">See here for <code>std::string_view</code></a></p>\n<h2><code>std::vector</code> over <code>std::list</code></h2>\n<p>I can see why you'd want <code>std::list</code>, since you want to insert books in a sorted manner. However, in almost all cases, you want to use <code>std::vector</code> over a <code>std::list</code>. In fact, I would argue that you don't ever need a <code>std::list</code> over <code>std::vector</code>. It's to do with the fact the <code>std::vector</code> stores elements contiguously, which benefits from something called <code>cache locality</code>. That is an answer on its own, so you should see this. <a href=\"https://stackoverflow.com/questions/16699247/what-is-a-cache-friendly-code\">Cache friendly code</a></p>\n<p>You can use <code>std::sort</code> on the <code>std::vector</code>, and using a lambda as a custom comparator.</p>\n<pre><code>std::vector<BookItem> inventory.\ninventory.push_back(...);\ninventory.push_back(...);\n...\n\nstd::sort(inventory.begin(), inventory.end(), [](const BookItem& a, const BookItem& b){ return a.getTitle() < b.getTitle(); });\n\n</code></pre>\n<h2><code>new</code> keyword</h2>\n<p>Unless you have good reason, you want to use the STL provided smart pointers instead of <code>new</code> and <code>delete</code>. Right now, your code is leaking memory because you haven't called <code>delete</code> on the list, and this is a biggest pitfall of using raw <code>new</code> and <code>delete</code>.</p>\n<p>And why are using allocating the list on the heap at all? <code>std::list</code> allocates on the heap by default; there is no reason to allocator the <code>list</code> object on the heap.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T09:01:57.213",
"Id": "493368",
"Score": "0",
"body": "Firstly, I appreciate the review. Wouldn't the vector introduce performance issues e.g when the books mostly added starts with letter 'A'... You would have to perform sorting always with O(n) or whatever complexity it takes but list is guaranteed to be O(1)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T19:04:20.050",
"Id": "493516",
"Score": "1",
"body": "On the topic of letting methods be `default`: you could also use default values for fields in `Date` and then let the constructor be `default`. e.g. `unsigned int month = 1; unsigned int day = 1; unsigned int year = 1970;` and then `Date() = default;`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T07:43:07.063",
"Id": "250780",
"ParentId": "250769",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "250780",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T23:33:30.350",
"Id": "250769",
"Score": "2",
"Tags": [
"c++",
"object-oriented"
],
"Title": "Library Management System OOP with c++( Part2 of a series )"
}
|
250769
|
<p>I have a neural network that I am training on a loss function composed of two terms (i.e. <code>loss = loss1 + loss2</code>). Ideally, I would like for both <code>loss1</code> and <code>loss2</code> to simultaneously decrease. Although I am wondering, is there any way to ensure neither <code>loss1</code> nor <code>loss2</code> increase during training, i.e. while minimizing <code>loss</code> is the overall objective, to constrain just <code>loss1</code> to be monotonically decreasing?</p>
<p>Below I have written a simple arbitrary example whereby I construct and train a neural network on a loss function composed of two terms that are potentially competing. I simply use <code>L-BFGS</code> and <code>Adam</code> to perform this optimization. But to improve upon this code, are there any best known practices, methods, or optimizers for handling loss functions and trying to enforce a robust monotonicity constraint on constituent loss terms during training?</p>
<hr />
<pre><code>import numpy as np
import tensorflow as tf
end_it = 1000 #number of iterations
layers = [2, 20, 20, 20, 1]
#Generate training data
len_data = 10000
x_x = np.array([np.linspace(0.,1.,len_data)])
x_y = np.array([np.linspace(0.,1.,len_data)])
y_true = np.array([np.linspace(-0.2,0.2,len_data)])
N_train = int(len_data)
idx = np.random.choice(len_data, N_train, replace=False)
x_train = x_x.T[idx,:]
y_train = x_y.T[idx,:]
v1_train = y_true.T[idx,:]
sample_batch_size = int(0.01*N_train)
np.random.seed(1234)
tf.set_random_seed(1234)
import logging
logging.getLogger('tensorflow').setLevel(logging.ERROR)
tf.logging.set_verbosity(tf.logging.ERROR)
class NeuralNet:
def __init__(self, x, y, v1, layers):
X = np.concatenate([x, y], 1)
self.lb = X.min(0)
self.ub = X.max(0)
self.X = X
self.x = X[:,0:1]
self.y = X[:,1:2]
self.v1 = v1
self.layers = layers
self.weights_v1, self.biases_v1 = self.initialize_NN(layers)
self.sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=False,
log_device_placement=False))
self.x_tf = tf.placeholder(tf.float32, shape=[None, self.x.shape[1]])
self.y_tf = tf.placeholder(tf.float32, shape=[None, self.y.shape[1]])
self.v1_tf = tf.placeholder(tf.float32, shape=[None, self.v1.shape[1]])
self.v1_pred = self.net(self.x_tf, self.y_tf)
self.loss1 = tf.reduce_mean(tf.square(self.v1_pred))
self.loss2 = tf.reduce_mean(tf.square(self.v1_tf - self.v1_pred))
self.loss = self.loss1 + self.loss2
self.optimizer = tf.contrib.opt.ScipyOptimizerInterface(self.loss,
var_list=self.weights_v1+self.biases_v1,
method = 'L-BFGS-B',
options = {'maxiter': 50,
'maxfun': 50000,
'maxcor': 50,
'maxls': 50,
'ftol' : 1.0 * np.finfo(float).eps})
self.optimizer_Adam = tf.train.AdamOptimizer()
self.train_op_Adam_v1 = self.optimizer_Adam.minimize(self.loss, var_list=self.weights_v1+self.biases_v1)
init = tf.global_variables_initializer()
self.sess.run(init)
def initialize_NN(self, layers):
weights = []
biases = []
num_layers = len(layers)
for l in range(0,num_layers-1):
W = self.xavier_init(size=[layers[l], layers[l+1]])
b = tf.Variable(tf.zeros([1,layers[l+1]], dtype=tf.float32), dtype=tf.float32)
weights.append(W)
biases.append(b)
return weights, biases
def xavier_init(self, size):
in_dim = size[0]
out_dim = size[1]
xavier_stddev = np.sqrt(2/(in_dim + out_dim))
return tf.Variable(tf.truncated_normal([in_dim, out_dim], stddev=xavier_stddev), dtype=tf.float32)
def neural_net(self, X, weights, biases):
num_layers = len(weights) + 1
H = 2.0*(X - self.lb)/(self.ub - self.lb) - 1.0
for l in range(0,num_layers-2):
W = weights[l]
b = biases[l]
H = tf.tanh(tf.add(tf.matmul(H, W), b))
W = weights[-1]
b = biases[-1]
Y = tf.add(tf.matmul(H, W), b)
return Y
def net(self, x, y):
v1_out = self.neural_net(tf.concat([x,y], 1), self.weights_v1, self.biases_v1)
v1 = v1_out[:,0:1]
return v1
def callback(self, loss):
global Nfeval
print(str(Nfeval)+' - Loss in loop: %.3e' % (loss))
Nfeval += 1
def fetch_minibatch(self, x_in, y_in, v1_in, N_train_sample):
idx_batch = np.random.choice(len(x_in), N_train_sample, replace=False)
x_batch = x_in[idx_batch,:]
y_batch = y_in[idx_batch,:]
v1_batch = v1_in[idx_batch,:]
return x_batch, y_batch, v1_batch
def train(self, end_it):
it = 0
while it < end_it:
x_res_batch, y_res_batch, v1_res_batch = self.fetch_minibatch(self.x, self.y, self.v1, sample_batch_size) # Fetch residual mini-batch
tf_dict = {self.x_tf: x_res_batch, self.y_tf: y_res_batch,
self.v1_tf: v1_res_batch}
self.sess.run(self.train_op_Adam_v1, tf_dict)
self.optimizer.minimize(self.sess,
feed_dict = tf_dict,
fetches = [self.loss],
loss_callback = self.callback)
it = it + 1
def predict(self, x_star, y_star):
tf_dict = {self.x_tf: x_star, self.y_tf: y_star}
v1_star = self.sess.run(self.v1_pred, tf_dict)
return v1_star
model = NeuralNet(x_train, y_train, v1_train, layers)
Nfeval = 1
model.train(end_it)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T11:21:38.050",
"Id": "493678",
"Score": "0",
"body": "This goal would cause the search to stop at any local minima. It makes sense only for certain optimization problems where the local and global minimas are the same."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T23:08:48.570",
"Id": "493754",
"Score": "0",
"body": "@GZ0 Yes, such a loss term is useful in only certain problems. But I wonder if such a loss term can even be encoded (e.g. in a classical feedforward neural network as I've encoded above)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T13:39:03.697",
"Id": "493816",
"Score": "0",
"body": "1. Convergence of training is different from monotonically decreasing of training loss -- which is a much stronger condition. 2. Convergence is determined by both the optimization problem (i.e. the prediction and loss functions) and the optimizer you choose. 3. In your problem the overall loss function can be simplified to a regular square loss so it should not hard for the training to converge."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T17:27:15.703",
"Id": "493830",
"Score": "0",
"body": "Correct, I don't disagree with these points in theory. But my question is regarding the practicality of implementing such a loss function in the TensorFlow code. Namely, the proposed loss function requires knowing losses from previous iterations during training (and therefore the state of the neural network in the past as well for it to be a trainable parameter, as far as I can tell). But is it possible to actually train on past loss functions in TensorFlow? If so, how can this actually be encoded in the example?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-24T08:30:00.280",
"Id": "494121",
"Score": "0",
"body": "If that is really what you want, the training loop needs to be customized. You need to obtain the loss values after each training step and stop training once the monotonicity constraint is violated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-27T19:55:38.397",
"Id": "494493",
"Score": "0",
"body": "Yes, that can all be done. But there is an additional necessary step. Namely, I want the optimizer to not simply stop but to keep training (i.e. try updating weights) in such a way that the monotonicity constraint isn't broken. But the neural network (and, consequently, the optimizer) only trains its weights at the current iteration. The current weights are all it knows. The neural network does not contain any information about its weights from the past, but I believe this would be required for the optimizer I'm describing to work. To be able to do this in any way is the crux of my question."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T02:04:22.270",
"Id": "250773",
"Score": "3",
"Tags": [
"python",
"ai",
"neural-network",
"tensorflow"
],
"Title": "Constraining monotonicity in the loss function during training"
}
|
250773
|
<p>This program is a project out of Udemy course. Kindly request you to review my code and suggest insights to better it. It takes your password hashes (sha1) and then sends hashedpassword[:5] to <a href="https://haveibeenpwned.com/" rel="nofollow noreferrer">https://haveibeenpwned.com/</a> website. Gets the response and checks whether our hashed password is present in the response got from the site</p>
<p>Thanks in advance!!</p>
<pre><code>import requests
from ezhashlib import hashlib
import sys
def req_api_data(query_char):
'''Returns response for pwned website after passing the tail'''
url = 'https://api.pwnedpasswords.com/range/' + query_char
res = requests.get(url)
if res.status_code!=200:
raise RuntimeError(f'Error fetching: {res.status_code}, check the api and try again')
else:
return res
def get_pw_lead_count(hashes,hashes_to_check):
hashes = (line.split(':') for line in hashes.text.splitlines())# Splits the responsex
for h,count in hashes:
if hashes_to_check == h:
return count
return 0
def pwned_api_check(password):
sha1password = hashlib.sha1(password.encode('utf-8 ')).hexdigest().upper()
# Generatng the sha1 for your password
head,tail = sha1password[:5],sha1password[5:]
res = req_api_data(head)
#sending the head to website
return get_pw_lead_count(res,tail)
#Sending website response and tail for checking whether tail exists in the list of responses got from website.
def main():
args=list(input().split())
for passwords in args:
count = pwned_api_check(passwords)
if count:
print(f"Change your \"{passwords}\" password as it's pwned {count} times")
else:
print("You've used a good password!!")
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T03:37:03.780",
"Id": "493340",
"Score": "2",
"body": "@Marc I'd say there's not just no need for that, it's even *wrong*. If your password appeared in a breach, it's rather the fault of the breached site, not yours."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T19:06:50.467",
"Id": "493517",
"Score": "0",
"body": "Calling this a \"password strength checker\" is misleading. It checks whether a website that you have used the password on was compromised, which has nothing to do with the strength of the password but rather with the security of the website that was cracked."
}
] |
[
{
"body": "<h2>Use requests built-in validation</h2>\n<p>This:</p>\n<pre><code>if res.status_code!=200:\n raise RuntimeError(f'Error fetching: {res.status_code}, check the api and try again')\nelse:\n return res\n</code></pre>\n<p>should not raise manually; and should be replaced with</p>\n<pre><code>res.raise_for_status()\nreturn res\n</code></pre>\n<h2>Hash checking</h2>\n<p>In <code>get_pw_lead_count</code>, <code>hashes_to_check</code> should be marked <code>: str</code>. Also, if <code>count</code> is a string - likely, since it comes from a <code>split()</code> - you should cast it to <code>int()</code> before returning it.</p>\n<h2>Real arguments</h2>\n<pre><code>args=list(input().split())\n</code></pre>\n<p>is not a standard way of retrieving arguments. Instead, use <code>argparse</code> and pass arguments via command line parameters.</p>\n<p>It's also possible to retain <code>stdin</code> input as you have it, but you should in that case show a prompt.</p>\n<h2>Indentation</h2>\n<p>Count the number of spaces for each of these lines:</p>\n<pre><code> if count:\n print(f"Change your \\"{passwords}\\" password as it's pwned {count} times")\n</code></pre>\n<p>Each should be a multiple of four.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T17:18:54.923",
"Id": "250802",
"ParentId": "250774",
"Score": "3"
}
},
{
"body": "<h2>PEP8 conventions and formatting</h2>\n<p>You are already using F-strings in your code, so</p>\n<pre><code>url = 'https://api.pwnedpasswords.com/range/' + query_char\n</code></pre>\n<p>could be:</p>\n<pre><code>url = f'https://api.pwnedpasswords.com/range/{query_char}'\n</code></pre>\n<p>Spacing:</p>\n<pre><code>if res.status_code!=200:\n</code></pre>\n<p>should be:</p>\n<pre><code>if res.status_code != 200:\n</code></pre>\n<p>Ditto for:</p>\n<pre><code>for h,count in hashes:\nhead,tail = sha1password[:5],sha1password[5:]\netc\n</code></pre>\n<p>My suggestion is to use an IDE that has a linter plugin. For example Atom but there are alternatives. This will help enforce some habits. Strictly speaking, as per PEP8 conventions there should be 2 lines spacing between functions (or one within a class).</p>\n<h2>request</h2>\n<p>The variable names are not always intuitive, for instance the function get_pw_lead_count expects a parameter named 'hashes', but it is in fact the request object from your other function.</p>\n<p>This is a text parsing function basically, so rather than send a request object I would send request.text instead, that is the response. And the variable names should better reflect their purpose.</p>\n<h2>Ergonomics</h2>\n<p>Good programs should be user-friendly and intuitive to use. So if you use the input function it would be good to add a prompt like this:</p>\n<pre><code>input("Enter one or more passwords, separated by whitespace: ")\n</code></pre>\n<p>Silent input is confusing. For the split function the default separator is any whitespace but an average user is not supposed to know the inner workings of your application. Clearly indicate what kind of input is expected.</p>\n<h2>Import</h2>\n<p>It is a good habit to write Python scripts like this:</p>\n<pre><code>if __name__ == "__main__":\n main()\n</code></pre>\n<p>Thus, your main function will be run if the file is executed as a script, but not if you <strong>import</strong> it. Because you may want to import the file (or any file) to reuse some of the functions it contains, but then it should not execute anything or interfere with the upstream code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T01:01:58.300",
"Id": "493535",
"Score": "0",
"body": "Wow thanks for reviewing the code. I'll try to implement the changes ."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T19:36:02.643",
"Id": "250807",
"ParentId": "250774",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T02:25:42.037",
"Id": "250774",
"Score": "4",
"Tags": [
"python"
],
"Title": "Password strength checker (Udemy course)"
}
|
250774
|
<p>First, thanks so much for looking at my code. Over the past decade, I have tried every task management apps imaginable. I finally realized that the only way I would ever find my perfect productivity system is if I build it myself.</p>
<p>To this end, I am creating ClearHeadTodo, a productivity app that seeks to bring the <a href="https://gettingthingsdone.com/" rel="nofollow noreferrer">GTD</a> model of productivity using entirely rust if possible.</p>
<p>While for now i'm only focused on the Command Line Interface (CLI) my ultimate goal is to make this a modular piece of software where the core productivity system works no matter what medium you are utilizing (GUI or CLI)</p>
<p><strong>The Question: Control Flow Best-Practices for Testing and Scalability</strong></p>
<p><strong>The Code: 2 Main Files</strong>
For now, most of this work is broken into two files (lib.rs and main.rs respectively)</p>
<ul>
<li>lib.rs contains the main logic for the Task List</li>
<li>While main.rs contains the CLI struct which the user actually interacts with to alter the task objects.</li>
</ul>
<p><strong>Current Code Status</strong>
For right now, users can only create tasks. Tasks have a name, priority, and completion status.</p>
<ul>
<li>This is all loaded to and from a vector using a .csv to reduce database complexity</li>
</ul>
<p>I'm very proud to say that everything works from all my testing, however, now that the code is all together, it feels... difficult to scale the code base since the main command loop is basically just a huge match statement.</p>
<p>I want to use best-practices like the result data type, but i am having trouble formatting the code in such a way that would propagate the result of each function properly to the end of the main command line.</p>
<p>Specifically, whenever i try using the <code>?</code>, it throws an error saying that i'm not using the proper type (even though you can see there are several results in this code)</p>
<p><strong>Operation</strong> all work is done through just running the main rust build with any arguments,
so <code>cargo run create_task</code> will create a new task which can be shown with `cargo run list_task
Dependencies are light, just serde, along with the CSV package for it to load and unload the task list through the serializer
Cargo.toml</p>
<pre><code>[package]
name = "clear_head_todo"
version = "0.1.0"
authors = ["Mantis-Shrimp <dargondab9@gmail.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
csv = "1.1"
serde = { version = "1.0", features = ["derive"] }
</code></pre>
<p>Main.rs</p>
<pre><code>use std::io::{self, Write};
use std::io::stdout;
use clear_head_todo::TaskList;
use clear_head_todo::PriEnum;
use std::path::Path;
pub struct CLI{
pub pattern: Option<String>,
pub index: Option<String>,
pub input: Option<String>,
pub task_vec: TaskList
}
impl CLI {
pub fn parse_arguments(&mut self) {
match self.pattern.as_ref().unwrap_or(
&"no command given".to_string()) as &str{
"create_task" | "create" | "ct" | "new_task" | "new" =>
self.task_vec
.create_task(),
"list_tasks" | "lt" | "list" | "list_all" =>
self.task_vec.print_task_list(std::io::stdout()).unwrap_or(()),
"remove_task" | "remove" | "rt" | "delete_task" | "delete" =>
self.task_vec
.remove_task(
self.index.as_ref()
.unwrap()
.to_string()
.parse::<usize>()
.unwrap(),
io::stdout())
.expect("invalid index"),
"complete_task" | "complete" | "mark_complete" =>
self.task_vec.tasks[
self.index.as_ref()
.unwrap()
.parse::<usize>()
.unwrap()]
.mark_complete(),
"change_priority" | "cp" | "new_priority" | "np" =>
self.task_vec.tasks[
self.index.as_ref()
.unwrap()
.parse::<usize>()
.unwrap()]
.change_priority(
&self.input.as_ref().unwrap()[..]),
"rename_task" | "rename" | "name" | "r" =>
self.task_vec.tasks[
self.index.as_ref()
.unwrap()
.parse::<usize>()
.unwrap()]
.rename_task(
self.input.as_ref()
.unwrap()),
_ => return
};
}
pub fn cli_list_tasks(&self, mut writer: impl std::io::Write){
self.task_vec.print_task_list(writer).unwrap_or(());
}
}
fn main() {
println!("starting program");
let mut main_cli: CLI = CLI{
pattern : std::env::args().nth(1),
index: std::env::args().nth(2),
input: std::env::args().nth(3),
task_vec: TaskList{
tasks: vec![]
}
};
main_cli.task_vec.load_tasks("tasks.csv").unwrap();
main_cli.parse_arguments();
main_cli.task_vec.load_csv("tasks.csv").unwrap();
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cli_creation_test () {
let mut test_cli = CLI {
pattern: None,
index: None,
input: None,
task_vec: TaskList{tasks: vec![]},
};
assert!(test_cli.pattern == None);
assert!(test_cli.index == None);
assert!(test_cli.input == None);
assert!(test_cli.task_vec.tasks.len() == 0);
test_cli.parse_arguments();
}
#[test]
fn cli_task_creation_test () {
let mut test_cli = CLI {
pattern: Some("create_task".to_string()),
index: None,
input: None,
task_vec: TaskList{tasks: vec![]},
};
test_cli.parse_arguments();
assert!(test_cli.task_vec.tasks.len() == 1);
assert!(test_cli.task_vec.tasks[0].name == "Test Task");
assert!(test_cli.task_vec.tasks[0].completed == false);
assert!(test_cli.task_vec.tasks[0].priority == PriEnum::Optional);
}
#[test]
fn cli_task_list_test () {
//let mut good_result = Vec::new();
let mut test_cli = CLI {
pattern: Some("list_tasks".to_string()),
index: None,
input: None,
task_vec: TaskList{tasks: vec![]},
};
test_cli.parse_arguments();
}
}
</code></pre>
<p>Lib.rs (logical center of the app)</p>
<pre><code>use std::error::Error;
use std::io::{Error as OtherError, ErrorKind};
use std::fmt;
use csv::Reader;
use csv::Writer;
use std::path::{Path, PathBuf};
use std::env;
use std::str::FromStr;
use serde::ser::{Serialize, SerializeStruct, Serializer};
use serde::Serialize as AltSerialize;
pub struct TaskList {
pub tasks: Vec<Task>
}
#[derive(PartialEq)]
#[derive(Debug)]
#[repr(u8)]
#[derive(AltSerialize)]
pub enum PriEnum {
Critical = 1,
High = 2,
Medium = 3,
Low = 4,
Optional = 5,
}
impl fmt::Display for PriEnum {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let printable: &str = match *self {
PriEnum::Critical => "Critical",
PriEnum::High => "High",
PriEnum::Medium => "Medium",
PriEnum::Low => "Low",
PriEnum::Optional => "Optional"
};
write!(f, "{}", printable)
}
}
impl Serialize for Task {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut s = serializer.serialize_struct("Task", 3)?;
s.serialize_field("name", &self.name)?;
s.serialize_field("priority", &self.priority)?;
s.serialize_field("completed", &self.completed)?;
s.end()
}
}
pub fn parse_priority(expr: &str) -> Result<PriEnum, String> {
match expr.to_ascii_lowercase().trim() {
"1" | "critical" | "crit" | "c" => Ok(PriEnum::Critical),
"2" | "high" | "hi" | "h" => Ok(PriEnum::High),
"3" | "medium" | "med" | "m" => Ok(PriEnum::Medium),
"4" | "low" | "lo" | "l" => Ok(PriEnum::Low),
"5" | "optional" | "opt" | "o" => Ok(PriEnum::Optional),
"" => Ok(PriEnum::Optional), //defaults to this
_ => Err(format!("Invalid priority value")),
}
}
#[derive(PartialEq, Debug)]
pub struct Task {
pub name: String,
pub completed: bool,
pub priority: PriEnum,
}
impl TaskList {
//load tasks from either tasks.csv or testTasks.csv using the file_name
pub fn load_tasks(&mut self, file_name: &str) -> Result<(), Box<dyn Error>> {
let pathbuf = env::current_dir().unwrap().join("data").join(file_name);
let mut rdr: Reader<std::fs::File> = Reader::from_path(pathbuf)?;
for result in rdr.records() {
let record = result?;
let new_task = Task {
name: record[0].to_string(),
completed: FromStr::from_str(&record[2])?,
priority : parse_priority(&record[1])?,
};
self.tasks.push(new_task);
}
Ok(())
}
pub fn load_csv(&mut self, file_name: &str) -> Result<(), Box<dyn Error>> {
let pathbuf = env::current_dir().unwrap().join("data").join(file_name);
let mut wtr: Writer<std::fs::File> = Writer::from_path(pathbuf)?;
for index in 0..=self.tasks.len()-1{
wtr.serialize::<_>(&self.tasks[index]).unwrap();
}
Ok(())
}
pub fn create_task(&mut self) {
let new_task: Task = Task {
name: String::from("Test Task"),
completed: false,
priority: PriEnum::Optional,
};
self.tasks.push(new_task);
}
pub fn print_task_list(&self, mut writer: impl std::io::Write)->
Result<(), std::io::Error> {
if self.tasks.is_empty()==true{
return Err(OtherError::new(ErrorKind::Other, "list is empty"));
} else{
for index in 0..=self.tasks.len()-1 {
writeln!(writer, "{index},{name},{priority},{completed}",
index = index,
name = self.tasks[index].name,
priority = self.tasks[index].priority,
completed = self.tasks[index].completed)?;
}
}
Ok(())
}
pub fn remove_task(&mut self, index: usize, mut writer: impl std::io::Write) ->
Result<(), std::io::Error> {
if index < self.tasks.len() {
writeln!(writer, "Deleted {name} Task",
name = self.tasks[index].name)?;
self.tasks.remove(index);
return Ok(());
}
else {
return Err(OtherError::new(ErrorKind::Other, "Invalid Index for Deletion"));
}
}
} //end 'impl TaskList'
impl Task {
pub fn rename_task(&mut self, new_task_name: &String) {
self.name = new_task_name.to_owned();
}
pub fn mark_complete(&mut self) {
self.completed = true;
}
pub fn change_priority(&mut self, new_priority: &str) {
let new_pri = parse_priority(new_priority);
match new_pri {
Ok(i) => self.priority = i,
Err(err) => println!("{}", err),
};
}
} //end 'impl Task'
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn task_creation_test() {
let mut test_task_list = TaskList{tasks: vec![]};
test_task_list.create_task();
let test_task = &test_task_list.tasks[0];
assert!(test_task.name == "Test Task");
assert!(test_task.completed == false);
assert!(test_task.priority == PriEnum::Optional);
assert!(&test_task_list.tasks[0] == test_task);
}
#[test]
fn task_rename_test() {
let mut test_task_list = TaskList{tasks: vec![]};
test_task_list.create_task();
let test_task = &mut test_task_list.tasks[0];
test_task.rename_task(&"Changed Name".to_string());
assert!(test_task.name == "Changed Name");
}
#[test]
fn task_completion_test() {
let mut test_task_list = TaskList{tasks: vec![]};
test_task_list.create_task();
let test_task = &mut test_task_list.tasks[0];
test_task.mark_complete();
assert!(test_task.completed == true);
}
#[test]
fn task_successful_removal_test() {
let mut test_task_list = TaskList{tasks: vec![]};
let mut good_result = Vec::new();
test_task_list.create_task();
test_task_list.remove_task(0, &mut good_result).unwrap();
assert!(test_task_list.tasks.is_empty());
assert_eq!(&good_result[..], "Deleted Test Task Task\n".as_bytes());
}
#[test]
fn task_removal_fail_test(){
let mut test_task_list = TaskList{tasks: vec![]};
let mut bad_result = Vec::new();
let error = test_task_list.remove_task(0, &mut bad_result).unwrap_err();
assert_eq!(error.to_string(), "Invalid Index for Deletion");
}
#[test]
fn task_reprioritize_test() {
let mut test_task_list = TaskList{tasks: vec![]};
test_task_list.create_task();
let test_task = &mut test_task_list.tasks[0];
println!("{}", test_task.name);
test_task.change_priority("4");
assert!(test_task.priority == PriEnum::Low);
test_task.change_priority("3");
assert!(test_task.priority == PriEnum::Medium);
test_task.change_priority("2");
assert!(test_task.priority == PriEnum::High);
test_task.change_priority("1");
assert!(test_task.priority == PriEnum::Critical);
test_task.change_priority("6");
assert!(test_task.priority == PriEnum::Critical); //should NOT change on bad input
}
#[test]
fn task_print_fail_test(){
let test_task_list = TaskList{tasks: vec![]};
let mut bad_result = Vec::new();
let error = test_task_list.print_task_list(&mut bad_result).unwrap_err();
assert_eq!(error.to_string(), "list is empty");
}
#[test]
fn task_print_full_test(){
let mut test_task_list = TaskList{tasks: vec![]};
let mut good_result = Vec::new();
test_task_list.create_task();
test_task_list.print_task_list(&mut good_result).unwrap();
assert_eq!(&good_result[..], "0,Test Task,Optional,false\n".as_bytes());
}
#[test]
fn load_from_csv_sucessful_test(){
let mut test_task_list = TaskList{tasks: vec![]};
test_task_list.load_tasks("testTasks.csv").unwrap();
let test_task = &test_task_list.tasks[0];
assert!(test_task.name == "test csv task");
assert!(test_task.completed == false);
assert!(test_task.priority == PriEnum::Optional);
}
#[test]
fn load_from_csv_fail_test(){
let mut test_task_list = TaskList{tasks: vec![]};
let error = test_task_list.load_tasks("bad_file").unwrap_err();
assert!(error.to_string().contains("(os error 2)"));
}
#[test]
fn load_to_csv_successful_test(){
let mut test_task_list = TaskList{tasks: vec![]};
test_task_list.create_task();
test_task_list.tasks[0].rename_task(&"test csv task".to_string());
test_task_list.load_csv("testTask.csv").unwrap();
let rdr = Reader::from_path(
env::current_dir().unwrap().join("data").join("testTasks.csv").as_path())
.unwrap();
let mut iter = rdr.into_records();
if let Some(result) = iter.next() {
let record = result.unwrap();
assert_eq!(record, vec!["test csv task", "Optional", "false"]);
}
}
}
</code></pre>
<p>Again, Thank you for taking the time to look at this, everything should run if you put these in a cargo project, if even cargo test fails, please send me the error code</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T09:17:02.137",
"Id": "493371",
"Score": "1",
"body": "Welcome to Code Review. Can you please add your `Cargo.toml` for your dependencies and library names?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T15:54:25.583",
"Id": "493396",
"Score": "0",
"body": "hey @Zeta I added the Cargo.toml, I just use serde, and the CSV derivative to load and unload data between runs using the serializer. Thanks so much for taking the time."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T02:55:31.567",
"Id": "250775",
"Score": "2",
"Tags": [
"unit-testing",
"error-handling",
"rust"
],
"Title": "Building a GTD Productivity App Designed through Test Driven Development (TDD)"
}
|
250775
|
<p>i'm self learning programming and following CS50 course on Youtube. Below is my attempt to solve the PSET 3 Tideman. The program "seems" to work, as it doesn't produce any errors or warnings, and it seems to produce the result correctly for a few test cases(3 to 5 candidates with 8 or more voters).</p>
<p>What I would like to learn more about are as follows:</p>
<ol>
<li><p>whether or not my code contains any obvious logical errors that won't work for cases where there is a lot of tied pairs between candidates, or if there are multiple candidates who have not lost in any preference pairs, i.e., multiple candidates have not been on the losing side. How would I need to change my program to determine the result then?</p>
</li>
<li><p>Since I'm new to programming, I'm using a lot of loops and nested loops, I'm not sure if this(using a whole bunch of loops in a program) is a common/good/normal practice or if there are any more "elegant" way of doing things in programming in the professional coding world?</p>
</li>
<li><p>Any other critiques in any areas are greatly appraciated!</p>
</li>
</ol>
<p>thank you!</p>
<pre><code>#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdbool.h>
/*max number of candidates*/
#define MAX 9
/*preferences[i][j] is the number of voters who prefer i over j, i and j being candidate index*/
int preferences[MAX][MAX];
/*bool type 2-d array, if true, locked[i][j] means i is locked in over j*/
bool locked[MAX][MAX];
/*each pair has a winner and a loser index, win_margin is the number of votes won*/
struct pair
{
int winner;
int loser;
int win_margin;
};
/*used for merge-sorting the pairs, based on win_margin*/
struct left
{
int winner;
int loser;
int win_margin;
};
struct right
{
int winner;
int loser;
int win_margin;
};
char* candidate[MAX];
struct pair pairs[MAX * (MAX - 1) / 2];
int pair_count;
int candidate_count;
/*prototype functions*/
bool vote(int rank, char name[], int ranks[]);
void record_preferrences(int ranks[]);
void add_pairs(void);
void sort_pairs(void);
void merge_sort(struct pair* pairs, int beg_index, int end_index);
void merge(struct pair* pairs, int beg_index, int end_index, int mid);
void lock_pairs(void);
void print_winner(void);
int main(int argc, char* argv[])
{
char buffer[100];
int voter_count;
pair_count = 0;
/*check the commanline input validty*/
if (argc < 2 || argc > MAX)
printf("Need to put in candidates' names, and max number of candidates is 9.\n");
/*populate the candidate array from command line arguments*/
candidate_count = argc - 1;
/*memory allocation*/
for (int i = 0; i < MAX; i++)
{
if ((candidate[i] = malloc(50)) == NULL)
printf("Error. memory allocation unseccessful.\n");
}
/*populate the candidate array with candidates' names*/
for (int j = 0; j < candidate_count; j++)
{
strcpy(candidate[j], argv[j + 1]);
printf("Candidate %d is: %s\n", j + 1, candidate[j]);
}
/*clear out the graph of locked in pairs*/
for (int i = 0; i < candidate_count; i++)
{
for (int j = 0; j < candidate_count; j++)
{
locked[i][j] = false;
}
}
/*get number of voters*/
do
{
int flag = 0;
printf("Number of voters: ");
fgets(buffer, sizeof(buffer), stdin);
sscanf(buffer, "%d", &voter_count);
if (voter_count < 2)
{
printf("Enter a number that's larger than 2.\n");
continue;
}
for (int i = 0; i < strlen(buffer) - 1; i++)
{
if (isdigit(buffer[i]) == 0) /*found non-numeric character with in user input*/
{
if (buffer[i] == '-' || buffer[i] == '+')
continue;
else
{
printf("Enter only whole numbers that's larger than 2.\n");
flag = 1;
break;
}
}
}
if (flag == 1)
continue;
else
break;
} while (true);
/*gather rank info for each vote; check each vote's validty; record preferences*/
for (int i = 0; i < voter_count; i++)
{
/*ranks[i] represent voter's i th preference*/
int* ranks;
if((ranks = malloc(sizeof(int) * candidate_count) == NULL)
printf("memory allocation for voter[%d]'s ranks failed.\n", i + 1);
char name[50];
for (int j = 0; j < candidate_count; j++)
{
do
{
int flag = 0;
printf("Ballot %d, rank %d: ", i + 1, j + 1);
fgets(name, sizeof(name), stdin);
name[strlen(name) - 1] = '\0';
if (!vote(j, name, ranks))
{
printf("Invalid name entered. Please Re-enter.\n");
continue;
}
if (j >= 1)
{
for (int k = 0; k < j; k++)
{
if (strcmp(candidate[ranks[k]], candidate[ranks[j]]) == 0)
{
flag = 1;
printf("Duplicate name entered. Please Reenter.\n");
break;
}
}
if (flag == 1)
continue;
else
break;
}
else
break;
} while (true);
free(ranks);
}
/*after each vote info has been collected, record perferences in preferences[i][j]*/
record_preferrences(ranks);
printf("\n");
}
/*for each pair of candidates, record winner and loser.*/
add_pairs();
/*sort the pairs, by the winning margin of each pair*/
sort_pairs();
/*lock pairs with the largest win margin first, keep locking down the list until a cycle is created*/
lock_pairs();
print_winner();
}
/*check each vote's validty; update the ranks[], ranks[0] is the first rank of a vote*/
bool vote(int rank, char name[], int ranks[])
{
int flag = 0;
for (int k = 0; k < candidate_count; k++)
{
if (strcmp(name, candidate[k]) == 0)
{
flag = 1;
ranks[rank] = k;
break;
}
}
if (flag == 0)
return false;
else
return true;
}
/*record preferences*/
void record_preferrences(int ranks[])
{
/*loop through each rank in ranks[], */
for (int i = 0; i < candidate_count; i++)
{
/*rank[0] is preferred over all other ranks; rank[1] preferred over all ranks after it */
int winner = ranks[i];
for (int j = i + 1; j < candidate_count; j++)
{
int loser = ranks[j];
preferences[winner][loser] += 1;
}
}
}
/*record the preferences in struct pair pairs*/
void add_pairs(void)
{
for (int i = 0; i < candidate_count; i++)
{
for (int j = i + 1; j < candidate_count; j++)
{
if (preferences[i][j] > preferences[j][i])
{
pairs[pair_count].winner = i;
pairs[pair_count].loser = j;
pairs[pair_count].win_margin = preferences[i][j];
printf("pair[%d], in pair[%d][%d] winner is: %s; loser is : %s, by %d votes.\n", pair_count, i + 1, j + 1, candidate[i], candidate[j], preferences[i][j]);
}
if (preferences[j][i] > preferences[i][j])
{
pairs[pair_count].winner = j;
pairs[pair_count].loser = i;
pairs[pair_count].win_margin = preferences[j][i];
printf("pair[%d], in pair[%d][%d] winner is: %s; loser is : %s, by %d votes.\n", pair_count, i + 1, j + 1, candidate[j], candidate[i], preferences[j][i]);
}
if(preferences[i][j] == preferences[j][i])
{
pairs[pair_count].winner = i;
pairs[pair_count].loser = j;
pairs[pair_count].win_margin = 0;
printf("pair[%d], in pair[%d][%d], there is a tie between %s and %s.\n", pair_count, i + 1, j + 1, candidate[i], candidate[j]);
}
pair_count++;
}
}
printf("There are %d pairs.", pair_count);
printf("\n");
}
/*sort pairs based on the amount of winning margin in each pair*/
void sort_pairs(void)
{
printf("unsorted array is:");
for (int i = 0; i < pair_count; i++)
{
printf("%d ", pairs[i].win_margin);
}
/*use merge sort to sort the array*/
int beg_index = 0;
int end_index = pair_count - 1;
merge_sort(pairs, beg_index, pair_count - 1);
printf("\n");
printf("sorted array is:");
for (int i = 0; i < pair_count; i++)
{
printf("%d ", pairs[i].win_margin);
}
printf("\n");
}
/*produce the sorted array*/
void merge_sort(struct pair *pairs, int beg_index, int end_index)
{
if (beg_index < end_index)
{
int mid = (beg_index + end_index) / 2;
merge_sort(pairs, beg_index, mid);
merge_sort(pairs, mid + 1, end_index);
merge(pairs, beg_index, end_index, mid);
}
}
/*merge the sorted 2 half arrays*/
void merge(struct pair* pairs, int beg_index, int end_index, int mid)
{
int n1 = mid - beg_index + 1;
int n2 = end_index - (mid + 1) + 1;
struct left* left;
if((left = malloc(sizeof(struct left) * (n1 + 1))) == NULL)
printf("memory allocation failed for struct left array.\n");
struct right *right;
if((right = malloc(sizeof(struct right) * (n2 + 1))) == NULL)
printf("memory allocation failed for struct right array.\n");
for (int i = 0; i < n1; i++)
{
left[i].win_margin = pairs[beg_index + i].win_margin;
left[i].winner = pairs[beg_index + i].winner;
left[i].loser = pairs[beg_index + i].loser;
}
for (int j = 0; j < n2; j++)
{
right[j].win_margin = pairs[mid + 1 + j].win_margin;
right[j].winner = pairs[mid + 1 + j].winner;
right[j].loser = pairs[mid + 1 + j].loser;
}
int i = 0;
int j = 0;
int k = beg_index;
while (i < n1 && j < n2)
{
if (left[i].win_margin <= right[j].win_margin)
{
pairs[k].win_margin = left[i].win_margin;
pairs[k].winner = left[i].winner;
pairs[k].loser = left[i].loser;
i++;
}
else
{
pairs[k].win_margin = right[j].win_margin;
pairs[k].winner = right[j].winner;
pairs[k].loser = right[j].loser;
j++;
}
k++;
}
while (i < n1)
{
pairs[k].win_margin = left[i].win_margin;
pairs[k].winner = left[i].winner;
pairs[k].loser = left[i].loser;
i++;
k++;
}
while (j < n2)
{
pairs[k].win_margin = right[j].win_margin;
pairs[k].winner = right[j].winner;
pairs[k].loser = right[j].loser;
j++;
k++;
}
free(left);
free(right);
}
void lock_pairs(void)
{
/*the pair with the largest win_margin always got locked first*/
locked[pairs[pair_count - 1].winner][pairs[pair_count - 1].loser] = true;
/*unique_ounter counts the number of unique candidate index on the loser side; if less than
candidate_count, keep locking since locking won't create a cycle*/
int unique_counter = 1;
int flag;
for (int i = pair_count - 2; i >= 0; i--)
{
for (int j = pair_count - 1; j >= i; j--)
{
flag = 0;
/*check duplicate loser index for locked pairs so far*/
if (pairs[i].loser == pairs[j].loser)
{
flag = 1;
break;
}
}
if (flag == 0)
unique_counter += 1;
if (unique_counter < candidate_count && pairs[i].win_margin != 0)
locked[pairs[i].winner][pairs[i].loser] = true;
if(unique_counter == candidate_count)
break;
}
for (int i = pair_count - 1; i >= 0; i--)
{
if (locked[pairs[i].winner][pairs[i].loser])
{
printf("pair[%d] locked.\n", i);
}
else
{
printf("pair[%d] remains unlocked.\n", i);
}
}
}
void print_winner(void)
{
int* lost_pool;
if((lost_pool = malloc(sizeof(int) * candidate_count)) == NULL)
printf("memory allocation failed for lost_pool array.\n");
int* win_pool;
if((win_pool = malloc(sizeof(int) * candidate_count)) == NULL)
printf("memory allocation failed for win_pool array.\n");
int flag;
lost_pool[0] = pairs[pair_count - 1].loser;
int k = 1;
int l = 0;
/*for all the locked pairs, find the candidates on the losing side and add to lost_pool array;
for duplicates, only add once.*/
for (int i = pair_count - 2; i >= 0; i--)
{
flag = 0;
for (int j = pair_count - 1; j > i; j--)
{
if (pairs[i].loser == pairs[j].loser)
{
flag = 1;
break;
}
}
if (locked[pairs[i].winner][pairs[i].loser] && flag == 0)
{
lost_pool[k] = pairs[i].loser;
k++;
}
}
printf("Candidats who lost in locked pairs: ");
for (int i = 0; i < k; i++)
{
printf("%s ", candidate[lost_pool[i]]);
}
printf("\n");
/*the candidate(s) that is not in the lost_pool within the locked pairs, will be the winner*/
for (int i = 0; i < candidate_count; i++)
{
int flag = 0;
for (int j = 0; j < k; j++)
{
if (i == lost_pool[j])
{
flag = 1;
break;
}
}
if (flag == 0)
{
win_pool[l] = i;
l++;
}
}
if (l == 1)
printf("The Winner is: %s!\n", candidate[win_pool[0]]);
if (l > 1)
{
printf("The following are in the win_pool: ");
for (int i = 0; i < l; i++)
printf("%s ", candidate[win_pool[i]]);
}
free(lost_pool);
free(win_pool);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T09:01:33.740",
"Id": "493367",
"Score": "4",
"body": "Welcome to Code Review! You probably want to [edit] some links to external results for those who aren't familiar with CS50 or [Tideman](https://en.wikipedia.org/wiki/Tideman_alternative_method). That way reviewers know what you implement and your background a little bit better and thus can focus on the code. Also, if you're a beginner, consider adding the [tag:beginner] tag, as reviewers try to create more beginner friendly reviews that way. I hope you get some nice reviews :)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T10:09:02.157",
"Id": "493374",
"Score": "1",
"body": "Thanks for the tip! I will edit my post accordingly."
}
] |
[
{
"body": "<h1>Avoid global variables</h1>\n<p>The larger the project, the higher the chance that if you use global variables, that you have conflicting global variable names. Try to avoid them when possible. Here are some generic rules you can follow:</p>\n<ul>\n<li>Declare variables in the function that first uses them.</li>\n<li>Pass variables as arguments to other functions that need to access them. This can be either by pointer or by value; if the variables are large structs or if they need to be written to, pass them by pointer, otherwise by value.</li>\n<li>If you need to pass more than few variables, consider grouping them in a <code>struct</code> instead.</li>\n</ul>\n<h1>Avoid forward declarations</h1>\n<p>You had to add some forward declarations above <code>main()</code>. You can avoid this by reversing the order in which the functions appear in the source file. Doing so avoids you having to repeat yourself, and there is less chance of mistakes. Only if there are cyclic dependencies between functions should you need forward declarations.</p>\n<h1>Print errors to <code>stderr</code>, and handle them in some way</h1>\n<p>First, always print errors to <code>stderr</code>. This is especially useful if you are redirecting the output of your program to a file for example; this way the errors don't get lost, and the output doesn't contain unexpected data.</p>\n<p>However I also see that while you check for invalid conditions and print an error message, you don't do anything about it, and just let the program continue running. In the best scenario, this leads to a crash, but in the worst scenario it looks like it is running fine but the final output will be incorrect. Whenever you have an error condition, do something about it. If you don't know how to recover from the error, the immediately exit from the program in some way, for example by calling <code>exit(1)</code> or <code>abort()</code>.</p>\n<h1>Avoid assignments in <code>if</code>-statements</h1>\n<p>Prefer to do the assignment before the <code>if</code>-statement. The reason is that it is quite easy to make mistakes when combining the assignment with the condition being tested (for example, writing <code>=</code> instead of <code>==</code> or the other way around). So for example, prefer to write:</p>\n<pre><code>for (int i = 0; i < MAX; i++)\n{\n candidate[i] = malloc(50);\n\n if (!candidate[i]) {\n fprintf(stderr, "Error. Memory allocation unsuccessful.\\n");\n abort();\n }\n}\n</code></pre>\n<p>You often do this for memory allocations. I would just write a wrapper function that does the error handling, like so:</p>\n<pre><code>void *checked_malloc(size_t size) {\n void *ptr = malloc(size);\n\n if (!ptr) {\n fprintf(stderr, "Error. Memory allocation unsuccessful.\\n");\n exit(1);\n }\n\n return ptr;\n}\n</code></pre>\n<p>And then use it like so:</p>\n<pre><code>for (int i = 0; i < MAX; i++)\n{\n candidate[i] = checked_malloc(50);\n}\n</code></pre>\n<h1>Avoid magic numbers</h1>\n<p>Avoid writing <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"noreferrer\">magic numbers</a> in your code, and instead declare them as a constant variable or a macro. For example:</p>\n<pre><code>#define MAX_NAME_LENGTH 50\n...\ncandidate[i] = checked_malloc(MAX_NAME_LENGTH);\n</code></pre>\n<h1>Guard against buffer overflows</h1>\n<p>There are a few cases where you still allow buffer overflows. For example, when reading the candidate names from the command line, you use a bare <code>strcpy()</code> which doesn't check if the candidate's name fits in the allocated buffer. So for example, write:</p>\n<pre><code>strncpy(candidate[j], argv[j + 1], MAX_NAME_LENGTH);\ncandidate[j][MAX_NAME_LENGTH - 1] = 0; // Necessary!\n</code></pre>\n<p>But you could have avoided this by allocating buffers of the right size. You can do this by doing a <code>strlen()</code> before allocating <code>candidate[j]</code>, but if possible use the function <a href=\"https://en.cppreference.com/w/c/experimental/dynamic/strdup\" rel=\"noreferrer\"><code>strdup()</code></a>:</p>\n<pre><code>candidate[j] = strdup(argv[j + 1]);\n</code></pre>\n<p>But why do you need to make a copy of the name anyway? You can just have <code>candidate[j]</code> point directly to the right command line argument:</p>\n<pre><code>candidate[j] = argv[j + 1];\n</code></pre>\n<h1>Nested loops</h1>\n<p>Nesting loops and/or conditional statements is perfectly normal, and often it's just the natural way to write things. However, if you nest too much the code might "fall off" the right hand of the screen and become unreadable. Sometimes it makes sense to wrap an inner loop into a function; this way you reduce the apparent nesting of loops, and make the code simpler to reason about.</p>\n<h1>Proper input validation</h1>\n<p>Your check for a valid number of voters is both quite complex and still wrong. For example, I can give the input <code>2-3+4</code>, and this will be accepted. There will also be a potential crash if the input reaches EOF before any character (not even a newline) is read, because then <code>strlen(buffer)</code> will be zero.</p>\n<p>There are multiple ways to solve this. To keep the code short, I would do the following:</p>\n<pre><code>while (true)\n{\n char dummy;\n\n printf("Number of voters: ");\n fgets(buffer, sizeof buffer, stdin);\n\n if (sscanf(buffer, "%d %c", &voter_count, &dummy) == 1 && voter_count > 2) {\n break;\n }\n\n fprintf(stderr, "Enter a single number larger than 2!\\n");\n}\n</code></pre>\n<p>I used the fact that <code>sscanf()</code> returns the number of successful conversions, that a space in the format string matches any amount of consecutive whitespace (including the newline), and that after the newline there should not be any other character in the buffer. Thus, if it succesfully read the number and there was nothing after it except for whitespace, the return value will be <code>1</code>, otherwise it will be <code>0</code> or <code>2</code>.</p>\n<p>I also noted that your error message says the number should be larger than two, but you actually check whether the number is not smaller than two, which means it passes it if it is <em>equal to</em> or larger than two.</p>\n<h1>Make flags <code>bool</code>, give them a proper name</h1>\n<p>If you want to store a true/false value in a variable, make it a <code>bool</code>. You already do that in some places, but for some reason you use <code>int</code> for <code>flag</code>.</p>\n<p>Also, <code>flag</code> tells me what kind of variable it is, but not what is used for. Try to give a more descriptive name. For example, when checking for duplicates, name it <code>duplicate_found</code>. This way, you can write:</p>\n<pre><code>if (pairs[i].loser == pairs[j].loser)\n{\n duplicate_found = true;\n break;\n}\n\n...\n\nif (!duplicate_found)\n unique_counter++;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T15:03:20.337",
"Id": "493821",
"Score": "0",
"body": "Hi G. Sliepen, I cannot thank you enough for the time and efforts you put into this response. You have no idea how much that meant to a self-learner like myself. Thank you again!!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T17:47:13.827",
"Id": "493832",
"Score": "0",
"body": "No problem, I'm glad you find the answer useful. By the way, consider marking the answer that was most useful to you as the [accepted answer](https://codereview.stackexchange.com/help/accepted-answer)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T15:51:53.587",
"Id": "250795",
"ParentId": "250779",
"Score": "9"
}
},
{
"body": "<p>@G.Sliepen covered most of what I would have. A few spare things:</p>\n<ul>\n<li>Particularly since this is a one-translation-unit (one-file) program, mark every function except <code>main</code> to be <code>static</code>.</li>\n<li>Consider not declaring <code>left</code> and <code>right</code> structures at all, reusing <code>pair</code>; or at least <code>typedef</code> aliases to <code>pair</code> rather than re-declaring all of the members</li>\n<li>Use a separate structure tag and <code>typedef</code> name so that you don't have to precede all of your variables with <code>struct</code></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T05:48:27.827",
"Id": "493456",
"Score": "0",
"body": "If no self-referential pointers are needed then struct tags are a waste: `struct { ... } typedef Foo` is all that's needed, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T13:26:56.063",
"Id": "493487",
"Score": "0",
"body": "Yep I'm in the habit of making a tag to be able to predeclare structures in header files, but here that isn't needed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T15:27:59.783",
"Id": "493825",
"Score": "0",
"body": "Thank you sir for the clarification!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T17:02:35.223",
"Id": "250801",
"ParentId": "250779",
"Score": "5"
}
},
{
"body": "<p>Congrats on starting to program in C. I started on my own as well, so I know how overwhelming it can be at first. I'm going to be hitting you with a lot in a couple of seconds, so I want you to know that it's not possible to internalize all of this information in one day, and this is an awesome start.</p>\n<p>I agree with both of the previous answers, so I'm not going to be referencing the same points, but please do take their advice.</p>\n<p>To start with, I recommend not writing programs in the "Enter number of voters" style. Console applications are usually run like old-school batch processes, where the program arguments are passed in with the initial invocation. If your program requires a number of voters as an argument, check <code>argv</code> for it. When programs need a ton of input, such as might not be feasible to pass in via the command-line, a filename argument is usually the way to go.</p>\n<h2>Formatting</h2>\n<p>Make sure to leave whitespace between tokens. The following code is syntactically correct, but makes reading unnecessarily more tedious.</p>\n<pre><code>if(ranks = malloc...)\n printf("memory allocation...");\nchar name[50];\n</code></pre>\n<p>I also can't stress enough how much I recommend never leaving out braces after an <code>if</code> block. I'm not particularly dogmatic about code style usually, but Apple's <a href=\"https://nakedsecurity.sophos.com/2014/02/24/anatomy-of-a-goto-fail-apples-ssl-bug-explained-plus-an-unofficial-patch/\" rel=\"nofollow noreferrer\"><code>goto fail</code></a> is only one example of how this can come back to bite you.</p>\n<h2>Compiler Errors</h2>\n<p>There is an error on line 131. You forgot to remove the extra open parenthesis at the beginning of the expression.</p>\n<pre><code>src/main.c:131:67: error: expected ‘)’ before ‘printf’\n 131 | if((ranks = malloc(sizeof(int) * candidate_count) == NULL)\n | ~ ^\n | )\n 132 | printf("memory allocation for voter[%d]'s ranks failed.\\n", i + 1);\n</code></pre>\n<h2>Semantic Errors</h2>\n<p>On line 131, you meant to check whether the result from the call to <code>malloc(3)</code> was valid, but the precedence of the <code>=</code> vs <code>==</code> operators means you're doing something completely different.</p>\n<pre><code>if(ranks = malloc(sizeof(int) * candidate_count) == NULL)\n</code></pre>\n<p>What you are saying here is the following:</p>\n<ol>\n<li>Heap-allocate <code>sizeof(int) * candidate</code> bytes of memory.</li>\n<li>Check whether the result is equal to <code>NULL</code>.</li>\n<li>Assign the result of the previous check to <code>ranks</code>.</li>\n</ol>\n<p>Your ranks variable will therefore be equal to either <code>0</code> or <code>1</code>, but it will not be a pointer to heap-allocated memory. Not only are you leaking a ton of memory, your program is also not going to work as intended.</p>\n<p>The correct assign-and-check syntax uses parentheses to circumvent the lower precedence of the assignment operator, like this.</p>\n<pre><code>if ((ranks = malloc(sizeof (int) * candidate_count)) == NULL) {\n</code></pre>\n<p>On line 105, you are using a loop counter of type <code>int</code> and comparing it against the length of the buffer width. Signed vs. unsigned comparisons like this can create really hard to track bugs. You can circumvent this problem by simply declaring your loop counter as the same type as that returned by <code>strlen(3)</code>.</p>\n<pre><code>for (size_t i = 0; i < strlen(buffer); ++i) {\n ...\n}\n</code></pre>\n<p>You also aren't using the <code>end_index</code> variable you declared on line 269, in the <code>sort_pairs</code> function.</p>\n<pre><code>/*sort pairs based on the amount of winning margin in each pair*/\nvoid sort_pairs(void)\n{\n printf("unsorted array is:");\n for (int i = 0; i < pair_count; i++)\n {\n printf("%d ", pairs[i].win_margin);\n }\n\n /*use merge sort to sort the array*/\n int beg_index = 0;\n int end_index = pair_count - 1;\n merge_sort(pairs, beg_index, pair_count - 1);\n printf("\\n");\n \n printf("sorted array is:");\n for (int i = 0; i < pair_count; i++)\n {\n printf("%d ", pairs[i].win_margin);\n }\n printf("\\n");\n}\n</code></pre>\n<p>It looks like you were going to use the <code>beg_index</code> and <code>end_index</code> variables as the start and stop configuration for the for loop, but you eventually went in another direction, using the <code>pair_count</code> variable.</p>\n<p>This is fine (although I don't necessarily agree with the specific method of relying on the global <code>pair_count</code> variable), but when you do that, just take out the unnecessary variables. Keeping them in makes the system harder to understand, due to the added noise from useless variables.</p>\n<p>The following patch contains the necessary modifications to make your code compile cleanly.</p>\n<pre><code>--- src/main.c.original 2020-10-17 13:31:23.904117706 -0400\n+++ src/main.c 2020-10-17 14:07:09.290771020 -0400\n@@ -102,7 +102,7 @@\n continue;\n }\n \n- for (int i = 0; i < strlen(buffer) - 1; i++)\n+ for (size_t i = 0; i < strlen(buffer) - 1; i++)\n {\n if (isdigit(buffer[i]) == 0) /*found non-numeric character with in user input*/ \n {\n@@ -128,7 +128,7 @@\n {\n /*ranks[i] represent voter's i th preference*/\n int* ranks;\n- if((ranks = malloc(sizeof(int) * candidate_count) == NULL)\n+ if((ranks = malloc(sizeof(int) * candidate_count)) == NULL)\n printf("memory allocation for voter[%d]'s ranks failed.\\n", i + 1);\n char name[50];\n \n@@ -266,7 +266,6 @@\n \n /*use merge sort to sort the array*/\n int beg_index = 0;\n- int end_index = pair_count - 1;\n merge_sort(pairs, beg_index, pair_count - 1);\n printf("\\n");\n</code></pre>\n<p>I recommend you use stricter compilation settings for your programs. Here is what I used to compile your program, yielding the recommendations I've covered.</p>\n<pre><code>gcc -std=c17 -Wall -Wextra -Wpedantic -O0 -ggdb3 -fanalyzer -fsanitize=address,leak,undefined -D_GNU_SOURCE -o review main.c\n</code></pre>\n<p>This disables all optimizations to prevent variables being optimized away when you're debugging, although I've heard that using the <code>-Og</code> can lead to a better debugging experience. I have not gotten around to checking this for myself, but it's something you might explore.</p>\n<p>The address sanitizer library checks I've included are important, because even though your program is now compiling with no warnings or errors on my machine, this is the output I get when I run it.</p>\n<pre><code>Need to put in candidates' names, and max number of candidates is 9.\nNumber of voters: 3\n\n\n\nThere are 0 pairs.\nunsorted array is:\nsorted array is:\nsrc/main.c:366:17: runtime error: index -1 out of bounds for type 'pair [36]'\n=================================================================\n==3448==ERROR: AddressSanitizer: global-buffer-overflow on address 0x5631c33a00d4 at pc 0x5631c3389d47 bp 0x7ffce7e9c040 sp 0x7ffce7e9c030\nREAD of size 4 at 0x5631c33a00d4 thread T0\n #0 0x5631c3389d46 in lock_pairs src/main.c:366\n #1 0x5631c338488b in main src/main.c:183\n #2 0x7f1392783151 in __libc_start_main (/usr/lib/libc.so.6+0x28151)\n #3 0x5631c338324d in _start (/home/jflopezfernandez/projects/code-reviews/c/250779-c-implementation-of-tideman-algorithm/review+0xf24d)\n\n0x5631c33a00d4 is located 44 bytes to the right of global variable 'candidate' defined in 'src/main.c:40:7' (0x5631c33a0060) of size 72\n0x5631c33a00d4 is located 12 bytes to the left of global variable 'pairs' defined in 'src/main.c:41:13' (0x5631c33a00e0) of size 432\nSUMMARY: AddressSanitizer: global-buffer-overflow src/main.c:366 in lock_pairs\nShadow bytes around the buggy address:\n 0x0ac6b866bfc0: f9 f9 f9 f9 f9 f9 f9 f9 00 00 00 00 00 00 00 00\n 0x0ac6b866bfd0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\n 0x0ac6b866bfe0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\n 0x0ac6b866bff0: 00 00 00 00 04 f9 f9 f9 f9 f9 f9 f9 00 00 00 00\n 0x0ac6b866c000: 00 00 00 00 00 00 01 f9 f9 f9 f9 f9 00 00 00 00\n=>0x0ac6b866c010: 00 00 00 00 00 f9 f9 f9 f9 f9[f9]f9 00 00 00 00\n 0x0ac6b866c020: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\n 0x0ac6b866c030: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\n 0x0ac6b866c040: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\n 0x0ac6b866c050: 00 00 f9 f9 f9 f9 f9 f9 04 f9 f9 f9 f9 f9 f9 f9\n 0x0ac6b866c060: 04 f9 f9 f9 f9 f9 f9 f9 00 00 00 00 00 00 00 00\nShadow byte legend (one shadow byte represents 8 application bytes):\n Addressable: 00\n Partially addressable: 01 02 03 04 05 06 07 \n Heap left redzone: fa\n Freed heap region: fd\n Stack left redzone: f1\n Stack mid redzone: f2\n Stack right redzone: f3\n Stack after return: f5\n Stack use after scope: f8\n Global redzone: f9\n Global init order: f6\n Poisoned by user: f7\n Container overflow: fc\n Array cookie: ac\n Intra object redzone: bb\n ASan internal: fe\n Left alloca redzone: ca\n Right alloca redzone: cb\n Shadow gap: cc\n==3448==ABORTING\n</code></pre>\n<p>Disabling the sanitizer library so I could run valgrind, I got this output from the GCC static analyzer.</p>\n<pre><code>src/main.c: In function ‘print_winner’:\nsrc/main.c:415:18: warning: dereference of NULL ‘lost_pool’ [CWE-690] [-Wanalyzer-null-dereference]\n 415 | lost_pool[0] = pairs[pair_count - 1].loser;\n | ~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n ‘print_winner’: events 1-7\n |\n | 409 | if((lost_pool = malloc(sizeof(int) * candidate_count)) == NULL)\n | | ~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n | | | |\n | | | (1) allocated here\n | | (2) assuming ‘lost_pool’ is NULL\n | | (3) following ‘true’ branch (when ‘lost_pool’ is NULL)...\n | 410 | printf("memory allocation failed for lost_pool array.\\n");\n | | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n | | |\n | | (4) ...to here\n | 411 | int* win_pool;\n | 412 | if((win_pool = malloc(sizeof(int) * candidate_count)) == NULL)\n | | ~ \n | | |\n | | (5) following ‘false’ branch (when ‘win_pool’ is non-NULL)...\n |......\n | 415 | lost_pool[0] = pairs[pair_count - 1].loser;\n | | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n | | | |\n | | | (6) ...to here\n | | (7) dereference of NULL ‘lost_pool’\n |\nsrc/main.c:468:58: warning: dereference of NULL ‘win_pool’ [CWE-690] [-Wanalyzer-null-dereference]\n 468 | printf("The Winner is: %s!\\n", candidate[win_pool[0]]);\n | ~~~~~~~~^~~\n ‘print_winner’: events 1-25\n |\n | 409 | if((lost_pool = malloc(sizeof(int) * candidate_count)) == NULL)\n | | ^\n | | |\n | | (1) following ‘false’ branch (when ‘lost_pool’ is non-NULL)...\n |......\n | 412 | if((win_pool = malloc(sizeof(int) * candidate_count)) == NULL)\n | | ~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n | | | |\n | | | (2) ...to here\n | | | (3) allocated here\n | | (4) assuming ‘win_pool’ is NULL\n | | (5) following ‘true’ branch (when ‘win_pool’ is NULL)...\n | 413 | printf("memory allocation failed for win_pool array.\\n");\n | | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n | | |\n | | (6) ...to here\n |......\n | 421 | for (int i = pair_count - 2; i >= 0; i--)\n | | ~~~\n | | |\n | | (7) following ‘false’ branch (when ‘i < 0’)...\n |......\n | 440 | printf("Candidats who lost in locked pairs: ");\n | | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n | | |\n | | (8) ...to here\n | 441 | for (int i = 0; i < k; i++)\n | | ~~~\n | | |\n | | (9) following ‘true’ branch (when ‘i < k’)...\n | | (11) following ‘false’ branch (when ‘i >= k’)...\n | 442 | {\n | 443 | printf("%s ", candidate[lost_pool[i]]);\n | | ~\n | | |\n | | (10) ...to here\n | 444 | }\n | 445 | printf("\\n");\n | | ~~~~~~~~~~~~\n | | |\n | | (12) ...to here\n |......\n | 449 | for (int i = 0; i < candidate_count; i++)\n | | ~~~ ~~~\n | | | |\n | | | (20) ...to here\n | | (13) following ‘true’ branch...\n | | (21) following ‘false’ branch...\n | 450 | {\n | 451 | int flag = 0;\n | | ~~~~\n | | |\n | | (14) ...to here\n | 452 | for (int j = 0; j < k; j++)\n | | ~~~\n | | |\n | | (15) following ‘true’ branch (when ‘j < k’)...\n | 453 | {\n | 454 | if (i == lost_pool[j])\n | | ~ ~\n | | | |\n | | | (16) ...to here\n | | (17) following ‘true’ branch...\n | 455 | {\n | 456 | flag = 1;\n | | ~~~~~~~~\n | | |\n | | (18) ...to here\n |......\n | 460 | if (flag == 0)\n | | ~\n | | |\n | | (19) following ‘false’ branch (when ‘flag != 0’)...\n |......\n | 467 | if (l == 1)\n | | ~\n | | |\n | | (22) ...to here\n | | (23) following ‘true’ branch (when ‘l == 1’)...\n | 468 | printf("The Winner is: %s!\\n", candidate[win_pool[0]]);\n | | ~~~~~~~~~~~\n | | |\n | | (24) ...to here\n | | (25) dereference of NULL ‘win_pool’\n |\n</code></pre>\n<p>And here is the valgrind output from running your program after rebuilding without the <code>-fsanitize=address,leak,undefined</code> option.</p>\n<pre><code>[jflopezfernandez@www 250779-c-implementation-of-tideman-algorithm]$ valgrind --leak-check=full --show-leak-kinds=all ./review\n==3688== Memcheck, a memory error detector\n==3688== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.\n==3688== Using Valgrind-3.16.1 and LibVEX; rerun with -h for copyright info\n==3688== Command: ./review\n==3688== \nNeed to put in candidates' names, and max number of candidates is 9.\nNumber of voters: 3\n\n\n\nThere are 0 pairs.\nunsorted array is:\nsorted array is:\n==3688== Invalid write of size 4\n==3688== at 0x10A81A: print_winner (main.c:415)\n==3688== by 0x10972C: main (main.c:185)\n==3688== Address 0x4a3ce00 is 0 bytes after a block of size 0 alloc'd\n==3688== at 0x483A77F: malloc (vg_replace_malloc.c:307)\n==3688== by 0x10A7AD: print_winner (main.c:409)\n==3688== by 0x10972C: main (main.c:185)\n==3688== \n==3688== Invalid read of size 4\n==3688== at 0x10A98B: print_winner (main.c:443)\n==3688== by 0x10972C: main (main.c:185)\n==3688== Address 0x4a3ce00 is 0 bytes after a block of size 0 alloc'd\n==3688== at 0x483A77F: malloc (vg_replace_malloc.c:307)\n==3688== by 0x10A7AD: print_winner (main.c:409)\n==3688== by 0x10972C: main (main.c:185)\n==3688== \n==3688== Conditional jump or move depends on uninitialised value(s)\n==3688== at 0x483DC75: strlen (vg_replace_strmem.c:459)\n==3688== by 0x48DDAB7: __vfprintf_internal (in /usr/lib/libc-2.32.so)\n==3688== by 0x48C8BBE: printf (in /usr/lib/libc-2.32.so)\n==3688== by 0x10A9B5: print_winner (main.c:443)\n==3688== by 0x10972C: main (main.c:185)\n==3688== \nCandidats who lost in locked pairs: \n==3688== \n==3688== HEAP SUMMARY:\n==3688== in use at exit: 450 bytes in 12 blocks\n==3688== total heap usage: 16 allocs, 4 frees, 2,498 bytes allocated\n==3688== \n==3688== 0 bytes in 3 blocks are definitely lost in loss record 1 of 2\n==3688== at 0x483A77F: malloc (vg_replace_malloc.c:307)\n==3688== by 0x109516: main (main.c:131)\n==3688== \n==3688== 450 bytes in 9 blocks are still reachable in loss record 2 of 2\n==3688== at 0x483A77F: malloc (vg_replace_malloc.c:307)\n==3688== by 0x10925C: main (main.c:72)\n==3688== \n==3688== LEAK SUMMARY:\n==3688== definitely lost: 0 bytes in 3 blocks\n==3688== indirectly lost: 0 bytes in 0 blocks\n==3688== possibly lost: 0 bytes in 0 blocks\n==3688== still reachable: 450 bytes in 9 blocks\n==3688== suppressed: 0 bytes in 0 blocks\n==3688== \n==3688== Use --track-origins=yes to see where uninitialised values come from\n==3688== For lists of detected and suppressed errors, rerun with: -s\n==3688== ERROR SUMMARY: 4 errors from 4 contexts (suppressed: 0 from 0)\n</code></pre>\n<p>As the static analyzer and valgrind both show, there are errors in the code.</p>\n<p>I ran the program by itself to see what would happen, and this was the output.</p>\n<pre><code>Need to put in candidates' names, and max number of candidates is 9.\nNumber of voters: 3\n\n\n\nThere are 0 pairs.\nunsorted array is:\nsorted array is:\nCandidats who lost in locked pairs: \n</code></pre>\n<p>Whatever the error is (I honestly skimmed the output, it's almost time for dinner c:), it's not causing the program to crash. This is bad, because you always want to fail as early as possible, allowing you to detect errors as early in the development process as you can. It's always easier to fix errors sooner rather than later.</p>\n<p>All in all, this is a solid start, and I commend you for taking the first step. If I can make a suggestion, your next steps should be the following:</p>\n<ol>\n<li>Learn how to use a debugger, whether it's GDB or LLDB (or whatever)</li>\n<li>Read the GCC, Clang, or whatever compiler you use's manual to figure out how to best configure your program for compilation for diagnostics, debuggin, profiling, static analysis, etc.</li>\n<li>Learn how to use valgrind</li>\n</ol>\n<p>Programming in C is awesome, and I love it, but I wasted <strong>hours</strong> of my life using <code>printf</code> statements to debug programs when following the advice to learn how to actually debug would have saved me hours of frustration. And remember, you can't <code>printf</code> if your program doesn't have an open file descriptor to write to, so if you write a daemon or a shared library, the <code>printf</code> method gets even harder to hack (i.e., you could use syslog for a daemon, etc.).</p>\n<p>By the way, if you don't have a copy or just haven't read "The C Programming Language" by Brian Kernighan and Dennis Ritchie, don't wait. I didn't buy the book for years because I was outraged that a 200-something page book was so expensive (especially when I already had "The C++ Programming Language" by Bjarne Stroustroup, which I bought for nearly the same price). Trust me, the book is worth every penny. If you can swing it, "The Unix Programming Environment" (also by Brian Kernighan, this time with Rob Pike) is also an awesome read. It will contextualize all of the perceived idiosyncracies of programming in C.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T15:29:46.200",
"Id": "493826",
"Score": "0",
"body": "Thank you and i will definitely try out the debugger! I have been trying to use debug tool in Visual Studio 2019, but it just refused to work...and the resulting mountain of printf() statments, lol. And yes, i think some point down the road, i will definitely grab that book! It has come up on my searches multiple times now..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T18:45:37.170",
"Id": "250804",
"ParentId": "250779",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T07:14:54.403",
"Id": "250779",
"Score": "7",
"Tags": [
"c"
],
"Title": "C Implementation of Tideman Algorithm"
}
|
250779
|
<p>This program allows users to manage questions and quiz users from years of historical events. I'm looking for suggestions on how can I better organize my code, maybe apply OOP for functions and avoid using global variable <code>data_filename</code>.</p>
<pre><code>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from enum import Enum
import os
import pickle
import random
data_filename = 'program.obj'
def read_int(prompt='> ', errmsg='Invalid number!'):
number = None
while number is None:
try:
number = int(input(prompt))
except ValueError:
print(errmsg)
return number
def display_menu():
print('What do you want to do?')
print('[1] List all historical events')
print('[2] Add event')
print('[3] Remove event')
print('[4] Quiz')
print('[5] Statistics')
print('[6] Clear statistics') # TODO: move to options submenu
print('[7] Exit')
def clear_screen():
print(chr(27) + "[2J")
def pause():
input('Press any key to continue...')
def yes_or_no(prompt='Proceed? [y|n]\n> ', errmsg='Valid answers are y and n.'):
answer = input(prompt).strip().lower()
while answer != 'y' and answer != 'n':
print(errmsg)
answer = input(prompt).strip().lower()
return answer
def read_data_file():
file = open(data_filename, 'a+b')
file.seek(0)
data = {'events': [], 'statistics': {'total_successes': 0, 'total_failures': 0}}
if os.path.getsize(data_filename) > 0:
data = pickle.load(file)
file.close()
return data
def list_events(data):
events = data['events']
if len(events) == 0:
print('Event list is empty!')
else:
print('Historical events:')
for event in events:
print(event)
def add_event(data):
events = data['events']
year = read_int(prompt='Enter year: ')
description = input('Enter description: ')
events.append({'year': year, 'description': description})
print('Successfully added a new historical event!')
def remove_event(data):
events = data['events']
if len(events) == 0:
print('Event list is empty!')
else:
for event in events:
print(events.index(event), event)
index = read_int('Which event do you want to delete? ')
try:
events.pop(index)
print('Successfully deleted event!')
except IndexError:
print('Number out of range!')
def quiz(data):
events = data['events']
stats = data['statistics']
if len(events) == 0:
print('Event list is empty!')
else:
num = read_int(prompt='How many questions should I ask? ')
if 0 < num <= len(events):
for event in random.sample(events, num):
print(event['description'])
year = read_int('In which year was following event occurred? ')
if year == event['year']:
stats['total_successes'] += 1
print('Good answer!')
else:
stats['total_failures'] += 1
print('Bad answer!')
elif num < 0:
print('Number of questions can\'t be negative!')
else:
print('Too much questions!')
def display_stats(data):
stats = data['statistics']
tries = stats['total_successes'] + stats['total_failures']
if tries == 0:
total_successes = 0
total_failures = 0
else:
total_successes = stats['total_successes']/tries * 100
total_failures = stats['total_failures']/tries * 100
print('Statistics')
print('Total: {0:10.2f}% successes, {1:10.2f}% failures'.format(total_successes, total_failures))
def clear_stats(data):
answer = yes_or_no('Are you sure you want to clear statistics? [y|n]\n> ')
if answer == 'y':
data['statistics'] = {'total_successes': 0, 'total_failures': 0}
print('Successfully cleared statistics!')
else:
print('Statistics left unchanged.')
# TODO: settings submenu
# def settings(data):
# print('-' * 10)
# print('Program settings')
# print('-' * 10)
# print('[1] Clear statistics')
# print('[2] Back')
# user_choice = read_int()
# while user_choice != 2:
# if user_choice == 1:
# clear_stats(data)
def update_data_file(data):
file = open(data_filename, 'wb')
pickle.dump(data, file)
file.close()
class Choices(Enum):
list_events = 1
add_event = 2
remove_event = 3
quiz = 4
statistics = 5
clear_stats = 6
exit = 7
program_data = read_data_file()
choice = None
while choice != Choices.exit.value:
clear_screen()
display_menu()
choice = read_int()
if choice == Choices.list_events.value:
list_events(program_data)
elif choice == Choices.add_event.value:
add_event(program_data)
elif choice == Choices.remove_event.value:
remove_event(program_data)
elif choice == Choices.quiz.value:
quiz(program_data)
elif choice == Choices.statistics.value:
display_stats(program_data)
elif choice == Choices.clear_stats.value:
clear_stats(program_data)
elif choice == Choices.exit.value:
print('Good bye!')
else:
print('Invalid choice!')
update_data_file(program_data)
pause()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T09:57:56.953",
"Id": "493373",
"Score": "1",
"body": "awesome, i'd say the code is much more readable than [before](https://codereview.stackexchange.com/questions/250339/task-management-program-in-python)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T16:47:26.303",
"Id": "493401",
"Score": "0",
"body": "As always with python, I suggest to apply black : https://pypi.org/project/black/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T16:48:47.660",
"Id": "493402",
"Score": "0",
"body": "Use a \"with\" context handler for opening / closing files"
}
] |
[
{
"body": "<h2>Constants</h2>\n<p><code>data_filename</code> should be capitalized, since it's a global constant.</p>\n<h2>Early-return</h2>\n<p>There's no need to use <code>number</code> as the condition on your <code>while</code>; instead:</p>\n<pre><code>number = None\nwhile number is None:\n try:\n number = int(input(prompt))\n except ValueError:\n print(errmsg)\nreturn number\n</code></pre>\n<p>can be</p>\n<pre><code>while True:\n try:\n return int(input(prompt))\n except ValueError:\n print(errmsg)\n</code></pre>\n<h2>Menu management</h2>\n<p><code>display_menu</code> could use a sequence of tuples, better yet a sequence of named tuples or <code>@dataclass</code>es, each having a title string attribute and a callable attribute. Then your <code>display_menu</code> could be</p>\n<pre><code>print('What do you want to do?')\nprint('\\n'.join(f'[{i}] {item.title}' for i, item in enumerate(menu, 1)))\n</code></pre>\n<p>I see that you also have a <code>Choices</code> enum. That's not bad, and you could potentially use both an enum and the suggestion above, so long as you have a dictionary of enum-choices-to-function-references.</p>\n<h2>Membership tests</h2>\n<pre><code>answer != 'y' and answer != 'n'\n</code></pre>\n<p>can be</p>\n<pre><code>answer not in {'y', 'n'}\n</code></pre>\n<h2>Loop structure</h2>\n<p>Avoid having to call <code>input</code> twice; this:</p>\n<pre><code>answer = input(prompt).strip().lower()\nwhile answer != 'y' and answer != 'n':\n print(errmsg)\n answer = input(prompt).strip().lower()\nreturn answer\n</code></pre>\n<p>can be</p>\n<pre><code>while True:\n answer = input(prompt).strip().lower()\n if answer in {'y', 'n'}:\n return answer\n print(errmsg)\n</code></pre>\n<h2>File operations</h2>\n<pre><code>file = open(data_filename, 'a+b')\nfile.seek(0)\n</code></pre>\n<p>has a few issues:</p>\n<ul>\n<li>Newly-opened file handles do not need an initial seek-to-beginning; that's redundant if you open in read-binary mode</li>\n<li>You should be using <code>with</code> and avoiding an explicit <code>close()</code></li>\n<li>You should only bother to initialize your default <code>data</code> when needed</li>\n<li>You want to check whether the file exists, not its size</li>\n</ul>\n<p>So:</p>\n<pre><code>if os.path.exists(data_filename):\n with open(data_filename, 'rb') as file:\n return pickle.load(file)\nreturn {'events': [], 'statistics': {'total_successes': 0, 'total_failures': 0}}\n</code></pre>\n<h2>Redundant predicates</h2>\n<pre><code>if 0 < num <= len(events):\n ...\nelif num < 0:\n print('Number of questions can\\'t be negative!')\nelse:\n print('Too much questions!')\n</code></pre>\n<p>needs to be re-thought. First, <code>too much questions</code> should be <code>too many questions</code>. Also, what if the user enters 0? Surely that's not "too many questions", but that's what will be printed. Suggested:</p>\n<pre><code>if num < 1:\n print('Not enough questions.')\nelif num > len(events):\n print('Too many questions.')\nelse:\n ...\n</code></pre>\n<h2>Stronger-typed, stronger-structured data</h2>\n<pre><code>stats['total_successes'] + stats['total_failures']\n</code></pre>\n<p>is an example of what I've seen called "data pasta". Dictionaries are being abused, here, when something like a <code>@dataclass</code> containing type hints is more appropriate.</p>\n<h2>String interpolation</h2>\n<pre><code>'Total: {0:10.2f}% successes, {1:10.2f}% failures'.format(total_successes, total_failures)\n</code></pre>\n<p>is more easily expressed as</p>\n<pre><code>(\n f'Total: {total_successes:10.2f}% successes, '\n f'{total_failures:10.2f}% failures'\n)\n</code></pre>\n<p>The line split is optional but better for legibility.</p>\n<h2>String escapes</h2>\n<pre><code>'Number of questions can\\'t be negative!'\n</code></pre>\n<p>is more easily written as</p>\n<pre><code>"Number of questions can't be negative!"\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T18:10:08.777",
"Id": "493415",
"Score": "0",
"body": "I have an issue with your answer. If a file exists, without `file.seek(0)` I'm getting `EOFError: Ran out of input`. Otherwise, this program instead of creating a file and returning empty settings object throws exception `FileNotFoundError`. Code: https://dpaste.com/7ULK8KJYD"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T18:11:22.103",
"Id": "493416",
"Score": "0",
"body": "That's deeply strange. Is it a normal file, or a FIFO (etc)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T18:12:12.827",
"Id": "493417",
"Score": "0",
"body": "This is a normal file. Maybe I'll send the complete project code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T18:13:47.357",
"Id": "493418",
"Score": "0",
"body": "Oh, I see what's happening. You open in append mode, but then seek? Why?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T18:14:32.130",
"Id": "493419",
"Score": "0",
"body": "You should just be opening in read-binary mode."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T18:19:09.660",
"Id": "493420",
"Score": "0",
"body": "I open in the append mode because I want the file to be created before reading. I have an another issue if file doesn't exist function `os.path.getsize(DATA_FILENAME)` throws an exception `FileNotFoundError`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T18:19:46.547",
"Id": "493421",
"Score": "0",
"body": "I mean, yes? What else would you expect? If a file doesn't exist, what do you think its size should be?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T18:22:46.743",
"Id": "493422",
"Score": "1",
"body": "Problem solved. Changed if statement condition to `os.path.exists(DATA_FILENAME) and os.path.getsize(DATA_FILENAME) > 0`."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T13:21:32.897",
"Id": "250789",
"ParentId": "250781",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T07:53:27.080",
"Id": "250781",
"Score": "4",
"Tags": [
"python",
"quiz"
],
"Title": "Python history quiz program"
}
|
250781
|
<h1>Motivation</h1>
<p>Previously, on the <a href="https://emacs.stackexchange.com/q/61246/20061">Emacs stack exchange</a>:</p>
<blockquote>
<p>In Org mode, when I open a link (<kbd>C-c C-o</kbd>) [...] [that] contains a wildcard, such as <code>file:3_o*.pdf</code>, Emacs opens it through <code>dired</code> instead [...] within Emacs.</p>
<p>I would instead have it open the first match of that pattern in the system application …</p>
</blockquote>
<p>The handling of <code>file:</code> links is hard-coded in Org mode. If there is any wildcard in the given <code>path</code>, then <code>org-link-open</code> will nope out of the situation and instead call <code>dired</code>. And while one could change Org mode's source code in the local elisp files, I remembered that you can change the arguments or results of functions with <a href="https://www.gnu.org/software/emacs/manual/html_node/elisp/Advising-Functions.html" rel="noreferrer">advices</a>.</p>
<h1>Solution</h1>
<p>I opted for an advice <code>:around</code> <code>org-link-open</code> with the following code:</p>
<pre class="lang-lisp prettyprint-override"><code>(defun my-org-expand-file-link (link)
"Expand a pattern in LINK to the first matching file.
Returns the original LINK if no file matches the pattern in LINK or if it is not
a link of type 'file:'. See info node `(org)External links' for more information."
(let ((type (org-element-property :type link))
(path (org-element-property :path link)))
(cond
((equal type "file")
(let ((candidates (file-expand-wildcards path)))
(if candidates
(org-element-put-property (org-element-copy link) :path (car candidates))
link)))
(t link))))
(defun my-org-link-open-advice (orig-fun link &rest args)
"Advice for ORIG-FUN that expands patterns in 'file:' LINKs.
See `my-org-expand-file-link' for more information.
Optional argument ARGS are passed as-is."
(apply orig-fun (my-org-expand-file-link link) args))
(advice-add 'org-link-open :around #'my-org-link-open-advice)
</code></pre>
<p>So whenever you open a link with <kbd>C-c C-o</kbd> (<code>org-open-at-point</code> which calls <code>org-link-open</code>), you end up with a concrete file.</p>
<p><a href="https://i.stack.imgur.com/nCrE0.png" rel="noreferrer"><img src="https://i.stack.imgur.com/nCrE0.png" alt="link expansion" /></a></p>
<h1>Some remarks</h1>
<p>I recommend using a custom link type like <code>first:</code> or wrapping the code above minor mode, as the advice is somewhat invasive and might surprise users that <em>really</em> want to get a list of matching files instead.</p>
<p>I'm open to any feedback on the elisp code, especially since I'm still a elisp newbie.</p>
|
[] |
[
{
"body": "<p>That's a cool feature I've to say. And the code looks excellent, I\nsuppose you could argue for one or the other wrt. <code>cond</code> vs. <code>if</code>\netc. but that's pointless pedantry IMO.</p>\n<p>Given that it works flawlessly (tried locally and via tramp as well), I\nwas unsure there was actually anything to say here, but I found two\npoints that might be of interest:</p>\n<p>Firstly, while the <code>:around</code> combinator works fine, it might be more\nappropriate to use <code>:filter-args</code>, since it's really just filtering the\narguments:</p>\n<pre><code>(defun my-org-link-open-advice (args)\n "Advice for ORIG-FUN that expands patterns in 'file:' LINKs.\nSee `my-org-expand-file-link' for more information.\nOptional argument ARGS are passed as-is."\n (list* (my-org-expand-file-link (first args)) (rest args)))\n\n(advice-add 'org-link-open :filter-args #'my-org-link-open-advice)\n</code></pre>\n<p>The functionality is absolutely unchanged of course.</p>\n<p>Secondly, and this is conflicting with the previous point, I could\nimagine using the prefix argument (so <kbd>C-u C-c C-o</kbd>) to\ndistinguish the two cases of whether to run the original behaviour, or\nnot, like so:</p>\n<pre><code>(defun my-org-link-open-advice (orig-fun link &optional arg &rest args)\n "Advice for ORIG-FUN that expands patterns in 'file:' LINKs.\nSee `my-org-expand-file-link' for more information.\nOptional argument ARGS are passed as-is."\n (apply orig-fun (if arg link (my-org-expand-file-link link)) arg args))\n</code></pre>\n<p>To quote the function docstring for <code>org-link-open</code>:</p>\n<blockquote>\n<p>ARG is an optional prefix argument. Some link types may handle it.\nFor example, it determines what application to run when opening a\n"file" link.</p>\n</blockquote>\n<p>This might interfere with the above idea, however practically I couldn't see a\ndifference with the unadvised function and this argument being present\nor not, YMMV.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T13:13:57.997",
"Id": "507682",
"Score": "1",
"body": "Thanks for the review. TIL about the aliases `first` and `rest` for `car` and `cdr`!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T20:06:00.137",
"Id": "507711",
"Score": "0",
"body": "Right, I actually thought for teaching purposes to use `first` and `rest`, normally I go for the shorter ones :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T10:34:56.163",
"Id": "257060",
"ParentId": "250783",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "257060",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T08:39:51.190",
"Id": "250783",
"Score": "6",
"Tags": [
"beginner",
"lisp",
"elisp"
],
"Title": "WOMOIWIW: What Org-mode Opens is What I Want"
}
|
250783
|
<p>I am creating one library for encryption/decryption using AES-256 with GCM Mode(With Random IV/Random Salt) for every request.</p>
<p>Code I have written is(reference : <a href="https://codereview.stackexchange.com/questions/187371/aes-encryption-decryption-with-key/187526#187526">AES Encryption/Decryption with key</a>) :</p>
<pre><code> public class AESGCMChanges {
static String plainText1 = "DEMO text to be encrypted @1234";
static String plainText2 = "999999999999";
public static final int AES_KEY_SIZE = 256;
public static final int GCM_IV_LENGTH = 12;
public static final int GCM_TAG_LENGTH = 16;
public static final int GCM_SALT_LENGTH = 32;
private static final String FACTORY_ALGORITHM = "PBKDF2WithHmacSHA256";
private static final String KEY_ALGORITHM = "AES";
private static final int KEYSPEC_ITERATION_COUNT = 65536;
private static final int KEYSPEC_LENGTH = 256;
private static final String dataKey = "demoKey";
public static void main(String[] args) throws Exception
{
byte[] cipherText = encrypt(plainText1.getBytes());
String decryptedText = decrypt(cipherText);
System.out.println("DeCrypted Text : " + decryptedText);
cipherText = encrypt(plainText2.getBytes());
decryptedText = decrypt(cipherText);
System.out.println("DeCrypted Text : " + decryptedText);
}
public static byte[] encrypt(byte[] plaintext) throws Exception
{
byte[] IV = new byte[GCM_IV_LENGTH];
SecureRandom random = new SecureRandom();
random.nextBytes(IV);
// Get Cipher Instance
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
byte[] salt = generateSalt();
// Generate Key
SecretKey key = getDefaultSecretKey(dataKey, salt);
// Create GCMParameterSpec
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, IV);
// Initialize Cipher for ENCRYPT_MODE
cipher.init(Cipher.ENCRYPT_MODE, key, gcmParameterSpec);
// Perform Encryption
byte[] cipherText = cipher.doFinal(plaintext);
byte[] message = new byte[GCM_SALT_LENGTH + GCM_IV_LENGTH + plaintext.length + GCM_TAG_LENGTH];
System.arraycopy(salt, 0, message, 0, GCM_SALT_LENGTH);
System.arraycopy(IV, 0, message, GCM_SALT_LENGTH, GCM_IV_LENGTH);
System.arraycopy(cipherText, 0, message, GCM_SALT_LENGTH+GCM_IV_LENGTH, cipherText.length);
return message;
}
public static String decrypt(byte[] cipherText) throws Exception
{
if (cipherText.length < GCM_IV_LENGTH + GCM_TAG_LENGTH + GCM_SALT_LENGTH) throw new IllegalArgumentException();
ByteBuffer buffer = ByteBuffer.wrap(cipherText);
// Get Salt from Cipher
byte[] salt = new byte[GCM_SALT_LENGTH];
buffer.get(salt, 0, salt.length);
// GET IV from cipher
byte[] ivBytes1 = new byte[GCM_IV_LENGTH];
buffer.get(ivBytes1, 0, ivBytes1.length);
byte[] encryptedTextBytes = new byte[buffer.capacity() - salt.length - ivBytes1.length];
buffer.get(encryptedTextBytes);
// Get Cipher Instance
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
// Generate Key
SecretKey key = getDefaultSecretKey(dataKey, salt);
// Create GCMParameterSpec
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, ivBytes1);
// Initialize Cipher for DECRYPT_MODE
cipher.init(Cipher.DECRYPT_MODE, key, gcmParameterSpec);
// Perform Decryption
byte[] decryptedText = cipher.doFinal(encryptedTextBytes);
return new String(decryptedText);
}
private static SecretKey getDefaultSecretKey(final String password, final byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException{
return getSecretKey(password, salt, FACTORY_ALGORITHM, KEY_ALGORITHM, KEYSPEC_ITERATION_COUNT, KEYSPEC_LENGTH);
}
private static SecretKey getSecretKey(final String password,
final byte[] salt,
final String factoryAlgorithm,
final String keyAlgorithm,
final int iterationCount,
final int keyLength) throws NoSuchAlgorithmException, InvalidKeySpecException{
SecretKeyFactory factory = SecretKeyFactory.getInstance(factoryAlgorithm);
return new SecretKeySpec(factory.generateSecret(new PBEKeySpec(password.toCharArray(), salt, iterationCount, keyLength)).getEncoded(), keyAlgorithm); //thanks alot for the bug report
}
private static byte[] generateSalt()
{
final Random r = new SecureRandom();
byte[] salt = new byte[32];
r.nextBytes(salt);
return salt;
}
}
</code></pre>
<p>Now my question is:</p>
<ul>
<li>Does it have any security flaws?</li>
<li>Does it follow best practices?</li>
<li>Can I do something to improve it?</li>
</ul>
<p>All the lengths that I have taken for SALT, IV, Authentication tag are they OK? or they needs to be changed.</p>
|
[] |
[
{
"body": "<h2>Protocol</h2>\n<p>Well, first the good news. I don't see anything particularly wrong with the algorithms or parameters used.</p>\n<h2>Class design</h2>\n<p>This is a badly designed class with a lot of copy / paste going on (and I've found a clear indication for that at the end, where you copy code directly from this site). I'm not a big fan of static classes, and this one doesn't lend itself particularly well for it. For instance, you don't want to use a separate password for each call, and you certainly don't want to derive a key from the same password multiple times.</p>\n<h2>By line code review</h2>\n<pre><code>public class AESGCMChanges {\n</code></pre>\n<p>That's not a good name for a class. I presume this is testing only though.</p>\n<hr />\n<pre><code>public static final int GCM_IV_LENGTH = 12;\n</code></pre>\n<p>Some things are called <code>_SIZE</code> and others <code>_LENGTH</code>. It might be that one is in bits and the other one in bytes, but if you mix them I would indicate it in the name of the constants. Generally crypto-algorithm specifications define IV and tag sizes in bits, so probably best keep to that (and divide by <code>Byte.SIZE</code> where needed).</p>\n<p>The constants have the correct sizes assigned to them though, although a salt of 32 bytes / 256 bits may be a bit overkill: 128 bits is a plenty.</p>\n<hr />\n<pre><code>private static final String FACTORY_ALGORITHM = "PBKDF2WithHmacSHA256";\n</code></pre>\n<p>Nope, that name doesn't do it for me. It's not a (generic?) factory you are naming, it is a name - and hash configuration - of the Password Based Key Derivation Algorithm or PBKDF.</p>\n<hr />\n<pre><code>private static final String dataKey = "demoKey";\n</code></pre>\n<p>For testing purposes it could be an idea to make such a key a constant in a testing class, but here it is really unwanted. The naming is incorrect as well, you'd expect all uppercase for constants.</p>\n<p>Besides that, it's not the "data key" nor is it even a "key", it's a password or passphrase.</p>\n<hr />\n<pre><code> byte[] cipherText = encrypt(plainText1.getBytes());\n</code></pre>\n<p>Always indicate the character encoding or you may see changes. Generally, I'd default to <code>StandardCharsets.UTF_8</code> on Java (if you use the string directly then you will get an annoying checked exception to handle, something you can do without).</p>\n<hr />\n<pre><code>public static byte[] encrypt(byte[] plaintext) throws Exception\n</code></pre>\n<p>This is not a good method signature. I'd at least expect a password within it (as long as you keep to the current design anyway). What is good is that the plaintext and ciphertext is specified in bytes.</p>\n<p>The exception handling is not well worked out; just throwing <code>Exception</code> is as bad as a catch-all. For a good idea of how to handle Java crypto-exceptions take a look <a href=\"https://stackoverflow.com/a/15712409/589259\">here</a>.</p>\n<p>What about creating a class that has e.g. the number of iterations as configuration option, then initializes using the password and then allows for a set of plaintexts to be encrypted / decrypted?</p>\n<p>Currently you don't allow any associated data for GCM mode. GCM mode specifies authenticated encryption <em>with associated data</em> or AEAD cipher. Not including associated data is not wrong, but it could be a consideration.</p>\n<hr />\n<pre><code>byte[] IV = new byte[GCM_IV_LENGTH];\nSecureRandom random = new SecureRandom();\nrandom.nextBytes(IV);\n</code></pre>\n<p>Normally I would not comment on this as it is not <em>wrong</em> or anything like that. It shows good use of the secure random class. However, I think it is not very symmetric with <code>generateSalt</code>; why not create a method for the IV as well?</p>\n<hr />\n<pre><code>SecretKey key = getDefaultSecretKey(dataKey, salt);\n</code></pre>\n<p>A "default" secret key? What's that? This is the key that's going to encrypt the data, right? Shouldn't this be called the "data key" in that case? We've already established that the other key is really a password. Besides that, I would not call a method that performs a deliberately heavy operation such as password based key derivation a "getter" either. It should be named e.g. <code>deriveDataKey</code> or something similar.</p>\n<p>Missing from the call is the work factor / iteration count. I would certainly make that configurable and possibly store it with the ciphertext. You should use the highest number you can afford for the iteration count, and that number is going to shift to higher values in the future. Or so it should anyway.</p>\n<hr />\n<pre><code>System.arraycopy(cipherText, 0, message, GCM_SALT_LENGTH+GCM_IV_LENGTH, cipherText.length);\n</code></pre>\n<p>The salt and IV are relatively small, so buffering them in a separate array. However, Java has specific methods of writing data to an existing array using <code>ByteBuffer</code>. If your data is not that big then I would be OK with not using multiple <code>update</code> calls or streaming the data. I would however not recommend duplicating the ciphertext using <code>System.arrayCopy</code>.</p>\n<p>And it is strange that this has not been implemented using <code>ByteBuffer</code> considering that you have used it for the <code>decrypt</code> method (again, the more symmetry the better).</p>\n<hr />\n<pre><code>return new SecretKeySpec(factory.generateSecret(new PBEKeySpec(password.toCharArray(), salt, iterationCount, keyLength)).getEncoded(), keyAlgorithm); //thanks alot for the bug report\n</code></pre>\n<p>The reason that the <code>password</code> is seen as character array is that you can destroy it's contents after you've handled it, in this case created a key from it. Array contents can be destroyed in Java (with reasonable certainty), <code>String</code> values cannot. So using <code>password.toCharArray()</code> here doesn't let you do this.</p>\n<pre><code>//thanks alot for the bug report\n</code></pre>\n<p>What bug report? What's the point of having a "thank you" here? Why not include a link if you decide to include such a comment?</p>\n<p>In this case it seems <a href=\"https://codereview.stackexchange.com/a/187526/9555\">you copied a small method without attribution</a>.</p>\n<p>This also shows the dangers of having end of line comments; they are easily missed. They are even less visible if too much is going on in that single line - as is the case here.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T08:33:46.560",
"Id": "493466",
"Score": "0",
"body": "Thanks Maarten for a detailed look at it. I have one doubt though. You mentioned its not a data key/ not even key. Now say I am generating the data key using AWS KMS. Now do I need to use PBKDF or can I use it directly to encrypt the data. I do missed giving attribution, added it now"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T09:02:41.067",
"Id": "493467",
"Score": "0",
"body": "@AnkitBansal As an additional point to the \"thanks\" comment, there is no point in keeping history in the code. That's what a version control system is supposed to do. Keeping stuff like \"this used to be an error\", \"there used to be a bug here\", \"this was added with bla\" in the code is completely meaningless, especially if the comment does not give any further context. \"We're using y instead of x because blablabla\" is a good comment, especially when the first instinct would be to use x instead of y. But otherwise, I would not bother to annotate fixed bugs in the code in any way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T10:32:14.217",
"Id": "493469",
"Score": "1",
"body": "You can use AWS KMS for this, but the question is how **you plan to use the keys**. It would make more sense to me to use a single key and possibly derive the data keys from it. However, in that case you certainly don't need a PBKDF. A key based key derivation mechanism (KBKDF) makes more sense. However, I don't know if those are implemented for AWS. KDF's are often the last algorithms to be implemented, while they are pretty useful for key management - which what this topic is about. Directly using the AWS keys is not wrong or anything. Beware that GCM does have a per key message limit though"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T19:59:28.467",
"Id": "250808",
"ParentId": "250785",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "250808",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T10:48:18.507",
"Id": "250785",
"Score": "3",
"Tags": [
"java",
"aes"
],
"Title": "AES GCM Encryption Code (Secure Enough or not)"
}
|
250785
|
<p>Simple script that asks you to think of a number between 1 and 63 then offers list of numbers and asks if your number is in that list. Can this be refactored further? Are there better ways to create lists? Any improvements?</p>
<pre><code>x= [xx for xx in range(1,64)]
num_i = [i for i in range(1,64,2)]
num_ii = x[1::16]+ x[2::16]+ x[5::16]+ x[6::16]+ \
x[9::16]+ x[10::16]+ x[13::16]+ x[14::16]
num_ii.sort()
num_iii= x[3::16]+ x[4::16]+ x[5::16]+ x[6::16]+ \
x[11::16]+ x[12::16]+ x[13::16]+ x[14::16]
num_iii.sort()
num_iv= x[7::16]+ x[8::16]+ x[9::16]+ x[10::16]+ \
x[11::16]+ x[12::16]+ x[13::16]+ x[14::16]
num_iv.sort()
num_v= x[15::32]+ x[16::32]+ x[17::32]+ x[18::32]+ \
x[19::32]+ x[20::32]+ x[21::32]+ x[22::32]+ \
x[23::32]+ x[24::32]+ x[25::32]+ x[26::32]+ \
x[27::32]+ x[28::32]+ x[29::32]+ x[30::32]
num_v.sort()
num_vi= [x for x in range(32,64)]
num_lists=[num_i,num_ii,num_iii,num_iv,num_v,num_vi]
addition_num= [1,2,4,8,16,32]
start_end= ["Think of a number between 1 and 63","I think the number you thought of was ..."]
intro= ["Is your number in the group of numbers below?",
"Is your number in this group of numbers ?","Is your number in this third group of numbers ?",
"Half way there. Is your number in this group of numbers ?",
"One more after this one. Is your number in this group of numbers ?",
"Last one. Is your number in this group of numbers ?"]
def format_list(xx):
for a,b,c,d,e,f,g,h in zip(xx[::8],xx[1::8],xx[2::8],xx[3::8],xx[4::8],xx[5::8],xx[6::8],xx[7::8]):
print('{:<8}{:<8}{:<8}{:<8}{:<8}{:<8}{:<8}{:<}'.format(a,b,c,d,e,f,g,h))
print('-'*62)
def main():
count=0
your_guess= 0
print(start_end[0])
ready= input('are you ready?(enter to quit or any key)')
if ready:
while count < 6:
print(intro[count])
format_list(num_lists[count])
reply = input("y/n ?")
if reply == "y" :
your_guess += addition_num[count]
count +=1
print(start_end[1] + str(your_guess))
replay= input('Play again? (enter to quit or any key)')
if replay:
main()
if __name__ == '__main__':
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T13:12:57.030",
"Id": "493385",
"Score": "1",
"body": "What's the basis by which you've chosen 1, 2, 5, 6, 9, 10, 13, 14? Are these basically randomly selected?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T14:38:02.033",
"Id": "493388",
"Score": "1",
"body": "@Reinderien it's a common boolean algebra problem. the lists are numbers with binary expressions having `1` at n-th bit, so binary lists would be: `xxxxx1`, `xxxx1x`, `xxx1xx`, ... hence 32 elements in each of those"
}
] |
[
{
"body": "<h2>Magic numbers</h2>\n<p>As already mentioned in comments, the numbers <span class=\"math-container\">\\$ 1, 2, \\cdots \\$</span> appear to be completely random to anyone not sure about how the summation is going to (or supposed to) work. The generation of the lists is also very cumbersome. The same trick could be expanded to a selection upto <span class=\"math-container\">\\$ 127, 255, 511, \\cdots, 2^{n} - 1 \\$</span>.</p>\n<h2>Recursive <code>main</code></h2>\n<p>You have a recursive call to <code>main</code> in case the player wants to replay the game. Recursive calls when you never return might lead to stack overflows. In this scenario, recursion is not really needed anyway.</p>\n<h2>Overusage of lists</h2>\n<p>You have almost everything put inside lists. This includes all the numbers from <span class=\"math-container\">\\$ 1-63 \\$</span>, all the generated charts from these numbers, aggregation of all the above lists, list of powers of <span class=\"math-container\">\\$ 2 \\$</span>, and so on.</p>\n<p>For some of those, a tuple (immutable) is good, others do not need to be placed in a list anyway.</p>\n<h2>Variable naming</h2>\n<p><code>x</code>, <code>xx</code>, <code>xxx</code>, <code>xxxx</code>, .. are not really meaningful. Use better variable names.</p>\n<hr />\n<p>For generation of the numerical lists:</p>\n<pre><code>for start in (2 ** i for i in range(6)):\n l = [_ for _ in range(start, 64) if _ % (start * 2) >= start]\n</code></pre>\n<hr />\n<p>Rewrite:</p>\n<pre><code>INTROS = (\n "Is your number in the group of numbers below?",\n "Is your number in this group of numbers?",\n "Is your number in this third group of numbers?",\n "Half way there. Is your number in this group of numbers?",\n "One more after this one. Is your number in this group of numbers?",\n "Last one. Is your number in this group of numbers?",\n # "Or maybe the following?",\n # "Add more intro strings here",\n # "to get larger guessing range",\n)\nCOUNT = len(INTROS)\nUPPER_LIMIT = 2 ** COUNT\n\n\ndef display_chart(index: int, columns: int = 8):\n print(INTROS[index])\n start = 1 << index\n chart = [str(x) for x in range(start, UPPER_LIMIT) if x % (start * 2) >= start]\n for i in range(len(chart) // columns):\n print("\\t".join(chart[i * columns : (i + 1) * columns]))\n\n\ndef game():\n guess = 0\n print(f"Think of a number between 1 and {UPPER_LIMIT - 1}")\n for current in range(COUNT):\n display_chart(current)\n reply = input("y/n? ")\n if reply == "y":\n guess += 1 << current\n print(f"I think the number you thought of was ... {guess}")\n\n\ndef main():\n while True:\n game()\n character = input("Play again? (enter to quit or any key)")\n if not character:\n break\n\n\nif __name__ == "__main__":\n main()\n</code></pre>\n<p>The rewrite is completely dynamic in nature now. If you want to increase the range, just add another section to the <code>INTROS</code> tuple.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T16:35:42.450",
"Id": "493398",
"Score": "1",
"body": "Also, in most cases here you should prefer `1 << x` over `2 ** x`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T16:49:59.967",
"Id": "493403",
"Score": "0",
"body": "Otherwise this is quite good, and basically where I would have landed :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T17:19:45.020",
"Id": "493407",
"Score": "1",
"body": "@Reinderien Why prefer `1 << x` here, and why only in most cases (which ones)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T17:24:10.040",
"Id": "493408",
"Score": "1",
"body": "@StefanPochmann I'm on the fence as to whether `UPPER_LIMIT ` should use exponentiation or shift, because I don't properly understand the algorithm being applied; this is a style choice and certainly not a performance factor. However, for the other instances (that @hjpotter92 has already changed) they should be shifts because conceptually, they are actually bit-wise operations and not \"math operations\", so the shift shows intention more clearly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T17:40:43.907",
"Id": "493410",
"Score": "0",
"body": "Thanks for the review and suggestions, I need some time to go over them, and examine if it's scales. I like your rewrite easier to read. thanks again, Joe"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T03:03:04.613",
"Id": "493453",
"Score": "1",
"body": "Nice review. The first print can be `Think of a number between 1 and {UPPER_LIMIT-1}`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T17:21:35.617",
"Id": "493592",
"Score": "0",
"body": "@hippotter92 wow do have did a jiu jitsu move on my code. your function display chart is magical. thanks again,"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T16:17:48.833",
"Id": "250796",
"ParentId": "250787",
"Score": "9"
}
},
{
"body": "<p>First pass:</p>\n<ul>\n<li>Move most of the list creation stuff into a function</li>\n<li>PEP8 fixes: standardize spaces, get rid of continuation escapes, spaces between functions</li>\n<li>Some immutable tuples instead of lists</li>\n</ul>\n<pre><code>def make_num_lists():\n x = [xx for xx in range(1, 64)]\n num_i = [i for i in range(1, 64, 2)]\n num_ii = (x[ 1::16] + x[ 2::16] + x[ 5::16] + x[ 6::16] +\n x[ 9::16] + x[10::16] + x[13::16] + x[14::16])\n num_ii.sort()\n num_iii = (x[ 3::16] + x[ 4::16] + x[ 5::16] + x[ 6::16] +\n x[11::16] + x[12::16] + x[13::16] + x[14::16])\n num_iii.sort()\n num_iv = (x[ 7::16] + x[ 8::16] + x[ 9::16] + x[10::16] +\n x[11::16] + x[12::16] + x[13::16] + x[14::16])\n num_iv.sort()\n num_v = (x[15::32] + x[16::32] + x[17::32] + x[18::32] +\n x[19::32] + x[20::32] + x[21::32] + x[22::32] +\n x[23::32] + x[24::32] + x[25::32] + x[26::32] +\n x[27::32] + x[28::32] + x[29::32] + x[30::32])\n num_v.sort()\n num_vi = [x for x in range(32, 64)]\n return [num_i, num_ii, num_iii, num_iv, num_v, num_vi]\n\n\nnum_lists = make_num_lists()\naddition_num = (1, 2, 4, 8, 16, 32)\nstart_end = (\n "Think of a number between 1 and 63",\n "I think the number you thought of was ...",\n)\nintro = (\n "Is your number in the group of numbers below?",\n "Is your number in this group of numbers ?",\n "Is your number in this third group of numbers ?",\n "Half way there. Is your number in this group of numbers ?",\n "One more after this one. Is your number in this group of numbers ?",\n "Last one. Is your number in this group of numbers ?",\n)\n\n\ndef format_list(xx):\n for a,b,c,d,e,f,g,h in zip(xx[::8],xx[1::8],xx[2::8],xx[3::8],xx[4::8],xx[5::8],xx[6::8],xx[7::8]):\n print('{:<8}{:<8}{:<8}{:<8}{:<8}{:<8}{:<8}{:<}'.format(a,b,c,d,e,f,g,h))\n print('-'*62)\n\n\ndef main():\n count = 0\n your_guess = 0\n print(start_end[0])\n ready = input('are you ready?(enter to quit or any key)')\n if ready:\n while count < 6:\n print(intro[count])\n format_list(num_lists[count])\n reply = input("y/n ?")\n if reply == "y":\n your_guess += addition_num[count]\n count += 1\n print(start_end[1] + str(your_guess))\n replay = input('Play again? (enter to quit or any key)')\n if replay:\n main()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p>But this is not sufficient. Do what @hjpotter92 suggested.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T17:42:55.470",
"Id": "493411",
"Score": "0",
"body": "thanks the conversion to tuples looks clearer. Thanks for taking the time, Joe"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T16:33:30.830",
"Id": "250798",
"ParentId": "250787",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T11:20:28.867",
"Id": "250787",
"Score": "8",
"Tags": [
"python",
"game"
],
"Title": "guess your number"
}
|
250787
|
<p>This is the follow-up question for <a href="https://codereview.stackexchange.com/questions/250743/a-summation-function-for-arbitrary-nested-vector-implementation-in-c">A Summation Function For Arbitrary Nested Vector Implementation in C++</a>. The following code is the improved version based on <a href="https://codereview.stackexchange.com/a/250749/231235">Zeta's answer</a>. I am trying to enhance this the <code>sum</code> function which can deal with iterable things which has <code>begin()</code> and <code>end()</code> (such as <code>std::array</code>) of various types (such as <code>int</code>, <code>char</code> or <code>unsigned int</code>) number. I am not familiar with the usage of <code>std::enable_if</code> and <code>std::is_arithmetic</code> for checking type constraint in template. If there is any possible improvement, please let me know.</p>
<pre><code>template<class Container, typename = typename Container::value_type>
inline long double Sum(const Container& numbers)
{
long double sumResult = 0.0;
for (auto& element : numbers)
{
sumResult += Sum(element);
}
return sumResult;
}
template<class T,
std::enable_if_t<std::is_arithmetic<T>::value, int> = 0,
std::enable_if_t<std::is_arithmetic<T>::value, double> = 0>
T Sum(T inputNumber)
{
return inputNumber;
}
</code></pre>
<p>Some tests for this sum function:</p>
<pre><code>int testNumber = 1;
std::vector<decltype(testNumber)> testVector1;
testVector1.push_back(testNumber);
testVector1.push_back(testNumber);
testVector1.push_back(testNumber);
std::cout << std::to_string(Sum(testVector1)) + "\n";
std::vector<decltype(testVector1)> testVector2;
testVector2.push_back(testVector1);
testVector2.push_back(testVector1);
testVector2.push_back(testVector1);
std::cout << std::to_string(Sum(testVector2)) + "\n";
std::vector<decltype(testVector2)> testVector3;
testVector3.push_back(testVector2);
testVector3.push_back(testVector2);
testVector3.push_back(testVector2);
std::cout << std::to_string(Sum(testVector3)) + "\n";
// std::array test case
std::array<long double, 90> numberArray;
for (size_t i = 0; i < 90; i++)
{
numberArray[i] = 1;
}
std::cout << std::to_string(Sum(numberArray)) + "\n";
</code></pre>
<p>The summary information:</p>
<ul>
<li><p>Which question it is a follow-up to?</p>
<p><a href="https://codereview.stackexchange.com/questions/250743/a-summation-function-for-arbitrary-nested-vector-implementation-in-c">A Summation Function For Arbitrary Nested Vector Implementation in C++</a></p>
</li>
<li><p>What changes has been made in the code since last question?</p>
<ul>
<li><p>The previous question focus on single type <code>long double</code> and the goal in this question is trying to deal with various type number.</p>
</li>
<li><p>The previous question focus on <code>std::vector</code> and the other iterable things which has <code>begin()</code> and <code>end()</code> are considered here.</p>
</li>
<li><p>The variable name has been modified in order to make better understanding.</p>
</li>
</ul>
</li>
<li><p>Why a new review is being asked for?</p>
<p>Is it a good idea to set the type constraint like <code>std::enable_if_t<std::is_arithmetic<T>::value, int> = 0, std::enable_if_t<std::is_arithmetic<T>::value, double> = 0></code>?</p>
</li>
</ul>
<p><strong>Oct 18, 2020 Update</strong></p>
<ul>
<li><p>The further implementation with c++-concepts:</p>
<p><a href="https://stackoverflow.com/q/64414869/6667035">https://stackoverflow.com/q/64414869/6667035</a></p>
</li>
</ul>
|
[] |
[
{
"body": "<h1>Proper constraints</h1>\n<blockquote>\n<p>Is it a good idea to set the type constraint like <code>std::enable_if_t<std::is_arithmetic<T>::value, int> = 0</code>, <code>std::enable_if_t<std::is_arithmetic<T>::value, double> = 0></code>?</p>\n</blockquote>\n<p>It is not a good idea to constrain the value type to the arithmetic ones. It will only match primitive integer and floating point types. There are many more types that you can sum together, either ones from the STL (like <code>std::complex</code>) or custom types.</p>\n<p>Also, the constraint on the overload that sums over containers is incorrect. You only restrict it to classes that have a <code>value_type</code>, but that doesn't necessarily mean it is a container. Again, <code>std::complex</code> is an example of a class that has a <code>value_type</code> but isn't a container. Instead, you want to restrict it to something that has the properties of a container that you are actually using: that it has a <code>begin()</code> and <code>end()</code> for example. See <a href=\"https://stackoverflow.com/questions/12042824/how-to-write-a-type-trait-is-container-or-is-vector\">this question</a> for some ideas of how to check for a container type.</p>\n<h1>Return type</h1>\n<p>If you pass a container to <code>Sum()</code>, the result is always <code>long double</code>. But what if I want to sum integers, or <code>std::complex</code> numbers, or something completely different like <code>std::string</code>s? You want the return type to match the <code>value_type</code> of the inner-most container. Have a look at how <a href=\"https://en.cppreference.com/w/cpp/algorithm/accumulate\" rel=\"nofollow noreferrer\"><code>std::accumulate()</code></a> handles this.</p>\n<h1>Summing non-container types</h1>\n<p>Normally I'm all for handling corner cases properly, and the case of summing over something that has zero nested containers, but just a single value, can be considered such a corner case. But in this case, I think it will most likely be a programming error if you tried to sum a single value. So consider whether it makes sense to have an overload that handles the sum of a single value.</p>\n<h1>Redundant calls to <code>std::to_string()</code></h1>\n<p>Not related to <code>Sum()</code>, but in your example you are converting the results to a string with <code>std::to_string()</code>, but the immediately writing it to <code>std::cout</code>. This is unnecessary, <code>std::cout</code> already knows how to format a <code>long double</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T10:27:57.233",
"Id": "493468",
"Score": "0",
"body": "Thank you for answering. About the proper constraints part, I realize that there are many more types that can be summed together. Is there any hint or example for dealing with this part?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T11:21:27.570",
"Id": "493471",
"Score": "2",
"body": "Yes: I would just not put any constraints on the value type. If it can't be summed you'll get a compile error. With C++20's concepts, you could create concept `Summable` that checks whether the value types can be summed, and give a helpful error message if not. You could do something similar with SFINAE, although that's more ugly, and without a clean error message it won't be as useful. See for an example [this question](https://stackoverflow.com/questions/54468896/implementation-of-concepts-in-c17)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T15:03:07.463",
"Id": "250792",
"ParentId": "250790",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "250792",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T14:20:27.573",
"Id": "250790",
"Score": "4",
"Tags": [
"c++",
"recursion"
],
"Title": "A Summation Function For Various Type Arbitrary Nested Iterable Implementation in C++"
}
|
250790
|
<p>The following code simply prompts the user to choose from a menu, and then it displays the choice made by that user.</p>
<p>It only accepts input consisting of a single digit between 1 and 6, inclusive. Anything else will be considered as being invalid.</p>
<p><strong>Questions</strong></p>
<ol>
<li><p>While it considers Ctrl-D as an invalid choice, should it be handled differently? If so, how?</p>
</li>
<li><p>It takes user input as an <code>int</code>. Would you suggest taking it as a <code>string</code> instead, and then use either <code>stoi</code> or <code>stringstream</code> to convert it to an <code>int</code>?</p>
</li>
<li><p>Can it be re-written in a more elegant and concise way?</p>
</li>
<li><p>Do you see any potential issues?</p>
</li>
<li><p>Any comments?</p>
</li>
</ol>
<p><strong>Source Code</strong></p>
<pre><code>#include <iostream>
#include <limits>
int getChoice()
{
std::cout << "Main Menu\n"
<< "-------------------\n"
<< "1. Add record\n"
<< "2. Edit record\n"
<< "3. Delete record\n"
<< "4. View record\n"
<< "5. View all records\n"
<< "6. Exit\n";
bool isValid;
int choice;
do
{
isValid = true;
std::cout << "Enter choice: ";
std::cin >> choice;
if (std::cin.fail())
{
if (std::cin.eof())
{
std::cin.clear();
}
else
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
isValid = false;
}
else
{
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
if (std::cin.gcount() > 1)
{
isValid = false;
}
else if (choice < 1 || choice > 6)
{
isValid = false;
}
}
if (!isValid)
{
std::cout << "Invalid choice\n";
}
} while (!isValid);
return choice;
}
int main()
{
int choice;
choice = getChoice();
std::cout << "User chose option " << choice << std::endl;
return 0;
}
</code></pre>
<p><strong>Input and Results</strong></p>
<pre><code>Main Menu
-------------------
1. Add record
2. Edit record
3. Delete record
4. View record
5. View all records
6. Exit
Enter choice: x
Invalid choice
Enter choice: 8
Invalid choice
Enter choice: 2x
Invalid choice
Enter choice: x2
Invalid choice
Enter choice: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Invalid choice
Enter choice: 888888888888888888888888888888888888888888888888888888888888888888888888888
Invalid choice
Enter choice: Invalid choice // Ctrl-D entered here
Enter choice: ^Z
[1]+ Stopped ./getchoice_cpp
</code></pre>
|
[] |
[
{
"body": "<h1>Answers to your questions</h1>\n<blockquote>\n<p>While it considers Ctrl-D as an invalid choice, should it be handled differently? If so, how?</p>\n</blockquote>\n<p>You should treat the end of the file as the definite end of the input, and return immediately with a value that indicates a failure. Not all EOFs are Ctrl-D's, there is no guarantee that you can even continue reading from <code>std::cin</code> after you encounter an EOF; for example the user might have redirected standard input to a file.</p>\n<blockquote>\n<p>It takes user input as an int. Would you suggest taking it as a string instead, and then use either stoi or stringstream to convert it to an int?</p>\n</blockquote>\n<p>As you have probably seen <code>std::cin >> some_int</code> does not read a whole line, instead it tries to read an integer but stops as soon as it encounters something that is not an integer. Instead of fighting against this, use <a href=\"https://en.cppreference.com/w/cpp/string/basic_string/getline\" rel=\"nofollow noreferrer\"><code>std::getline()</code></a> if you want to read a line, and then indeed use <code>std::stoi()</code> or something similar to convert that to a number. You still need to deal with the fact that also <code>stoi()</code> stops as soon as it sees the first character that is not part of an integer.</p>\n<blockquote>\n<p>Can it be re-written in a more elegant and concise way?</p>\n</blockquote>\n<p>Yes, see below.</p>\n<blockquote>\n<p>Do you see any potential issues?</p>\n</blockquote>\n<p>There is code duplication and unnecessary complexity dealing with <code>std::cin</code>. Also, the function is not very generic; if you want to get a choice for a different menu you would have to write a new function.</p>\n<h1>Reading a line with an integer in it</h1>\n<p>First, read a single line, and check if that succeeded. If not, either return some value indicating an error, or <code>throw</code> an exception. For example:</p>\n<pre><code>std::string line;\n\nif (!std::getline(std::cin, line)) {\n throw std::runtime_error("Error while reading input");\n}\n</code></pre>\n<p>Then try to convert it with <code>std::stoi()</code> or any of its variants, depending on the type of integer. Use the second argument to <a href=\"https://en.cppreference.com/w/cpp/string/basic_string/stol\" rel=\"nofollow noreferrer\"><code>std::stoi()</code></a> to know where it stopped parsing the integer, and check that this was at the end of the string:</p>\n<pre><code>try {\n size_t endpos;\n size_t value = stoi(line, &endpos);\n\n if (endpos == line.size()) {\n // Success!\n ...\n }\n} catch (std::logic_error &) {\n // Error parsing the integer\n ...\n}\n</code></pre>\n<h1>Make <code>getChoice()</code> more generic</h1>\n<p>You hardcoded the choices in <code>getChoice()</code>. If you have a program with multiple menus, then you would have to write different versions of <code>getChoice()</code>, duplicating a lot of code. So try to make it more generic. For example, you can have <code>getChoice()</code> take two parameters: one is a string with the title of the menu, the second is a vector of strings with the possible choices.</p>\n<h1>Full example</h1>\n<p>Here is an example of what it could look like:</p>\n<pre><code>#include <iostream>\n#include <stdexcept>\n#include <string>\n#include <vector>\n\nsize_t getChoice(const std::string &title, const std::vector<std::string> &choices)\n{\n std::cout << title << "\\n"\n << "-------------------\\n";\n\n for (size_t i = 0; i < choices.size(); ++i) {\n std::cout << i << ". " << choices[i] << "\\n";\n }\n\n while (true) {\n std::cout << "Enter choice: " << std::flush;\n std::string line;\n\n if (!std::getline(std::cin, line)) {\n throw std::runtime_error("Could not read input");\n }\n\n try {\n size_t endpos;\n size_t choice = stoul(line, &endpos);\n\n if (endpos == line.size() && choice < choices.size()) {\n return choice;\n }\n } catch (std::exception &) {\n // nothing to do here\n }\n\n std::cout << "Invalid choice\\n";\n }\n}\n\nint main()\n{\n static const std::vector<std::string> choices = {\n "Add record",\n "Edit record",\n "Delete record",\n "View record",\n "view all records",\n "Exit",\n };\n\n size_t choice = getChoice("Main menu", choices);\n\n std::cout << "User chose option " << choice << std::endl;\n}\n</code></pre>\n<p>Note that I made the option numbers start with zero, just to keep the code slightly simpler. I also used <code>size_t</code>, as it is unsigned (no need to deal with negative numbers), and it's good practice whenever you deal with indices into arrays, vectors and so on. Note that you don't have to create a named vector in <code>main()</code>, you can even pass a literal to <code>getChoices()</code>:</p>\n<pre><code>size_t choice = getChoice("Menu", {"First option", "Second option", ...});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T22:16:38.983",
"Id": "493437",
"Score": "0",
"body": "Thank you very much for taking the time to answer my questions. I really appreciate it. I like all your suggestions. In particularly, I like your suggestion to make getChoice() a generic function, using try/catch to handle errors, and using getline() to get input from the user. I've learned quite a bit studying your example. That's great, thanks again, cheers!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T20:58:14.293",
"Id": "250810",
"ParentId": "250794",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "250810",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T15:15:45.740",
"Id": "250794",
"Score": "7",
"Tags": [
"c++",
"linux"
],
"Title": "Prompt user to choose from menu"
}
|
250794
|
<p>I'm wondering and actually playing in typescript playground with generics functions. The question is, is the code below readable? If not what kind of approach I could use to make it more typescript way and more readable?</p>
<p>Working example <a href="https://www.typescriptlang.org/play?#code/C4TwDgpgBAYg9gGwCYJgVwHYGNgEs4YA8AKgHxQC8UAFAIYBcUxANFAEaPECUl5xA3AChBAM0w58GWIhQlS1EY3jJU4vATms2tAM4ROrWgCcjnANoBdLpygBvQVEdQsBHcChmAFhFpJWAOkCjCDcLSihjIyEnKGDgNCMpAEJvXygAfnZdaCUZBAVWEWptPVZUpC5WYLcuIQBfYRcMHUQIfwQ4AHNqZRRqOkYMNABbNggjLUGRsaMeCnI6KABqdkqoAAZWMwBGZgAmZgBmZgAWZm2D7bPtgFZzgDYrWuFQSCgAWXfaMHRsdSIWAAlchUAZMObkQFCURqSQfL5gEjMYEKRifb6-CQaIGkQwmcxWRiAyx2BxOJpuDzlAJBELAMJUSLRJxxBLJcoZDxhRhmIrlNaBfzosAFWJ0rgWeqNVytdpdajC-oADymo3GEJoSqgACooEq1jt9kdTudLtc7ttHlxnoJXtAYLgEMBxpj-nJwmDuLx2HBWrQMNCxH84Q6neM5KjYI7nUZXZJNBF8UxLNZk2F7DEKe4vD4-FBBdV6eEmWTHKzElAUrnOSTGKWYjQ%20bmeJkc74af5QzHRYWJVAeYKu%20Me%20KrIIGoIKbKOt0h0ZlaqZhrqFqAKRQPaUChUdYG3YHY7XM3nC1Wm24DAxkS0LDQAAK4xaUgzTgwtGG%20igbiMF86zMcOhsu%20n7fr%20-4RJ0n5DGqUTjtKzTuJARhPjojAPshBAklQZj1i%20DZQG%20H6MAA5AAUnAngYMRzD1jEgGJMBJEACJwBA1G0U4tCQYwJyHPWdQ0TEeENoRn7EQAymgABe-q0Ox%20EAUBRFQMRABCrFGPJClcZ%20ezbPxglOMJMSiSRd60GgCBafh9GmSpAAyEAYAQ1kNjpjAXPxgiSvBLQIG0M7UPWvT5HQWjLrQyyrKwmxQPWirULYOl1BFkFrMF0bDolyWpdAhAbjcaxISh1rWvwQA" rel="noreferrer">here</a></p>
<p>I implemented some basic functions like foldl, map and filter to experiment generics, maybe the implementation don't satisfies all requirements in the sense of functionality.</p>
<pre class="lang-js prettyprint-override"><code>type FoldlFunction<T> = (a: T, b: T) => T;
function Foldl<T>(f: FoldlFunction<T>, base: T, arr: T[]): T {
const [head, ...rest] = arr;
return !head ? base : Foldl(f, f(base, head), rest);
}
console.log(Foldl((a: number, b: number) => (a + b), 0, [1,2,3,4,12,14,15,16]));
type MMapFunction<T,R> = (a: T) => R;
function MMap<T,R>(f: MMapFunction<T,R>, arr: T[]): R[] {
const [head, ...rest] = arr;
return !head ? [] : [f(head), ...MMap(f, rest)];
}
console.log(MMap((x: number) => (x * x), [1,2,3,4,12,14,15,16]));
type FilterFunction<T> = (a: T) => boolean;
function Filter<T>(f: FilterFunction<T>, arr: T[]): T[] {
const [head, ...rest] = arr;
return !head ? [] :
(f(head) ? [head, ...Filter(f, rest)] : [...Filter(f, rest)])
}
console.log(Filter((x: number) => (x % 2 === 0), [1,2,3,4,12,14,15,16]));
</code></pre>
|
[] |
[
{
"body": "<p>Your code looks quite reasonable, though there are a few tweaks you could consider.</p>\n<p><strong>Function or Callback?</strong> Rather than names like <code>FoldlFunction</code> and <code>MMapFunction</code>, since what those types contain are the types for the <em>callback</em> run for each element of the array, consider calling them <code>FoldlCallback</code> etc instead. It's a bit more precise and will make more intuitive sense at a glance. (One might think at a glance that <code>FoldlFunction</code> might refer to the type of the whole <code>Foldl</code> function, which is incorrect.)</p>\n<p><strong><code>camelCase</code></strong> is the near-universal convention for plain non-class functions and variables in JavaScript. PascalCase is generally used for class constructors and namespaces, which aren't being used here, so camelCase is probably more appropriate. Eg <code>Foldl</code> -> <code>foldl</code> (or to <code>foldL</code>).</p>\n<p><strong>DRYer types</strong> You only need to specify the type of a parameter when TypeScript can't infer it automatically. For example, with <code>foldl</code>, since the base value is T, and the array is <code>T[]</code>, the callback - the <code>f: FoldlFunction<T></code> - will be known to be of the form <code>(a: T, b: T) => T</code>. There's no need to additionally specify the arguments' types when calling <code>foldl</code>. That is, this:</p>\n<pre><code>foldl((a: number, b: number) => (a + b), 0, [1,2,3,4,12,14,15,16])\n</code></pre>\n<p>can be</p>\n<pre><code>foldl((a, b) => (a + b), 0, [1,2,3,4,12,14,15,16])\n</code></pre>\n<p>It's a good idea to let TypeScript automatically infer the types of variables and parameters whenever possible - less code to read makes comprehension easier. You can do the same thing for <code>MMap</code> and <code>Filter</code>.</p>\n<p><strong>Outside definition?</strong> I'm not entirely convinced of defining the type of the function/callback outside - it's one more type parameter that needs to be cognitively pieced together. Consider defining the callback type in the parameter list:</p>\n<pre><code>function foldl<T>(\n f: (a: T, b: T) => T,\n base: T,\n arr: T[]\n): T {\n const [head, ...rest] = arr;\n return !head ? base : foldl(f, f(base, head), rest);\n}\n\nconsole.log(foldl((a, b) => (a + b), 0, [1,2,3,4,12,14,15,16]));\n</code></pre>\n<p>I consider that significantly more readable. You can do the same thing for <code>MMap</code> and <code>Filter</code>.</p>\n<p><strong>Falsey bug</strong> You use <code>return !head ? base : foldl...</code>. This will not run if <code>head</code> is falsey. For example, <code>foldl((a, b) => (a + b), 0, [1,2,3,4,12,14,15,16])</code> results in 67, but <code>foldl((a, b) => (a + b), 0, [0, 1,2,3,4,12,14,15,16])</code> results in 0, which probably isn't desirable. Check the array's length instead:</p>\n<pre><code>function foldl<T>(\n f: (a: T, b: T) => T,\n base: T,\n arr: T[]\n): T {\n if (!arr.length) {\n return base;\n }\n const [head, ...rest] = arr;\n return foldl(f, f(base, head), rest);\n}\n</code></pre>\n<p>This applies to <code>MMap</code> and <code>Filter</code> as well.</p>\n<p><strong>DRYer filter</strong> To fix the falsey bug <em>and</em> make Filter a bit cleaner, you can replace:</p>\n<pre><code>const [head, ...rest] = arr;\nreturn !head ? [] : \n (f(head) ? [head, ...Filter(f, rest)] : [...Filter(f, rest)])\n</code></pre>\n<p>with</p>\n<pre><code>if (!arr.length) {\n return [];\n}\nconst includeThis = f(head); // call this here to preserve callback execution order\nconst restFiltered = Filter(f, rest);\nreturn includeThis ? [head, ...restFiltered] : restFiltered;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T17:54:40.583",
"Id": "493412",
"Score": "0",
"body": "Thanks for you detailed answer, as a beginner in typescript I really thought that will be good practice to put types explicitly everywhere, good to know that I can trust typescript to infer obvious code by itself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T17:54:47.413",
"Id": "493413",
"Score": "0",
"body": "Other question that arises in my mind, is if it is possible to \"extract\" the type of an function parameter, for example, you said that the outside definition was not quite relevant in this example, but suppose I want to extract the type of f parameter of foldl will it be possible? I don't know if I make myself understandable, but I know that I can \"extract\" the type of an object property using keyof right, is there some operator that could help me do the same thing with a function parameter?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T18:07:26.153",
"Id": "493414",
"Score": "0",
"body": "You can use `Parameters`, eg `type Callback = Parameters<typeof f>;` or `Parameters<typeof foldl>[0];`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T18:24:07.617",
"Id": "493423",
"Score": "0",
"body": "Something interesting just happens, I think as typescript cannot infer the contextual type, when I do something like you suggested`type Callback = Parameters<typeof foldl>[0]` the signature of Callback is `(a: unknown, b: unknown): unknown` as demonstrated here in [playground](https://www.typescriptlang.org/play?#code/FAMwrgdgxgLglgewgAhAgNgE3QHgCoB8AFCAFzJECG5eANMgEY0CUyAvAcnY5QM4CmNepQBOImgG0AusxrIA3sGTLkUJLxjIJAC36VM9AHTGR-DVPbJRIgNxKVpmGBEoAhLv3IA-DwHJyaFjoJPQgRAx8-PQemMz0phrMdgC+wMAwAJ4ADvzIAMKU6OgRUADWlgAKopQAtvww-CK8OJk5CCCoGNgEEgAMUmlAA) how could I use generics in Callback definition?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T21:23:51.250",
"Id": "493433",
"Score": "0",
"body": "Not entirely sure what's going on there. It could be that if the callback type is inlined like that, it can't be extracted outside the function. It can be used *inside* the function: `type Callback = typeof f;` If you need the type outside the function, you can declare it outside as well like your original code does with `type FoldlFunction<T> = (a: T, b: T) => T;`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T02:01:15.603",
"Id": "493448",
"Score": "0",
"body": "I’m not sure callback is much better; functional programming simply calls those parameters « functions »"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T17:02:28.257",
"Id": "250800",
"ParentId": "250797",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "250800",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T16:28:27.030",
"Id": "250797",
"Score": "5",
"Tags": [
"generics",
"typescript"
],
"Title": "Best Practices Generics in Typescript"
}
|
250797
|
<p>The goal of the function is to find and print the minimum number of swaps (bribes) in what was initially a sorted array of ints - <a href="https://www.hackerrank.com/challenges/new-year-chaos/problem" rel="noreferrer">https://www.hackerrank.com/challenges/new-year-chaos/problem</a></p>
<p><a href="https://i.stack.imgur.com/g6z2I.png" rel="noreferrer"><img src="https://i.stack.imgur.com/g6z2I.png" alt="problem image" /></a></p>
<p>I have passed this problem with the following code:</p>
<pre><code>def minimumBribes(q):
bribeCount = 0
simulated = list(range(1, len(q) + 1))
for i in range(0, len(q)):
if q[i] > i+3:
print("Too chaotic")
return
for i in range(0, len(simulated)):
if simulated[i] == q[i]:
continue
while(simulated[i] != q[i]):
# do 2 bribes
if i + 3 == q[i]:
simulated[i + 2], simulated[i + 1] = simulated[i + 1], simulated[i + 2]
simulated[i + 1], simulated[i] = simulated[i], simulated[i + 1]
bribeCount += 2
# do 1 bribe
else:
simulated[i + 1], simulated[i] = simulated[i], simulated[i + 1]
bribeCount += 1
print(bribeCount)
</code></pre>
<p>My approach was to first scan through the array to determine whether it is valid, as 1 person can only bribe (swap) twice, hence the first for loop.
Then I go through each entry in my initial state array(<code>simulated</code>) and do swaps until the simulated entry at position <code>i</code> matches that in the final array at the same position.</p>
<p>I'm wondering if there is a better way to do this or whether something can be improved in my approach? I rarely do while loops like this as it seems it could go infinite, but I guess it's okay for this problem as we know only 2 swaps are possible for any entry.</p>
|
[] |
[
{
"body": "<p>Some minor stuff:</p>\n<p>This <code>if</code>:</p>\n<pre><code> if simulated[i] == q[i]:\n continue\n</code></pre>\n<p>is redundant and can be removed, due to the predicate on your <code>while</code>. The <code>while</code> would execute zero times and have the same effect as if you <code>continue</code>d.</p>\n<p>The while itself:</p>\n<pre><code> while(simulated[i] != q[i]):\n</code></pre>\n<p>should drop the outer parens.</p>\n<p>The range here:</p>\n<pre><code>for i in range(0, len(simulated)):\n</code></pre>\n<p>should drop the <code>0, </code> because that's the default.</p>\n<p>Since you use both <code>i</code> and <code>simulated[i]</code>, you should iterate using <code>enumerate</code> instead of <code>range</code> (though this won't be the case if you delete the <code>if; continue</code>). Getting a value from <code>enumerate</code> won't be helpful during the value swaps that you do later.</p>\n<p>About the value swaps, this block:</p>\n<pre><code> if i + 3 == q[i]:\n simulated[i + 2], simulated[i + 1] = simulated[i + 1], simulated[i + 2]\n simulated[i + 1], simulated[i] = simulated[i], simulated[i + 1]\n bribeCount += 2\n # do 1 bribe\n else:\n simulated[i + 1], simulated[i] = simulated[i], simulated[i + 1]\n bribeCount += 1\n</code></pre>\n<p>should collapse to</p>\n<pre><code> if i + 3 == q[i]:\n simulated[i + 2], simulated[i + 1] = simulated[i + 1], simulated[i + 2]\n bribeCount += 1\n\n simulated[i + 1], simulated[i] = simulated[i], simulated[i + 1]\n bribeCount += 1\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T21:20:24.637",
"Id": "493432",
"Score": "0",
"body": "Thanks for the feedback - I see all your points are valid, don't know how I missed some of those :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T22:45:42.523",
"Id": "493438",
"Score": "0",
"body": "After getting another variable with `enumerate`, how do you keep it in sync with `simulated[i]` throughout the changes? Rather seems inconvenient."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T22:51:23.350",
"Id": "493439",
"Score": "0",
"body": "@HeapOverflow `enumerate` only applies to the current state of the code, where there's a separate `continue` which would use the item from `enumerate`. If that's deleted, there's no advantage to `enumerate`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T23:37:57.300",
"Id": "493441",
"Score": "0",
"body": "I'd say it doesn't apply to the current state, either. Sure, it would make the condition in the `if` shorter, but then during the while you either have the inconvenience of keeping in sync or if you don't keep in sync, you have the confusion of that. Unless you `del` the variable between the `if` and the `while`, at which point I'd say it's worse than the current state that never created the extra variable in the first place."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T20:42:10.897",
"Id": "250809",
"ParentId": "250803",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "250809",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T18:39:55.107",
"Id": "250803",
"Score": "5",
"Tags": [
"python",
"algorithm",
"programming-challenge"
],
"Title": "New Year Chaos (HackerRank problem) - find minimum swap count"
}
|
250803
|
<h2>Please see my previous post in the below hyperlink</h2>
<p>I've updated my <code>.htaccess</code> file to account for an HSTS, along with many of the recommended changes. See the snippet below. I'd like to stress that <strong>implementing an HSTS is not to be taken lightly</strong> for anybody else new to it. With that said, I'm looking for advice on what can be done differently from those who have knowledge on <code>.htaccess</code>.</p>
<pre><code>#IMPLEMENT HSTS
<IfModule mod_headers.c>
Header set Strict-Transport-Security "max-age=63072000; includeSubDomains; preload"
</IfModule>
#CUSTOM ERROR PAGES
ErrorDocument 400 /allerror.php
ErrorDocument 401 /allerror.php
ErrorDocument 403 /allerror.php
ErrorDocument 404 /allerror.php
ErrorDocument 405 /allerror.php
ErrorDocument 408 /allerror.php
ErrorDocument 500 /allerror.php
ErrorDocument 502 /allerror.php
ErrorDocument 504 /allerror.php
RewriteEngine On
#REDIRECT TO SECURE HTTPS CONNECTION
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
#FORCE WWW TO NON-WWW
RewriteCond %{HTTP_HOST} ^www.example.com [NC]
RewriteRule ^(.*)$ https://example.com/$1 [L,R=301]
#URL EXTENSION REMOVAL
RewriteCond %{THE_REQUEST} /([^.]+)\.html [NC]
RewriteRule ^ /%1 [NC,L,R]
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^ %{REQUEST_URI}.html [NC,L]
#HOTLINKING PROTECTION
RewriteCond %{HTTP_REFERER} !^https://(www\.)?example\.com(/.*)*$ [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteRule \.(css|flv|gif|ico|jpe|jpeg|jpg|js|mp3|mp4|php|png|pdf|swf|txt)$ - [F]
#CONTENT SECURITY POLICY
<FilesMatch "\.(html|php)$">
Header set Content-Security-Policy "default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; img-src 'self' data: 'unsafe-inline'; media-src 'self' data: 'unsafe-inline'; connect-src 'self';"
</FilesMatch>
#REDIRECT FOR DATE PAGE
RewriteRule ^date$ /storage/date-202010 [R=301,L]
#REDIRECT FOR HOME PAGE
RewriteRule ^home$ / [R=301,L]
#PREVENT DIRECTORY BROWSING
Options All -Indexes
#FILE CACHING
#cache html and htm files for one day
<FilesMatch "\.(html|htm)$">
Header set Cache-Control "max-age=43200"
</FilesMatch>
#cache css, javascript and text files for one week
<FilesMatch "\.(js|css|txt)$">
Header set Cache-Control "max-age=604800"
</FilesMatch>
#cache flash and images for one month
<FilesMatch "\.(flv|swf|ico|gif|jpg|jpeg|mp4|png)$">
Header set Cache-Control "max-age=2592000"
</FilesMatch>
#disable cache for script files
<FilesMatch "\.(pl|php|cgi|spl|scgi|fcgi)$">
Header unset Cache-Control
</FilesMatch>
#BLOCKS FILE TYPES FOR USERS
<FilesMatch "\.(ht[ap]|ini|log|sh|inc|bak)$">
Require all denied
</FilesMatch>
</code></pre>
<h2>HSTS Implementation</h2>
<p>To note a few things that I've learned while researching HSTS:</p>
<ol>
<li>An SSL certificate is required</li>
<li>If your sites are available via HTTP, redirect all requests to HTTPS with a 301 Permanent Redirect.</li>
<li>Include the following in your <code>.htaccess</code> file: <code>Strict-Transport-Security: max-age=31536000; includeSubDomains; preload</code>. Max-age must be at least 10886400 seconds or 18 Weeks. Go for the two years value.</li>
<li>Add your domain to a preload list using the first link below.</li>
</ol>
<p>I encourage everyone to read each source below for more information.</p>
<ul>
<li><a href="https://hstspreload.org/" rel="nofollow noreferrer">HSTS Preload List Submission</a></li>
<li><a href="https://www.acunetix.com/blog/articles/what-is-hsts-why-use-it/" rel="nofollow noreferrer">What is HSTS and Why Should I use it? | Acunetix</a></li>
<li><a href="https://networkdynamics.com/2017/11/what-is-hsts-and-should-i-implement-it/" rel="nofollow noreferrer">What is HSTS and should I implement it? | Network Dynamics</a></li>
<li><a href="https://searchengineland.com/why-websites-should-be-using-hsts-to-improve-security-and-seo-304380" rel="nofollow noreferrer">Why websites should be using HSTS to improve security and SEO</a></li>
</ul>
|
[] |
[
{
"body": "<p>There are two aspects to HTTP Strict Transport Security (HSTS):</p>\n<ol>\n<li>Implementing HSTS on your site.</li>\n<li>Submitting your already HSTS enabled site to the <a href=\"https://hstspreload.org/\" rel=\"nofollow noreferrer\">HSTS preload list</a>. This is where the "list of HSTS sites" are compiled directly into the browser, which avoids the first request ever being over HTTP (where the request is potentially vulnerable to MITM attacks).</li>\n</ol>\n<p>You seem to be going straight for #2. This is not necessarily recommended. Think of the "preload list" as a one-way trip. Technically it's possible to be removed from the preload list; realistically that's not something you want to even be thinking about. (It's hard - slow - enough stepping back from HSTS-only.)</p>\n<p>The preload list submission page itself does not recommend going straight to "preload list submission". The recommendation is to increase the <code>max-age</code> parameter over a period of time (months), before taking the final step to submitting to the preload list. Test test test in the meantime to ensure SSL certs are reliably renewed, no mixed content warnings etc. etc.</p>\n<p>I would also be wary about HSTS preload list submission (or even HSTS itself to some degree) on a <em>shared server</em>, where you don't have full control over the SSL configuration. You don't actually state whether you are on a shared server or not, but since you are doing all this config in <code>.htaccess</code>, I assume that you are. If you have your own server and access to the server config then most of this should be configured in the server/virtualhost config (and it is arguably easier and more reliable to do so).</p>\n<p>Remember, that once you have gone the HSTS route (and users have accessed the HTTPS site or you are on the "preload list") then your site can <em>only</em> be accessed over HTTPS. This doesn't just apply to your site, but also to any 3rd party services you might be using (mixed content browser warnings etc.).</p>\n<blockquote>\n<pre><code>#IMPLEMENT HSTS\n<IfModule mod_headers.c>\nHeader set Strict-Transport-Security "max-age=63072000; includeSubDomains; preload"\n</IfModule>\n</code></pre>\n</blockquote>\n<p>This sets the required HSTS HTTP response header on "most"<sup><b>*1</b></sup> responses (but note the <code>preload</code> parameter, which should probably be omitted initially).</p>\n<p><sup><b>*1</b></sup> However, this directive does not necessarily set the required header on <em>all</em> responses. A requirement of HSTS is that you also set the header on "redirect" responses (eg. www to non-www on HTTPS). Currently the above does not do this. You should be using the <code>always</code> <em>condition</em> on the <code>Header</code> directive to set the header on responses other than 200 OK. For example:</p>\n<pre><code># Use "always" condition to set on "redirects" as well.\nHeader always set Strict-Transport-Security "max-age=63072000; includeSubDomains"\n</code></pre>\n<p>(I've also removed the <code>preload</code> parameter for now.)</p>\n<p>You do not need the <code><IfModule></code> wrapper and should be removed. mod_headers should be enabled by default. This is <em>your</em> server, you know whether mod_headers is enabled or not. mod_headers <em>must</em> be enabled for this to work. You don't want this to <em>silently</em> fail should mod_headers not be available - you need notification as soon as this fails with an error in your logs.</p>\n<p>Many articles state that you should <em>only</em> set the <code>Strict-Transport-Security</code> header on secure (HTTPS) responses. And the "preload list submission" does indeed issue a "warning" (not strictly an "error" I believe) if you send the header over HTTP as well. However, whilst it only <em>needs</em> to be set on the HTTPS response, compliant browsers ignore this header when sent over an unencrypted HTTP connection (to prevent MITM attacks) so it should not matter whether the header is "unnecessarily" sent over HTTP as well. This would be easier to manage in the appropriate <code><VirtualHost></code> containers in the main server config. Sending this header <em>only</em> on HTTPS responses in <code>.htaccess</code> is more complex (and hence more prone to error). You would need to employ an additional environment variable that you can use to set the HSTS response header conditionally.</p>\n<p>For example:</p>\n<pre><code># Set environment var "HSTS" if accessed over HTTPS connection\nRewriteCond %{HTTPS} on\nRewriteRule ^ - [E=HSTS:1]\n\n# Conditionally set only on HTTPS connections (ie. when "HSTS" env var is set)\nHeader always set Strict-Transport-Security "max-age=63072000; includeSubDomains" env=HSTS\n</code></pre>\n<p>Otherwise, I believe your remaining directives are OK with regards to HSTS. But as always, test test test.</p>\n<hr />\n<h3>Resolve multiple (unnecessary) redirects</h3>\n<blockquote>\n<pre><code>#FORCE WWW TO NON-WWW\nRewriteCond %{HTTP_HOST} ^www.example.com [NC]\nRewriteRule ^(.*)$ https://example.com/$1 [L,R=301]\n\n#URL EXTENSION REMOVAL\nRewriteCond %{THE_REQUEST} /([^.]+)\\.html [NC]\nRewriteRule ^ /%1 [NC,L,R]\n</code></pre>\n</blockquote>\n<p>A potential issue here (with the 2nd and 3rd canonical redirects above, after the HTTP to HTTPS redirect) is that this potentially results in two additional redirects if <code>www</code> + <code>.html</code> is requested. This could be resolved by simply reversing the two redirects and including the canonical hostname in the "URL EXTENSION REMOVAL" redirect (as mentioned in <a href=\"https://codereview.stackexchange.com/a/250710/6744\" title=\".htaccess Recommendations\">my answer to your earlier question</a>).</p>\n<p>For example:</p>\n<pre><code>#URL EXTENSION REMOVAL\nRewriteCond %{THE_REQUEST} /([^.]+)\\.html [NC]\nRewriteRule ^ https://example.com/%1 [R=301,L]\n\n#FORCE WWW TO NON-WWW\nRewriteCond %{HTTP_HOST} ^www\\.example\\.com [NC]\nRewriteRule (.*) https://example.com/$1 [R=301,L]\n</code></pre>\n<p>See <a href=\"https://codereview.stackexchange.com/a/250710/6744\" title=\".htaccess Recommendations\">my previous answer</a> for an alternative approach to the "URL EXTENSION REMOVAL" redirect that addresses some potential issues.</p>\n<p>If you are not using the <code>www</code> subdomain on other hostnames (eg. <code>www.subdomain.example.com</code>) then you could simplify the <em>CondPattern</em> on the www to non-www redirect to simply <code>^www\\.</code>, ie. any requested hostname that simply starts <code>www.</code>, rather than checking the entire hostname.</p>\n<hr />\n<h1>Additional Fixes</h1>\n<h3>URL Extension Removal / Rewrite Loop (500 Internal Server Error)</h3>\n<p>There are a couple of other issues that I did not get round to addressing in <a href=\"https://codereview.stackexchange.com/a/250710/6744\" title=\".htaccess Recommendations\">your earlier question</a>, not relating to HSTS, which I'll cover below...</p>\n<blockquote>\n<pre><code>#URL EXTENSION REMOVAL\n:\nRewriteCond %{REQUEST_FILENAME}.html -f\nRewriteRule ^ %{REQUEST_URI}.html [NC,L]\n</code></pre>\n</blockquote>\n<p>This (and similar) is one of those code snippets that is "blindly" copy/pasted everywhere (and I mean <em>everywhere</em>) as the "standard" way to append (URL-rewrite) the file-extension when using extensionless URLs. However, whilst it probably "works" for your valid-URLs, it has a serious flaw when requesting invalid-URLs...</p>\n<p>If <code>/about.html</code> is a valid file that you wish to serve when requesting the extensionless URL <code>/about</code> then it works OK. However, if I (maliciously) requested <code>/about/</code> or <code>/about/<anything></code> it will send your server into a spiralling rewrite-loop, resulting in 500 Internal Server Error response. The end-user should not be able to invoke such a response (potentially more vulnerable to DDOS attacks and other hostile behaviour).</p>\n<p>This is because <code>REQUEST_FILENAME</code> (the mapped filesystem path) does not necessarily refer to the same public URL-path as the <code>REQUEST_URI</code> (requested URL-path) variable.</p>\n<p>To resolve this, use <code>REQUEST_URI</code> throughout. For example:</p>\n<pre><code>RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI}.html -f\nRewriteRule ^ %{REQUEST_URI}.html [L]\n</code></pre>\n<p>(The <code>NC</code> flag is superfluous on the <code>RewriteRule</code> directive here.)</p>\n<p>See <a href=\"https://serverfault.com/a/989351/49157\">my answer</a> to <a href=\"https://serverfault.com/questions/989333/using-apache-rewrite-rules-in-htaccess-to-remove-html-causing-a-500-error\" title=\"Using Apache rewrite rules in .htaccess to remove .html causing a 500 error\">the following ServerFault question</a> for more detail on this.</p>\n<h3>Hotlink Protection - Simplify Condition</h3>\n<blockquote>\n<pre><code>#HOTLINKING PROTECTION\nRewriteCond %{HTTP_REFERER} !^https://(www\\.)?example\\.com(/.*)*$ [NC]\n</code></pre>\n</blockquote>\n<p>This is relatively minor. The regex in the above condition can be simplified. At this point in the <code>.htaccess</code> file, the hostname has already been canonicalised to remove the www the subdomain, so the <code>(www\\.)?</code> subpattern in the above is superfluous. As is the trailing <code>(/.*)*$</code> subpattern, which simply <em>matches</em> everything else. You don't need to actually <em>match</em> anything here, you just need to assert that the <code>Referer</code> header starts with the appropriate (scheme+)hostname.</p>\n<p>For example:</p>\n<pre><code>RewriteCond %{HTTP_REFERER} !^https://example\\.com\n</code></pre>\n<p>The <code>NC</code> flag is also superfluous here. Forcing a case-insensitive match when it's not required just creates (a tiny bit) more work for your server and in some cases can open you up to vulnerabilities ("duplicate content" being a common one - although that is not an issue here).</p>\n<h3>Enabling unnecessary <code>Options</code></h3>\n<blockquote>\n<pre><code>#PREVENT DIRECTORY BROWSING\nOptions All -Indexes\n</code></pre>\n</blockquote>\n<p>This doesn't <em>only</em> prevent "directory browsing". The <code>All</code> argument <em>enables</em> a bunch of other stuff that you probably don't need, such as server-side includes (<code>Includes</code>) and the ability to execute CGI scripts (<code>ExecCGI</code>). (Incidentally, this is the only time when you can mix arguments with a <code>+</code> or <code>-</code> with those without.) To <em>only</em> prevent directory browsing (ie. the auto generating of directory indexes by mod_autoindex) then remove the <code>All</code> argument.</p>\n<p>However, you probably only <em>need</em> <code>FollowSymLinks</code> (which might already be set in the server config), so you could set the following instead:</p>\n<pre><code>Options FollowSymLinks\n</code></pre>\n<p>Note the absence of <code>+</code> or <code>-</code>. This <em>only</em> sets <code>FollowSymLinks</code>, so disabling <code>Indexes</code> ("directory browsing") if it was already set.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-27T16:09:48.487",
"Id": "251218",
"ParentId": "250805",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "251218",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T19:21:31.033",
"Id": "250805",
"Score": "5",
"Tags": [
"security",
"error-handling",
"cache",
".htaccess",
"https"
],
"Title": "HSTS Recommendations in .htaccess"
}
|
250805
|
<p>Write a C program that will implement the basic operations of table processors.</p>
<p>The input will be text data read from a <em>.txt</em> file, operations will be defined using terminal arguments, and the output will be in a <em>.txt</em> file as well.</p>
<p>Program should be run the following way:</p>
<pre><code>./main [-d delimiter] [name of the function for the table] <in.txt >out.txt
</code></pre>
<p>Where the <code>-d</code> argument determines which symbols can be interpreted as separators of single cells, by default the <code>delimiter</code> is a space character.</p>
<p>Multiple cases of the same sign in the delimiter are ignored.</p>
<p>The first sign in the delimiter character will be used as the separator of output values.</p>
<p><code>name of the function</code> is the identifier of the function that will be called to perform certain tasks on the table. <code><in.txt</code> redirects reading from stdin to reading from <em>in.txt</em>, <code>>out.txt</code> redirects outputting to stdout to outputting to <code>out.txt</code>.</p>
<p>Here's what I wrote:</p>
<pre><code>#include <stdio.h>
#include <string.h>
int main(int argc, char* argv[])
{
if((argc > 2) && (strcmp(argv[1], "-d") == 0)) {
char delim = *argv[2];
for (int i; (i = getchar()) != EOF; ) {
if(i == '\n')
putchar(i);
if(!((i >= '0' && i <= '9') || (i >= 'a' && i <= 'z') || (i >= 'A' && i <= 'Z')) ){
putchar(delim);
continue;
}
putchar(i);
}
}
else if((argc == 2) && strcmp(argv[1], "-d") == 0) {
char delim = ' ';
for (int i; (i = getchar()) != EOF; ) {
if(i == '\n')
putchar(i);
if(!((i >= '0' && i <= '9') || (i >= 'a' && i <= 'z') || (i >= 'A' && i <= 'Z')) ){
putchar(delim);
continue;
}
putchar(i);
}
}
return 0;
}
</code></pre>
<p>The code works and does what it's supposed to, but I am not sure about the effectivity of the implementation. The requirements are: input table can't be an empty file, maximum length of a row (both input & output) is 10KiB, otherwise an error message should be shown. Using global variables isn't allowed, preprocessor macro <code>#define</code> is. Functions for working with files and dynamic memory allocation aren't allowed as well.</p>
<p>What are the ways to change my code?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T09:18:44.527",
"Id": "493906",
"Score": "0",
"body": "Maybe the loop body can be reduced to `putchar( (isalnum(i) || i=='\\n') ? i : delim);`"
}
] |
[
{
"body": "<p>It would be helpful for you to break up the code into functions, that will simplify each task.</p>\n<p>Process the command line arguments first, then once you have the delimiter process the text files.</p>\n<ol>\n<li>Declare the variable <code>delim</code> above any logic and initialize it to the default value</li>\n<li>Process the command line to get the actual delimiter.</li>\n<li>Process the input file.</li>\n</ol>\n<p>This should shorten the code because you only need one loop to process the input file rather than 2.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T22:21:07.773",
"Id": "250812",
"ParentId": "250811",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "250812",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T21:23:58.030",
"Id": "250811",
"Score": "4",
"Tags": [
"c",
"strings",
"io"
],
"Title": "Processing delimiter characters in C?"
}
|
250811
|
<p>In a recent toy project, I made heavy use of calculations involving polynomials in Z[x]. As an experiment, I decided to try out implementing expression templates - and it did seem to provide drastic speed-ups in my primary use case, with minimal changes to the consumer code. (In case it might be useful to see the context where I'm using this library, see: <a href="https://github.com/dschepler/groebner-zx" rel="nofollow noreferrer">https://github.com/dschepler/groebner-zx</a> .)</p>
<p>Here, my primary concern is with the expression template implementation part of the library. Some of my current thoughts (though if these particular questions are too open-ended to provide good answers, that's fair; on the other hand, if there are standard answers, in particular for the reference vs. move of subexpression objects question, then I'm all ears):</p>
<ul>
<li>I chose here to capture references to subexpressions throughout; so for example, <code>auto myexpr = 2 * p + q;</code> would immediately result in dangling references to the <code>2 * p</code> subexpression. It could also be possible to move-capture intermediate subexpressions; though this would increase the implementation complexity (in particular, I would still want to avoid making copies of <code>polynomial</code> leaf expressions which are references to existing variables).</li>
<li>One possibility I've been thinking of would be: providing a special class for subexpressions where it's easy to determine at compile time that the result of the subexpression is a monomial; and then that would allow for providing for optimized implementations of multiplication by a monomial. That would make consumer code a bit more readable: for example, instead of <code>p -= 2 * times_x_to(q, 3);</code> it would read <code>p -= 2 * x_to(3) * q;</code>. But again, at a cost of increased implementation complexity.</li>
</ul>
<p>Things that I'm aware of but are not as much of a concern for the purposes of this review include:</p>
<ul>
<li>A possibility of templatizing the polynomial type so that it could also be used for polynomials over Q, over <code>double</code>, over mpfr arbitrary-precision reals, etc.</li>
<li>Internal representation choices - in particular, whether it might be better to store the coefficients in order of increasing degree.</li>
</ul>
<p>polynomial.h:</p>
<pre><code>#pragma once
#include <gmpxx.h>
#include <initializer_list>
#include <iostream>
#include <string>
#include <vector>
using Z = mpz_class;
inline Z operator""_Z(const char* s)
{
return operator""_mpz(s);
}
// This is a library for manipulating polynomials with integer
// coefficients. Note that because the library uses expression
// templates behind the scenes, the following general restrictions
// apply:
//
// * Use of "auto" keyword to initialize a variable with the result
// of a calculation will generally not work as expected. Instead,
// explicitly set the result type to "polynomial". e.g. instead of
// auto p = 2 * q + r;
// write
// polynomial p = 2 * q + r;
//
// * Assignment expressions aliasing the destination variable will not
// work as expected. To work around this, use a polynomial constructor
// to materialize the intermediate result before assignment. e.g.
// instead of
// p += 2 * times_x_to(p + q, 3);
// write
// p += polynomial{2 * times_x_to(p + q, 3)};
// polynomial expression templates: each type should declare a member type
// is_polynomial_expr, and implement methods compatible with:
// int degree_bound() const;
// upper bound on degree of the result (does not need to be exact in
// cases such as sum or difference of two polynomials)
// Z coefficient(int d) const;
// return the coefficient of x^d - where d can still be greater than
// degree_bound()
template <typename CoeffCallable>
class polynomial_expr {
public:
using is_polynomial_expr = std::true_type;
polynomial_expr(int degree_bound, CoeffCallable&& coeff_callable)
: m_degree_bound(degree_bound)
, m_coeff_callable(std::forward<CoeffCallable>(coeff_callable))
{
}
int degree_bound() const { return m_degree_bound; }
Z coefficient(int d) const
{
return m_coeff_callable(d);
}
private:
int m_degree_bound;
typename std::decay_t<CoeffCallable> m_coeff_callable;
};
template <typename PolyExpr1, typename PolyExpr2,
typename = typename std::decay_t<PolyExpr1>::is_polynomial_expr,
typename = typename std::decay_t<PolyExpr2>::is_polynomial_expr>
auto operator+(PolyExpr1&& p, PolyExpr2&& q)
{
return polynomial_expr {
std::max(p.degree_bound(), q.degree_bound()),
[&p, &q](int d) -> Z { return p.coefficient(d) + q.coefficient(d); }
};
}
template <typename PolyExpr1, typename PolyExpr2,
typename = typename std::decay_t<PolyExpr1>::is_polynomial_expr,
typename = typename std::decay_t<PolyExpr2>::is_polynomial_expr>
auto operator-(PolyExpr1&& p, PolyExpr2&& q)
{
return polynomial_expr {
std::max(p.degree_bound(), q.degree_bound()),
[&p, &q](int d) -> Z { return p.coefficient(d) - q.coefficient(d); }
};
}
template <typename PolyExpr,
typename = typename std::decay_t<PolyExpr>::is_polynomial_expr>
auto operator-(PolyExpr&& p)
{
return polynomial_expr {
p.degree_bound(),
[&p](int d) -> Z { return -(p.coefficient(d)); }
};
}
template <typename PolyExpr,
typename = typename std::decay_t<PolyExpr>::is_polynomial_expr>
auto operator*(const Z& n, PolyExpr&& p)
{
return polynomial_expr {
n == 0 ? -1 : p.degree_bound(),
[&n, &p](int d) -> Z { return n * p.coefficient(d); }
};
}
template <typename PolyExpr,
typename = typename std::decay_t<PolyExpr>::is_polynomial_expr>
auto operator*(PolyExpr&& p, const Z& n)
{
return polynomial_expr {
n == 0 ? -1 : p.degree_bound(),
[&n, &p](int d) -> Z { return p.coefficient(d) * n; }
};
}
class polynomial;
polynomial operator*(const polynomial& p, const polynomial& q);
template <typename PolyExpr,
typename = typename std::decay_t<PolyExpr>::is_polynomial_expr>
auto times_x_to(PolyExpr&& p, int d)
{
return polynomial_expr {
p.degree_bound() < 0 ? -1 : p.degree_bound() + d,
[&p, d](int e) -> Z { return e >= d ? p.coefficient(e - d) : 0; }
};
}
template <typename PolyExpr1, typename PolyExpr2,
typename = typename std::decay_t<PolyExpr1>::is_polynomial_expr,
typename = typename std::decay_t<PolyExpr2>::is_polynomial_expr>
bool operator==(PolyExpr1&& p, PolyExpr2&& q)
{
auto d = std::max(p.degree_bound(), q.degree_bound());
for (int i = 0; i <= d; ++i)
if (p.coefficient(i) != q.coefficient(i))
return false;
return true;
}
template <typename PolyExpr1, typename PolyExpr2,
typename = typename std::decay_t<PolyExpr1>::is_polynomial_expr,
typename = typename std::decay_t<PolyExpr2>::is_polynomial_expr>
bool operator!=(PolyExpr1&& p, PolyExpr2&& q)
{
auto d = std::max(p.degree_bound(), q.degree_bound());
for (int i = 0; i <= d; ++i)
if (p.coefficient(i) != q.coefficient(i))
return true;
return false;
}
class polynomial {
public:
using is_polynomial_expr = std::true_type;
polynomial() = default;
polynomial(std::initializer_list<Z> coeffs);
explicit polynomial(std::vector<Z> coeffs);
polynomial(const polynomial&) = default;
polynomial(polynomial&&) = default;
template <typename PolyExpr,
typename = typename std::decay_t<PolyExpr>::is_polynomial_expr>
polynomial(PolyExpr&& p)
{
int d = p.degree_bound();
if (d >= 0) {
m_coeffs.reserve(d + 1);
for (; d >= 0; --d)
m_coeffs.push_back(p.coefficient(d));
normalize();
}
}
polynomial& operator=(const polynomial&) = default;
polynomial& operator=(polynomial&&) = default;
template <typename PolyExpr,
typename = typename std::decay_t<PolyExpr>::is_polynomial_expr>
polynomial& operator=(PolyExpr&& p)
{
auto deg = p.degree_bound();
m_coeffs.resize(deg + 1);
for (int d = 0; d <= deg; ++d)
m_coeffs[deg - d] = p.coefficient(d);
normalize();
return *this;
}
int degree() const { return m_coeffs.size() - 1; }
int degree_bound() const { return degree(); }
const Z& coefficient(int d) const
{
static Z static_zero = 0;
return d > degree() ? static_zero : m_coeffs[degree() - d];
}
// leading_coefficient has as a precondition that the polynomial must not be 0
const Z& leading_coefficient() const
{
return m_coeffs.front();
}
void negate();
template <typename PolyExpr,
typename = typename std::decay_t<PolyExpr>::is_polynomial_expr>
polynomial& operator+=(PolyExpr&& p)
{
if (p.degree_bound() > degree())
m_coeffs.insert(m_coeffs.begin(), p.degree_bound() - degree(), 0);
for (int d = p.degree_bound(); d >= 0; --d)
m_coeffs[m_coeffs.size() - d - 1] += p.coefficient(d);
normalize();
return *this;
}
template <typename PolyExpr,
typename = typename std::decay_t<PolyExpr>::is_polynomial_expr>
polynomial& operator-=(PolyExpr&& p)
{
if (p.degree_bound() > degree())
m_coeffs.insert(m_coeffs.begin(), p.degree_bound() - degree(), 0);
for (int d = p.degree_bound(); d >= 0; --d)
m_coeffs[m_coeffs.size() - d - 1] -= p.coefficient(d);
normalize();
return *this;
}
polynomial& operator*=(Z n);
polynomial& operator*=(const polynomial& p)
{
return *this = (*this * p);
}
std::string to_string() const;
friend std::ostream& operator<<(std::ostream& os, const polynomial& p)
{
return os << p.to_string();
}
private:
std::vector<Z> m_coeffs;
void normalize();
static std::string monomial_to_string(const Z& coeff, int d);
};
</code></pre>
<p>polynomial.cpp:</p>
<pre><code>#include "polynomial.h"
#include <algorithm>
polynomial::polynomial(std::initializer_list<Z> coeffs)
: m_coeffs(coeffs)
{
normalize();
}
polynomial::polynomial(std::vector<Z> coeffs)
: m_coeffs(std::move(coeffs))
{
normalize();
}
void polynomial::normalize()
{
auto first_nonzero = find_if(m_coeffs.begin(), m_coeffs.end(),
[](const Z& coeff) { return coeff != 0; });
m_coeffs.erase(m_coeffs.begin(), first_nonzero);
}
void polynomial::negate()
{
for (auto& coeff : m_coeffs)
coeff = -coeff;
}
polynomial& polynomial::operator*=(Z n)
{
if (n == 0)
m_coeffs.clear();
else {
for (Z& coeff : m_coeffs)
coeff *= n;
}
return *this;
}
namespace polynomial_mult_details {
auto evenpart(const polynomial& p)
{
return polynomial_expr {
p.degree() / 2,
[&p](int d) -> const Z& { return p.coefficient(d * 2); }
};
}
auto oddpart(const polynomial& p)
{
return polynomial_expr {
(p.degree() - 1) / 2,
[&p](int d) -> const Z& { return p.coefficient(d * 2 + 1); }
};
}
template <typename PolyExpr1, typename PolyExpr2,
typename = typename PolyExpr1::is_polynomial_expr,
typename = typename PolyExpr2::is_polynomial_expr>
auto interleave(PolyExpr1&& p, PolyExpr2&& q)
{
return polynomial_expr {
std::max(2 * p.degree_bound(), 2 * q.degree_bound() + 1),
[&p, &q](int d) -> Z {
if (d % 2 == 0)
return p.coefficient(d / 2);
else
return q.coefficient(d / 2);
}
};
}
} // namespace polynomial_mult_details
polynomial operator*(const polynomial& p, const polynomial& q)
{
// Following the classic recursive algorithm with O(d^lg(3)) multiplications of Z values
if (p == polynomial {} || q == polynomial {})
return polynomial {};
if (p.degree() == 0)
return p.coefficient(0) * q;
if (q.degree() == 0)
return p * q.coefficient(0);
// In the following, we'll be using each coefficient of p and q
// multiple times, which is why we have designed the interface to let
// the caller materialize p and q for us.
auto pe = polynomial_mult_details::evenpart(p);
auto po = polynomial_mult_details::oddpart(p);
auto qe = polynomial_mult_details::evenpart(q);
auto qo = polynomial_mult_details::oddpart(q);
polynomial pe_qe = pe * qe;
polynomial po_qo = po * qo;
polynomial pepo_qeqo = (pe + po) * (qe + qo);
return polynomial_mult_details::interleave(
pe_qe + times_x_to(po_qo, 1),
pepo_qeqo - pe_qe - po_qo);
}
std::string polynomial::monomial_to_string(const Z& coeff, int d)
{
std::string result;
if (coeff == 1 && d > 0)
result = "";
else if (coeff == -1 && d > 0)
result = "-";
else {
result = coeff.get_str();
if (d > 0)
result += " ";
}
if (d == 1)
result += "x";
else if (d > 1) {
result += "x^";
result += std::to_string(d);
}
return result;
}
std::string polynomial::to_string() const
{
if (m_coeffs.empty())
return "0";
std::string result = monomial_to_string(m_coeffs.front(), degree());
for (int d = degree() - 1; d >= 0; --d) {
auto coeff = coefficient(d);
if (coeff > 0) {
result += " + ";
result += monomial_to_string(coeff, d);
} else if (coeff < 0) {
result += " - ";
result += monomial_to_string(-coeff, d);
}
}
return result;
}
</code></pre>
<p>And, in case it might be useful to see my current test battery (though I'm aware it's currently missing tests for <code>operator+=,-=,*=</code>):
polynomial_test.cpp:</p>
<pre><code>#include "polynomial.h"
#include <gtest/gtest.h>
TEST(Polynomial, Equality)
{
EXPECT_EQ((polynomial {}), (polynomial {}));
EXPECT_EQ((polynomial { 0, 0 }), (polynomial {}));
EXPECT_EQ((polynomial {}), (polynomial { 0, 0 }));
EXPECT_EQ((polynomial { 1, 2 }), (polynomial { 1, 2 }));
EXPECT_EQ((polynomial { 0, 1, 2 }), (polynomial { 1, 2 }));
EXPECT_EQ((polynomial { 1, 2 }), (polynomial { 0, 1, 2 }));
EXPECT_NE((polynomial { 1, 2 }), (polynomial { 1, 2, 0 }));
}
TEST(Polynomial, Degree)
{
EXPECT_EQ((polynomial {}.degree()), -1);
EXPECT_EQ((polynomial { 5 }.degree()), 0);
EXPECT_EQ((polynomial { 1, 2, 3 }.degree()), 2);
}
TEST(Polynomial, Coefficient)
{
EXPECT_EQ((polynomial {}.coefficient(0)), 0);
EXPECT_EQ((polynomial {}.coefficient(1)), 0);
EXPECT_EQ((polynomial { 5 }.coefficient(0)), 5);
EXPECT_EQ((polynomial { 5 }.coefficient(1)), 0);
EXPECT_EQ((polynomial { 5 }.coefficient(2)), 0);
EXPECT_EQ((polynomial { 1, 2, 3 }.coefficient(0)), 3);
EXPECT_EQ((polynomial { 1, 2, 3 }.coefficient(1)), 2);
EXPECT_EQ((polynomial { 1, 2, 3 }.coefficient(2)), 1);
EXPECT_EQ((polynomial { 1, 2, 3 }.coefficient(3)), 0);
EXPECT_EQ((polynomial { 1, 2, 3 }.coefficient(4)), 0);
}
TEST(Polynomial, Negate)
{
EXPECT_EQ((-polynomial {}), (polynomial {}));
EXPECT_EQ((-polynomial { 1, 2 }), (polynomial { -1, -2 }));
EXPECT_EQ((-polynomial { 1, -3, -2 }), (polynomial { -1, 3, 2 }));
}
TEST(Polynomial, TimesXTo)
{
EXPECT_EQ(times_x_to(polynomial {}, 5), (polynomial {}));
EXPECT_EQ(times_x_to(polynomial { 1, 2, 3 }, 0), (polynomial { 1, 2, 3 }));
EXPECT_EQ(times_x_to(polynomial { 1, 2, 3 }, 3),
(polynomial { 1, 2, 3, 0, 0, 0 }));
}
TEST(Polynomial, ScalarMult)
{
EXPECT_EQ((2 * polynomial {}), (polynomial {}));
EXPECT_EQ((0 * polynomial { 1, 2, 3 }), (polynomial {}));
EXPECT_EQ((3 * polynomial { 1, -2, 3 }), (polynomial { 3, -6, 9 }));
EXPECT_EQ((-3 * polynomial { 1, -2, 3 }), (polynomial { -3, 6, -9 }));
}
TEST(Polynomial, Add)
{
EXPECT_EQ((polynomial {} + polynomial {}), (polynomial {}));
EXPECT_EQ((polynomial { 1, 2, 3 } + polynomial {}), (polynomial { 1, 2, 3 }));
EXPECT_EQ((polynomial {} + polynomial { 1, 2, 3 }), (polynomial { 1, 2, 3 }));
EXPECT_EQ((polynomial { 1, 2, 3 } + polynomial { 1, 2, 3 }), (polynomial { 2, 4, 6 }));
EXPECT_EQ((polynomial { 1, 2, 3 } + polynomial { -1, -2, -3 }), (polynomial {}));
EXPECT_EQ((polynomial { 1, 2, 3, 4 } + polynomial { -1, -2, 5, 6 }),
(polynomial { 8, 10 }));
EXPECT_EQ((polynomial { 1, 2, 3, 4 } + polynomial { 5, 6 }),
(polynomial { 1, 2, 8, 10 }));
EXPECT_EQ((polynomial { 5, 6 } + polynomial { 1, 2, 3, 4 }),
(polynomial { 1, 2, 8, 10 }));
}
TEST(Polynomial, Subtract)
{
EXPECT_EQ((polynomial {} - polynomial {}), (polynomial {}));
EXPECT_EQ((polynomial { 1, 2, 3 } - polynomial {}), (polynomial { 1, 2, 3 }));
EXPECT_EQ((polynomial {} - polynomial { 1, 2, 3 }), (polynomial { -1, -2, -3 }));
EXPECT_EQ((polynomial { 1, 2, 3 } - polynomial { 1, 2, 3 }), (polynomial {}));
EXPECT_EQ((polynomial { 1, 2, 3, 4 } - polynomial { 1, 2, 5, 6 }),
(polynomial { -2, -2 }));
EXPECT_EQ((polynomial { 1, 2, 3, 4 } - polynomial { 5, 6 }),
(polynomial { 1, 2, -2, -2 }));
EXPECT_EQ((polynomial { 5, 6 } - polynomial { 1, 2, 3, 4 }),
(polynomial { -1, -2, 2, 2 }));
}
TEST(Polynomial, Multiply)
{
EXPECT_EQ((polynomial {} * polynomial {}), (polynomial {}));
EXPECT_EQ((polynomial {} * polynomial { 1, 2, 3 }), (polynomial {}));
EXPECT_EQ((polynomial { 1, 2, 3 } * polynomial {}), (polynomial {}));
EXPECT_EQ((polynomial { 2 } * polynomial { 1, 2, 3 }), (polynomial { 2, 4, 6 }));
EXPECT_EQ((polynomial { 1, 2, 3 } * polynomial { 2 }), (polynomial { 2, 4, 6 }));
EXPECT_EQ((polynomial { 1, 5 } * polynomial { 1, 6 }), (polynomial { 1, 11, 30 }));
EXPECT_EQ((polynomial { 1, 2 } * polynomial { 1, -2 }), (polynomial { 1, 0, -4 }));
EXPECT_EQ((polynomial { 1, 1, 1, 1, 1 } * polynomial { 1, 1, 1 }), (polynomial { 1, 2, 3, 3, 3, 2, 1 }));
}
TEST(Polynomial, ExprTemplates)
{
polynomial p { 2, 3, 4 };
polynomial q { 5, 6 };
EXPECT_EQ(p * q - p, p * (q - polynomial { 1 }));
EXPECT_EQ(p + q + p, 2 * p + q);
EXPECT_EQ(3 * p + 4 * times_x_to(q, 2), (polynomial { 20, 30, 9, 12 }));
EXPECT_EQ(5 * p - 2 * times_x_to(q, 1), (polynomial { 3, 20 }));
}
TEST(Polynomial, ToString)
{
EXPECT_EQ((polynomial {}.to_string()), "0");
EXPECT_EQ((polynomial { 13 }.to_string()), "13");
EXPECT_EQ((polynomial { -3 }.to_string()), "-3");
EXPECT_EQ((polynomial { 1, 0 }.to_string()), "x");
EXPECT_EQ((polynomial { 1, 4 }.to_string()), "x + 4");
EXPECT_EQ((polynomial { 1, -4 }.to_string()), "x - 4");
EXPECT_EQ((polynomial { 2, 3 }.to_string()), "2 x + 3");
EXPECT_EQ((polynomial { -2, -3 }.to_string()), "-2 x - 3");
EXPECT_EQ((polynomial { -1, 5 }.to_string()), "-x + 5");
EXPECT_EQ((polynomial { 1, 3, 2 }.to_string()), "x^2 + 3 x + 2");
EXPECT_EQ((polynomial { 1, 0, -3, 0, 0, 1, 5 }.to_string()), "x^6 - 3 x^4 + x + 5");
EXPECT_EQ((polynomial { -1, 0, 0, 0 }.to_string()), "-x^3");
EXPECT_EQ((polynomial { 1, 0, 1 }.to_string()), "x^2 + 1");
EXPECT_EQ((polynomial { 1, 0, -1 }.to_string()), "x^2 - 1");
EXPECT_EQ((polynomial { -1 }.to_string()), "-1");
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T11:28:54.177",
"Id": "493558",
"Score": "0",
"body": "How dramatic were the speedups, and was that with compiler optimizations enabled or not?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T17:23:28.050",
"Id": "493593",
"Score": "0",
"body": "In my go-to \"expensive\" test case, the execution time decreased from 2 seconds to 0.5 seconds. (And yes, naturally for performance comparisons I use versions with compiler optimizations enabled.)"
}
] |
[
{
"body": "<h1>Consider the <a href=\"https://en.wikipedia.org/wiki/Principle_of_least_astonishment\" rel=\"nofollow noreferrer\">Principle of Least Astonishment</a></h1>\n<p>Unless you know the implementation details of your classes, it is hard to understand why the following works:</p>\n<pre><code>std::cout << polynomial{1} << "\\n";\n</code></pre>\n<p>But this doesn't:</p>\n<pre><code>std::cout << polynomial{1} + polynomial{2} << "\\n";\n</code></pre>\n<p>You already explained why, but having to remember this and to wrap the expression in yet another <code>polynomial{}</code> is frustrating and tedious. Some users, when faced with something like this, will add <code>polynomial{}</code> around everything, even if it doesn't need it, and then any performance benefit will be lost.</p>\n<p>You should have the public interface follow the principle of least astonishment, and have it work exactly like you expect regular expressions to work, as far as possible. Performance should be of secondary concern here. However, that does not mean that you shouldn't have <code>polynomial_expr</code> at all. It does mean however that you should try to:</p>\n<ul>\n<li>Make <code>polynomial</code> itself be more efficient, or</li>\n<li>Make <code>polynomial_expr</code>s implicitly cast to <code>polynomial</code> where needed, or</li>\n<li>Provide overloads for <code>polynomial_expr</code> that make it behave like <code>polynomial</code>.</li>\n</ul>\n<p>For example, I can make the second statement I wrote above compile and run by adding:</p>\n<pre><code>template <typename CoeffCallable>\nclass polynomial_expr {\n ...\n friend std::ostream &operator<<(const std::ostream &out, const polynomial_expr &expr);\n};\n\n... // after definition of class polynomial:\n\ntemplate <typename CoeffCallable>\nstd::ostream &operator<<(std::ostream &out, const polynomial_expr<CoeffCallable> &expr)\n{\n return out << polynomial{expr};\n}\n</code></pre>\n<h1>Why are <code>polynomial_expr</code>s faster than <code>polynomial</code>s?</h1>\n<p>I think the reason why returning <code>polynomial_expr</code>s is faster is because you avoid constructing a new <code>polynomial</code> with the result, which involves constructing a <code>std::vector</code> with the coefficients. Since that requires memory allocation, which has side-effects and might change behaviour if, for example, the global <code>operator new</code> is overloaded, compilers might not be able to optimize this away, even if they can see that the resulting <code>polynomial</code> itself is just a temporary.</p>\n<p>But C++ users are used to this kind of performance issue; it is why we often modify containers in-place for example. So instead of writing:</p>\n<pre><code>polynomial p1, p2, p3 = ...;\npolynomial result = p1 + p2 * p3;\n</code></pre>\n<p>If you know you no longer need to keep the original values around, you can write:</p>\n<pre><code>polynomial p1, p2, p3 = ...;\np1 += p2 *= p3;\n</code></pre>\n<p>While that doesn't win any beauty contests either, it is at least less surprising, and it a way a performance-conscious user can get high-performance code with just your <code>polynomial</code> class.</p>\n<h1>Making <code>polynomial</code> go faster</h1>\n<p>As I mentioned before, the fact that <code>polynomial</code> uses a <code>std::vector</code> means it needs to do heap memory allocations. Consider using a different container for storing the coefficients that implements a <a href=\"https://stackoverflow.com/questions/2178281/small-string-optimization-for-vector\">small vector optimization</a>.</p>\n<p>Furthermore, you already mentioned making monomials a special case. I think that's a good idea, but you can maybe generalize this optimization, and make it so you only store coefficients between the highest and lowest non-zero coefficient. For example, make it so the polynomial <span class=\"math-container\">\\$x^{102} + x^{101} + x^{100}\\$</span> only stores three coefficients. The implementation can be as simple as adding a member variable to <code>class polynomial</code> that stores the offset to the lowest non-zero coefficient. Of course, this might mean a bit more work here and there, but some operations will greatly benefit from this. For example, multiplying or dividing by a unity monomial will be trivial.</p>\n<h1>Making it even easier to use</h1>\n<p>You already mentioned that <code>x_to()</code> would be a nice short way to write a monomial. Even shorter would be <code>X()</code>, but since that is a very short name you probably want to put it in a namespace, to avoid polluting the global namespace, and so that users can opt-in to that:</p>\n<pre><code>namespace polynomial_utilities {\npolynomial_expr X(int d = 1) {\n return {d, [&p, d](int e) -> Z { return int(e == d); }};\n}\n}\n\n...\n\nusing polynomial_utilies::X;\nauto expr = 3 * X(2) - 5 * X() + 4;\n</code></pre>\n<p>Alternatively you could make <code>d</code> a template parameter so you have to use angle brackets.</p>\n<h1>Add a way to evaluate a <code>polynomial</code> at a given point</h1>\n<p>It's very nice that you can build polynomials and print them, but usually you will want to evaluate the polynomial at a given point. So I would add an <code>operator()()</code> to do this:</p>\n<pre><code>class polynomial {\n ...\n template<typename T>\n T operator()(T x) {\n T result{0};\n T multiplier{1};\n\n for (auto &coeff: m_coeffs) {\n result += coeff * multiplier;\n multiplier *= x;\n }\n\n return result;\n }\n}\n</code></pre>\n<p>So you can write:</p>\n<pre><code>polynomial func{3, -5, 4};\nstd::cout << func(1.5) << "\\n"; // should print: 3.25\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T19:49:14.797",
"Id": "493608",
"Score": "0",
"body": "I suppose instead of the `p1 += p2 *= p3;` example, you could instead provide rvalue overloads of the operators which reuse storage (similar to what the standard library does for `std::string`), and then write `polynomial result = std::move(p1) + std::move(p2) * std::move(p3)`. Right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T19:53:04.947",
"Id": "493611",
"Score": "0",
"body": "Though in my particular use case, the most frequent operation (as part of an implementation of modding out one polynomial in a set by another) is `p -= quotient * times_x_to(q, i);` where `q` is a const reference to an element in the set which has to remain in it; so as far as I can see, the rvalue overloads or similar wouldn't be applicable in that use case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T19:56:25.077",
"Id": "493613",
"Score": "0",
"body": "(And by the way, I chose to have that modding out operation be in my consumer code instead of as an `operator%=` in the library because in general, for the integer coefficient case, different users might want different semantics for which remainder they want - i.e. I chose to have remainder in the range [0, |leading_divisor_coeff|) whereas others might want more like standard C/C++ remainder behavior, or [-|divisor_coeff|/2, |divisor_coeff|/2], etc.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T20:21:19.917",
"Id": "493616",
"Score": "0",
"body": "Hmm, I'm actually a bit surprised that `std::cout << polynomial{2} + polynomial{3};` doesn't work -- I would have thought it would choose the `operator<<(std::ostream&, const polynomial&)` overload with a conversion from the `polynomial_expr<...>` argument."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T20:44:24.713",
"Id": "493619",
"Score": "1",
"body": "Oh, rvalue overloads, I hadn't thought of that. That might work too, but that requires some effort to support. As for the modulo operator, you could leave it out, but if you support it I would make it behave as much as possible as that operator does for `int`s, again because of least astonishment for a C++ programmer. As for `operator<<(..., polynomial)` not being chosen: this is because of how [argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl) works."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T21:53:39.220",
"Id": "493625",
"Score": "0",
"body": "Ah, I see... So, moving the `operator<<` from a friend function inside the class to an inline function outside the class made `std::cout << times_x_to(polynomial{2}, 1) + polynomial{3} << '\\n';` work as expected."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T22:10:49.297",
"Id": "493630",
"Score": "0",
"body": "Which brings up another point: it would probably be good to have an automatic conversion from `Z` to `polynomial` (and likewise for integral types, since C++ won't apply chains of conversions `int -> Z -> polynomial`) - and then some overloads would probably be necessary to have things like your `3 * X(2) - 5 * X() + 4` example work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T06:27:18.383",
"Id": "493658",
"Score": "0",
"body": "In general, you should be careful with an out-of-class `operator<<`, as you might unintentionally allow it to handle more types than you expect, because now everything that implicitly converts to a `polynomial` will work. Luckily you use `explicit` and SFINAE in your constructors of `polynomial` to prevent this."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T19:10:20.047",
"Id": "250878",
"ParentId": "250813",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "250878",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T23:25:37.813",
"Id": "250813",
"Score": "4",
"Tags": [
"c++",
"library",
"template-meta-programming"
],
"Title": "Polynomial library using expression templates"
}
|
250813
|
<p>I have a slow query on a wordpress site. How can I rewrite this to make it faster? I'm not having much luck. The query takes about 0.900 seconds I have both the query and the explain below, my goal is to modify this query to make it execute faster, thanks.</p>
<p>This is the query:</p>
<pre><code>SELECT
wrapper_featured_colorways.id,
wrapper_featured_colorways.design_name AS dname,
wrapper_featured_colorways.designId,
wrapper_featured_colorways.submodel_id,
wrapper_featured_colorways.sled_image,
wrapper_featured_colorways.sled_png,
wrapper_featured_colorways.colorway_name,
wrapper_featured_colorways.engineId,
wrapper_featured_colorways.yearText,
wrapper_submodels.model_id,
wrapper_submodels.sub_name,
wrapper_models.model_name,
wrapper_chassis.id AS chassis_id,
wrapper_chassis.chassis_name,
wrapper_manufacturers.mf_name,
wrapper_manufacturers.mf_id,
a.guid AS svgPath,
afx_posts.post_type,
afx_posts.post_title,
GROUP_CONCAT(
wrapper_featured_colorway_colors.color_name
ORDER BY
wrapper_featured_colorway_colors.sort_order
) AS colors
FROM
wrapper_featured_colorways
JOIN afx_posts a ON
(
a.post_parent = wrapper_featured_colorways.designId
)
JOIN afx_posts ON(
afx_posts.ID = wrapper_featured_colorways.designId
)
JOIN afx_postmeta z ON
(
(z.meta_key = 'svg_image') AND(a.ID = z.meta_value)
)
JOIN wrapper_submodels ON wrapper_featured_colorways.submodel_id = wrapper_submodels.id
JOIN wrapper_models ON wrapper_submodels.model_id = wrapper_models.id
JOIN wrapper_chassis ON wrapper_models.chassis_id = wrapper_chassis.id
JOIN wrapper_manufacturers ON wrapper_chassis.manufacturer_id = wrapper_manufacturers.mf_id
JOIN wrapper_featured_colorway_colors ON wrapper_featured_colorways.id = wrapper_featured_colorway_colors.colorway_id
WHERE
wrapper_featured_colorways.deleted = 0
GROUP BY
wrapper_featured_colorway_colors.colorway_id
</code></pre>
<p>This is the Explain:</p>
<pre><code>EXPLAIN SELECT
wrapper_featured_colorways.id,
wrapper_featured_colorways.design_name AS dname,
wrapper_featured_colorways.designId,
wrapper_featured_colorways.submodel_id,
wrapper_featured_colorways.sled_image,
wrapper_featured_colorways.sled_png,
wrapper_featured_colorways.colorway_name,
wrapper_featured_colorways.engineId,
wrapper_featured_colorways.yearText,
wrapper_submodels.model_id,
wrapper_submodels.sub_name,
wrapper_models.model_name,
wrapper_chassis.id AS chassis_id,
wrapper_chassis.chassis_name,
wrapper_manufacturers.mf_name,
wrapper_manufacturers.mf_id,
a.guid AS svgPath,
afx_posts.post_type,
afx_posts.post_title,
GROUP_CONCAT(
wrapper_featured_colorway_colors.color_name
ORDER BY
wrapper_featured_colorway_colors.sort_order
) AS colors
FROM
wrapper_featured_colorways
JOIN afx_posts a ON
(
a.post_parent = wrapper_featured_colorway[...]
1 SIMPLE wrapper_manufacturers
NULL
ALL PRIMARY
NULL
NULL
NULL
4 100.00 Using temporary; Using filesort
1 SIMPLE wrapper_featured_colorways
NULL
ALL PRIMARY
NULL
NULL
NULL
45 10.00 Using where; Using join buffer (Block Nested Loop)
1 SIMPLE wrapper_submodels
NULL
eq_ref PRIMARY PRIMARY 4 fxgraphi_v2019.wrapper_featured_colorways.submodel_id 1 100.00 Using where
1 SIMPLE wrapper_models
NULL
eq_ref PRIMARY PRIMARY 4 fxgraphi_v2019.wrapper_submodels.model_id 1 100.00 Using where
1 SIMPLE wrapper_chassis
NULL
eq_ref PRIMARY PRIMARY 4 fxgraphi_v2019.wrapper_models.chassis_id 1 10.00 Using where
1 SIMPLE afx_posts
NULL
eq_ref PRIMARY PRIMARY 8 fxgraphi_v2019.wrapper_featured_colorways.designId 1 100.00 Using index condition
1 SIMPLE z
NULL
ref meta_key meta_key 576 const 139 100.00 Using where
1 SIMPLE a
NULL
eq_ref PRIMARY,post_parent PRIMARY 8 fxgraphi_v2019.z.meta_value 1 10.00 Using index condition; Using where
1 SIMPLE wrapper_featured_colorway_colors
NULL
ALL
NULL
NULL
NULL
NULL
1431 10.00 Using where; Using join buffer (Block Nested Loop)
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T23:51:07.017",
"Id": "250814",
"Score": "2",
"Tags": [
"sql",
"wordpress"
],
"Title": "wordpress slow query shown in query monitor"
}
|
250814
|
<p>I was recently introduced to the wonders of TPL Dataflow and thought it would be a good exercise to create a wrapper class which wraps around an ASP.NET <code>WebSocket</code> object and processes the input and output streams using dataflow blocks, to make it easy to pipe inbound and outbound messages to data processing pipelines.</p>
<p>To keep things simple, this wrapper buffers received messages in full before passing them, which I believe is similar to how the JavaScript WebSocket API in the browser works. To prevent enormous messages from tanking the server, you can specify <code>maxReceivedMessageSize</code>.</p>
<pre class="lang-csharp prettyprint-override"><code>using System;
using System.Buffers;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;
namespace WebSocketSample
{
public sealed class DataflowWebSocketConnection : IDisposable
{
private readonly WebSocket _webSocket;
private readonly int _maxReceivedMessageSize;
private readonly CancellationToken _connectionAbortedToken;
private readonly CancellationTokenSource _sendingAbortedCts;
private readonly BufferBlock<(WebSocketMessageType Type, ReadOnlyMemory<byte> Data)> _receiveBlock;
private readonly ActionBlock<(WebSocketMessageType Type, ReadOnlyMemory<byte> Data)> _sendBlock;
private readonly WriteOnceBlock<(WebSocketCloseStatus Code, string? Reason)> _closeBlock;
private readonly Task _webSocketClosure;
public DataflowWebSocketConnection(
WebSocket webSocket,
int maxReceivedMessageSize,
CancellationToken connectionAbortedtoken)
{
_webSocket = webSocket;
_maxReceivedMessageSize = maxReceivedMessageSize;
_connectionAbortedToken = connectionAbortedtoken;
_sendingAbortedCts = CancellationTokenSource.CreateLinkedTokenSource(_connectionAbortedToken);
_receiveBlock = new BufferBlock<(WebSocketMessageType Type, ReadOnlyMemory<byte> Data)>(
new DataflowBlockOptions { CancellationToken = _connectionAbortedToken });
_sendBlock = new ActionBlock<(WebSocketMessageType Type, ReadOnlyMemory<byte> Data)>(
x => SendMessageAsync(x.Type, x.Data),
new ExecutionDataflowBlockOptions { CancellationToken = _sendingAbortedCts.Token });
_closeBlock = new WriteOnceBlock<(WebSocketCloseStatus Code, string? Reason)>(
cloningFunction: null,
new DataflowBlockOptions { CancellationToken = _connectionAbortedToken });
_webSocketClosure = Task.WhenAll(ReceiveMessagesAsync(), SendMessagesAsync());
}
public ISourceBlock<(WebSocketMessageType Type, ReadOnlyMemory<byte> Data)> Input => _receiveBlock;
public ITargetBlock<(WebSocketMessageType Type, ReadOnlyMemory<byte> Data)> Output => _sendBlock;
public Task Closure => _webSocketClosure;
private async Task ReceiveMessagesAsync()
{
// NOTE: In practice, we use a rented buffer that starts off small but grows in size up until
// '_maxReceivedMessageSize', but this has been simplified for the sake of brevity.
using var receiveBufferOwner = MemoryPool<byte>.Shared.Rent(_maxReceivedMessageSize);
var receiveBuffer = receiveBufferOwner.Memory.Slice(0, _maxReceivedMessageSize);
try
{
while (_webSocket.State < WebSocketState.Closed)
{
var receiveResult = await _webSocket.ReceiveAsync(receiveBuffer, _connectionAbortedToken);
if (!receiveResult.EndOfMessage)
{
// We received a message that exceeded '_maxReceivedMessageSize' in size, so we should prepare
// to close the connection.
_ = _closeBlock.Post((WebSocketCloseStatus.MessageTooBig, null));
_receiveBlock.Complete();
_sendingAbortedCts.Cancel();
return;
}
if (_webSocket.State == WebSocketState.CloseReceived
&& receiveResult.MessageType == WebSocketMessageType.Close)
{
// The remote endpoint started the closing handshake, so we should prepare to complete the
// closing handshake by echoing the message.
_ = _closeBlock.Post((_webSocket.CloseStatus!.Value, _webSocket.CloseStatusDescription));
_receiveBlock.Complete();
_sendingAbortedCts.Cancel();
return;
}
if (_webSocket.State == WebSocketState.Open)
{
// If the WebSocket is still open, continue posting messages to '_receiveBlock' as usual.
// NOTE: In practice, we use pooled memory and work with 'IMemoryOwner<byte>', but this has
// been replaced with a simple array allocation for the sake of brevity.
var messageData = new byte[receiveResult.Count];
receiveBuffer.Slice(0, receiveResult.Count).CopyTo(messageData);
_ = _receiveBlock.Post((receiveResult.MessageType, messageData));
}
}
}
catch (Exception e)
{
_ = _closeBlock.Post((WebSocketCloseStatus.InternalServerError, null));
((IDataflowBlock)_receiveBlock).Fault(e);
_sendingAbortedCts.Cancel();
throw;
}
}
private async Task SendMessagesAsync()
{
try
{
await _sendBlock.Completion;
}
catch (Exception)
{
// Attempt to set a close message indicating that a server error occurred. If the exception caught is
// an 'OperationCanceledException' that was thrown due to '_sendingAbortedCts' being canceled, a
// different close message reflecting the actual reason for closure should have already been set, in
// which case the below operation will do nothing.
_ = _closeBlock.Post((WebSocketCloseStatus.InternalServerError, null));
throw;
}
finally
{
if (!_connectionAbortedToken.IsCancellationRequested)
{
// Attempt to close the connection gracefully.
var (code, reason) = await _closeBlock.ReceiveAsync(_connectionAbortedToken);
if (_webSocket.State == WebSocketState.Open)
{
await _webSocket.CloseAsync(code, reason, _connectionAbortedToken);
}
else if (_webSocket.State == WebSocketState.CloseReceived)
{
await _webSocket.CloseOutputAsync(code, reason, _connectionAbortedToken);
}
}
}
}
private async Task SendMessageAsync(WebSocketMessageType type, ReadOnlyMemory<byte> data)
{
if (_webSocket.State != WebSocketState.Open)
{
return;
}
await _webSocket.SendAsync(data, type, endOfMessage: true, _connectionAbortedToken);
}
public void Close(WebSocketCloseStatus code, string? reason)
{
if (_closeBlock.Completion.IsCompleted)
{
return;
}
_ = _closeBlock.Post((code, reason));
_sendBlock.Complete();
}
public void Dispose()
{
_sendingAbortedCts.Dispose();
}
}
}
</code></pre>
<p>Sample usage:</p>
<pre class="lang-csharp prettyprint-override"><code>// Inside Startup.cs
app.Run(async context =>
{
if (!context.WebSockets.IsWebSocketRequest)
{
return;
}
var webSocket = await context.WebSockets.AcceptWebSocketAsync();
using var connection = new DataflowWebSocketConnection(
webSocket,
maxReceivedMessageSize: 8 * 1024,
context.RequestAborted);
var utf8Encoding = new UTF8Encoding(false, true);
// Echo whatever the client sends in reverse.
var echoBlock = new TransformBlock<
(WebSocketMessageType Type, ReadOnlyMemory<byte> Data),
(WebSocketMessageType Type, ReadOnlyMemory<byte> Data)>(
message =>
{
if (message.Type == WebSocketMessageType.Text)
{
message.Data = utf8Encoding.GetBytes(
new string(utf8Encoding.GetString(message.Data.Span).Reverse().ToArray()));
}
return message;
},
new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = DataflowBlockOptions.Unbounded });
using var link1 = connection.Input.LinkTo(echoBlock, new DataflowLinkOptions { PropagateCompletion = true });
using var link2 = echoBlock.LinkTo(connection.Output, new DataflowLinkOptions { PropagateCompletion = true });
// Send a greeting message to the client.
_ = connection.Output.Post((WebSocketMessageType.Text, utf8Encoding.GetBytes("Greetings!")));
// Close the connection after 20 seconds.
var closeAfter20SecondsTask = Task.Factory.StartNew(async () =>
{
await Task.Delay(TimeSpan.FromSeconds(20));
connection.Close(WebSocketCloseStatus.NormalClosure, "Bye-bye!");
});
await connection.Closure;
await closeAfter20SecondsTask;
});
</code></pre>
<p>I have played around with this implementation a bit and it seems to do what it is supposed to, but because I'm not very experienced with TPL Dataflow I'd like to know if there are any problems or caveats with this design that I should be aware of, especially when it comes to thread safety.</p>
<p>If there are any general improvements to code clarity or the design of the class that I could make I would also love to hear.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T00:28:43.630",
"Id": "250815",
"Score": "2",
"Tags": [
"c#",
"asp.net-core",
"websocket",
"tpl-dataflow"
],
"Title": "Handle ASP.NET WebSocket connections using TPL Dataflow"
}
|
250815
|
<p>I made a program to find words in a word grid. It will find words that are horizontal, vertical, positive sloped and vertical sloped, all in both forwards and backwards.</p>
<p>Here is my code:</p>
<pre><code>with open('grid.txt', 'r') as f:
lst = [[a for a in l.strip() if a != ' ' and a!= '\n'] for l in f.readlines() if l] # Convert file to a nested list, with all whitespaces removed
lst2 = [a[::-1] for a in zip(*lst)] # Create another nested list that is the first nested list rotated 90 degrees clockwise
height = len(lst) # Height of grid
width = len(lst[0]) # Width of grid
while True:
word = input("Input your word: ") # Word to find
# Find horizontal word
for l in lst:
w = ''.join(l)
if word in w or word in w[::-1]:
print(w)
print('Horizontal!')
# Find vertical word
for l in lst2:
w = ''.join(l)
if word in w or word in w[::-1]:
print(w)
print('Vertical!')
# Find Negative slope
for i in range(width):
w = ''
for j in range(height):
try:
w += lst[j][i]
i += 1
except:
break
if word in w or word in w[::-1]:
print(w)
print('Negative Slope!')
for i in range(height):
w = ''
for j in range(width):
try:
w += lst[i][j]
i += 1
except:
break
if word in w or word in w[::-1]:
print(w)
print('Negative Slope!')
# Find positive slope
for i in range(height):
w = ''
for j in range(width):
try:
w += lst2[j][i]
i += 1
except:
break
if word in w or word in w[::-1]:
print(w)
print('Positive Slope!')
for i in range(width):
w = ''
for j in range(height):
try:
w += lst2[i][j]
i += 1
except:
break
if word in w or word in w[::-1]:
print(w)
print('Positive Slope!')
</code></pre>
<p>Here is my <code>grid.txt</code>:</p>
<pre><code>n x b z t a ê s e y m t w u e r r
y s j q l n o i l f k j c y h t a
q x n e z d l g v r x y x a p u a
b b k à a y e g q i h u x b q e u
m h z x r é q m x m e l t i b t q
i k i g c j c h w l w i ï t p u o
i s o w u w m a p z a b w g d e p
i p s g u y n n j i j f o f n w l
l i u l ô i e j b e o t s e b c j
y m f v f e v h f c p r d m y v n
f w h v d t z y i x t e e u v n e
e w x e h l x n q m s n p z e f b
e j l v r x ç t d b i a z v d h z
c i i n s s i b s t o q o d d k x
z o f c a w b j b l m w k f e i s
</code></pre>
<p>I feel like my code is unnecessarily long for a rather simple task.</p>
<p>Are there any ways to shorten and improve it?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T02:24:36.773",
"Id": "493449",
"Score": "0",
"body": "Seems not to work. If I enter `zxs` from the lower-right, it does not output anything."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T02:28:29.050",
"Id": "493450",
"Score": "1",
"body": "It's because of encoding. After copying and pasting your example file, I had to specify UTF-8 for your `open` call to get this thing to work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T02:34:51.670",
"Id": "493451",
"Score": "1",
"body": "The central slopes are printed twice, for example `nsn` from the top-left or `zil` from the bottom-left."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T18:33:44.543",
"Id": "493602",
"Score": "0",
"body": "Re. your most recent edit to describe `strip()` - technically this is an example of _answer invalidation_, because the feedback I gave is now partially incorrect given your new constraints. This is something that CodeReview tries to avoid, and as such - if we were to be strict - your most recent edit should be rolled back. Please keep this in mind for future questions: once you have answers, you generally shouldn't edit your question at least in substance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T23:56:03.843",
"Id": "493635",
"Score": "0",
"body": "@Reinderien Oh! I'm very sorry! I'll roll it back."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T05:51:58.797",
"Id": "493657",
"Score": "0",
"body": "@user229550 Consider accepting any answer :)\\"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T12:09:34.487",
"Id": "493682",
"Score": "0",
"body": "@AryanParekh I will as soon as I find one more way that improves my code and does not make it longer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T13:01:53.567",
"Id": "493690",
"Score": "0",
"body": "@user229550 I linked a site which implements a much shorter and faster way, you might want to check that out, or do you want me to add that in my review?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T13:28:52.847",
"Id": "493692",
"Score": "0",
"body": "@user229550 Are you only looking to copy-paste the new code? It's better if you try to understand and implement it, also don't assume that shorter code is always better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T14:51:16.310",
"Id": "493698",
"Score": "0",
"body": "@AryanParekh I am not looking to copy-paste the new code. If so I could easily google \"python word grid code\". Note that I said \"find one more way that *improves my code* and does not make it longer\". I am fully aware that \"shorter code is *not* always better\". Your `.split()` was a nice tip for me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T14:57:25.753",
"Id": "493699",
"Score": "0",
"body": "@user229550 This is a little controversial, you might feel like you are copying if you follow the link I cited, but please don't think so. If you fully understand the method then it's absolutely fine. If you think that way then learning from any source can be considered as copying :), so try to understand that method as it's much cleaner and shorter."
}
] |
[
{
"body": "<h2>Catch invalid input</h2>\n<p>When I was trying out your code, I entered <code>Cntrl + Z</code> which crashed the program. Using <a href=\"https://www.w3schools.com/python/python_try_except.asp#:%7E:text=The%20try%20block%20lets%20you,the%20try%2D%20and%20except%20blocks.\" rel=\"noreferrer\">Try and Except</a> can prevent this from happening</p>\n<pre class=\"lang-py prettyprint-override\"><code>try:\n word = input("Enter your word:")\nexcept Exception:\n print("Invalid input!")\n</code></pre>\n<ul>\n<li>Also, I'd keep a check of <code>len(word) == 0</code> since an empty input is dangerous too</li>\n</ul>\n<hr />\n<h1>Reading <code>grid.txt</code></h1>\n<pre class=\"lang-py prettyprint-override\"><code>with open('grid.txt', 'r') as f:\n lst = [[a for a in l.strip() if a != ' ' and a!= '\\n'] for l in f.readlines() if l] \n lst2 = [a[::-1] for a in zip(*lst)]\n</code></pre>\n<p>You can greatly simplify this part by using <code>list.split()</code></p>\n<pre class=\"lang-py prettyprint-override\"><code>with open('grid.txt', 'r') as f:\n lst = [line.split() for line in f.readlines()]\n lst2 = list( zip (*lst[::-1]) )\n</code></pre>\n<p>If you're worried about the <code>'\\n'</code> at the end, the new lists using this method will not have it.</p>\n<ul>\n<li>I'd suggest you keep the names of the lists as <code>horizontal</code> and <code>vertical</code> rather than <code>lst</code> and <code>lst2</code> which don't mean much</li>\n</ul>\n<h1>Split work into functions</h1>\n<p>You should separate tasks into functions so that there isn't one huge block of code that does everything. Moreover, splitting work into functions makes it easy to maintain your code. What if your main game loop could look like this</p>\n<pre class=\"lang-py prettyprint-override\"><code>def game_loop():\n while True:\n word = take_input()\n matches = find_matches(grid,word)\n\n if matches == None: print("No matches")\n else:\n for match in matches:\n print( "Match: " + match )\n\n if input("Do you want to play again? (y/n): ").lower() == 'n':\n break\n</code></pre>\n<h1>An alternate approach</h1>\n<p>The reason your code isn't as efficient as the method I will just show you is that you repeatedly reverse the lists and use a lot of loops. There is a much better and cleaner way in which you need to go through the whole grid only once.</p>\n<ul>\n<li>Read the <code>.txt</code> file into a list ( like we previously did for <code>lst</code>)</li>\n<li>Start by going through each element in the 2-D list</li>\n<li>If the element matches the first character of the entered word, check all 8 directions to complete the match</li>\n</ul>\n<p><a href=\"https://www.geeksforgeeks.org/search-a-word-in-a-2d-grid-of-characters/\" rel=\"noreferrer\"><strong>Implementaion</strong></a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T07:49:15.930",
"Id": "250827",
"ParentId": "250816",
"Score": "5"
}
},
{
"body": "<p>There's a few things you need to avoid:</p>\n<ul>\n<li><code>strip()</code> when you really just need <code>rstrip()</code></li>\n<li>Forcing a caller of your program to loop through input; you should have functions to make this more divisible</li>\n<li>Keeping a list of lists of characters. Just keep lists of strings.</li>\n<li>Reversing the word on the inside of every loop; this should only be done once</li>\n<li>Iterating blindly over a sequence until you hit <code>IndexError</code></li>\n<li><code>except:</code> (you should catch the specific exception)</li>\n</ul>\n<p>The following suggested implementation fixes your coordinate iteration so that you don't have to rely on exceptions.</p>\n<pre><code>def make_rot45(grid):\n m, n = len(grid[0]), len(grid)\n coords = (\n (\n (y + x, x) for x in range(max(0, -y), min(m, n-y))\n ) for y in range(1-m, n)\n )\n return [\n ''.join(grid[y][x] for y, x in coord_line)\n for coord_line in coords\n ]\n\n\ndef simple(word: str):\n with open('grid.txt', encoding='utf-8') as f:\n rot0 = tuple(\n line.replace(' ', '').rstrip('\\n')\n for line in f\n )\n\n rot90 = tuple(''.join(col[::-1]) for col in zip(*rot0))\n rot45 = make_rot45(rot0)\n rot135 = make_rot45(rot90)\n word_rev = word[::-1]\n\n for grid, message in (\n (rot0, 'Horizontal!'),\n (rot90, 'Vertical!'),\n (rot45, 'Negative Slope!'),\n (rot135, 'Positive Slope!'),\n ):\n try:\n line = next(line for line in grid if word in line or word_rev in line)\n print(line)\n print(message)\n except StopIteration:\n pass\n\n\nfor test_word in (\n 'def',\n 'ehk',\n 'gko',\n 'sqo',\n):\n print(f'Test word "{test_word}":')\n simple(test_word)\n print()\n</code></pre>\n<p>I ran this against the following file:</p>\n<pre><code>a b c\nd e f\ng h i\nj k l\nm n o\np q r\ns t u\n</code></pre>\n<p>and it produced correct results.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T16:56:38.387",
"Id": "493503",
"Score": "0",
"body": "Good points,+1, I missed them in my review. I wanted to clarify, is there any problem is using `list.split()` for reading the grid from the file?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T16:58:22.260",
"Id": "493504",
"Score": "0",
"body": "Yes, there's at least two issues: it's not `list.split()`, but `line.split()`; and you shouldn't `split()` at all - simply `replace`. There's no need for an intermediate list representation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T17:21:51.077",
"Id": "493506",
"Score": "0",
"body": "But doesn't `.replace()` return a string, compared to OP's implementation which uses a `2x2` list?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T17:24:50.377",
"Id": "493507",
"Score": "0",
"body": "It's not a 2x2 list; it's a two-deep nested list. And yes, it's different from the OP's implementation intentionally. There's no sense in storing lists of lists of characters if all you're doing is string membership tests."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T17:43:01.033",
"Id": "493596",
"Score": "0",
"body": "Thanks. But for some reason, when I remove the `try` `except` part of your code, I get an IndexError."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T18:26:43.440",
"Id": "493599",
"Score": "0",
"body": "Keep in mind that `original_ish` is basically your code, with a few modifications; and certainly won't work if you remove the exception handling. The alternate implementation in `simple`/`make_rot45` does not need to produce and catch `IndexError`s to function; that's what I was getting at."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T16:45:43.340",
"Id": "250837",
"ParentId": "250816",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "250827",
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T00:54:33.183",
"Id": "250816",
"Score": "4",
"Tags": [
"python",
"performance"
],
"Title": "Find words in a word grid"
}
|
250816
|
<p>I have a program which goes through your drive and does two things:</p>
<ol>
<li>For every file extension it creates a file "file of extension_name" and whenever it encounters a file with that extension, it writes the path of it to its appropriate file.</li>
<li>Once it finishes going through every file, it goes through every file created in step 1 and counts all of the files in it, and writes to a <em>new</em> file the number of files to that extension.</li>
</ol>
<p>NOTE: I do not follow any variable naming conventions, I exclusively use camelCase. If that is unsatisfactory, let me know...</p>
<p>NOTE: The runtime of the program depends upon how many files you have in your drive...</p>
<p>NOTE: Sorry I didn't really document the second half of my code that well...</p>
<p>NOTE: Most of the try-except blocks came from a bunch of errors I kept getting while trying to access certain files...</p>
<pre><code>import os
import time
def documentFile(path):
global numberOfFilesChecked
for r in range(len(path) - 1, -1, -1): # search from the back to the front of
# the file name for the period which marks the extension.
if path[r] == ".":
try:
fObject = open(f"file of {path[r + 1:]}.txt", "a+")
# we create a file named "file of extension", and we set it to append
# mode
numberOfFilesChecked += 1
fObject.write(path + "\n")
# we then write the name of the file being indexed to the file we just opened, then add a line break.
fObject.close()
if numberOfFilesChecked % 5000 == 0:
print(numberOfFilesChecked)
except FileNotFoundError:
pass
break
def loopThroughDir(path):
try:
for iterator in os.listdir(path):
if os.path.isdir(path + "\\" + iterator): # if the path is a folder
loopThroughDir(path + "\\" + iterator)
else: # if it's a regular file
if iterator[0:4] != "fileO":
documentFile(path + "\\" + iterator)
except PermissionError:
pass
if __name__ == '__main__':
documentationStrings = []
extension = None
cTime = (int(time.time()) / 3600)
os.makedirs(f"C:\\fileDocumentation\\{cTime}")
os.chdir(f"C:\\fileDocumentation\\{cTime}")
numberOfFilesChecked = 0
loopThroughDir("C:\\")
print(int(time.time())/3600 - int(cTime))
print(numberOfFilesChecked)
numberOfFileTypes = 0
listOfFilesInCTime = os.listdir(f"C:\\fileDocumentation\\{cTime}")
aFile = open("controlFile.txt", "a+")
for fileContainingExtensions in listOfFilesInCTime:
numberOfFileTypes += 1
extension = None
fileExtensionFile = open(f"C:\\fileDocumentation\\{cTime}\\" + fileContainingExtensions)
numberOfFilesCheckedInEachExtension = 0
for eachLine in fileExtensionFile:
for x in range(len(eachLine) - 1, -1, -1): # search from the back to the front of
# the file name for the period which marks the extension.
if eachLine[x] == ".":
extension = eachLine[x:]
# because there is a \n at the end of the line we remove it.
extension.strip("\n")
break
numberOfFilesCheckedInEachExtension += 1
extension.strip("\n")
documentationStrings.append([numberOfFilesCheckedInEachExtension, f"{numberOfFilesCheckedInEachExtension}"
f" is the number of {extension}'s in the "
f"file "
f"which is {(numberOfFilesCheckedInEachExtension / numberOfFilesChecked) * 100}% "
f"percent of the total {numberOfFilesChecked}.\n"])
documentationStrings.sort()
documentationStrings.reverse()
for i in documentationStrings:
aFile.write(i[1])
</code></pre>
|
[] |
[
{
"body": "<h2>PEP-8</h2>\n<p>Python introduced a coding convention almost 20 years ago, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">namely PEP-8</a>. Quoting certain section from the same:</p>\n<blockquote>\n<p>[...] The guidelines provided here are intended to improve the\nreadability of code and make it consistent across the wide spectrum of\nPython code. [...]</p>\n<p>[...]</p>\n<p>Some other good reasons to ignore a particular guideline:</p>\n<ol>\n<li>When applying the guideline would make the code less readable, even for someone who is used to reading code that follows this PEP.</li>\n<li>To be consistent with surrounding code that also breaks it (maybe for historic reasons) -- although this is also an opportunity to clean\nup someone else's mess (in true XP style).</li>\n<li>Because the code in question predates the introduction of the guideline and there is no other reason to be modifying that code.</li>\n<li>When the code needs to remain compatible with older versions of Python that don't support the feature recommended by the style guide.</li>\n</ol>\n</blockquote>\n<p>I do not think any of these 4 apply in your case, so it is better to follow convention for one-off scripts (and put it into habit). The most common ones being:</p>\n<ol>\n<li>variables and functions follow <code>lower_snake_case</code> naming</li>\n<li>constants follow <code>UPPER_SNAKE_CASE</code></li>\n<li>classes are <code>UpperCamelCase</code></li>\n</ol>\n<h2>Functions</h2>\n<p>You start off with declaring 2 functions, then everything else is a mess of code all put inside the <code>if __name__</code> clause. Split this further into functions.</p>\n<h2>os.path vs pathlib</h2>\n<p>Since you're using python 3.x, may I suggest looking into a more friendlier inbuilt module for path traversals, <a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"nofollow noreferrer\">called <code>pathlib</code></a>. The docs provide few examples on how to easily convert your current code utilizing <code>os.path</code> and friends with their equivalent <code>pathlib</code> calls.</p>\n<h2>File contexts</h2>\n<p>Python also has a context based file handling. You currently are opening the files explicitly, without ever calling a <code>.close()</code>. Prefer using the following syntax when operating with files:</p>\n<pre><code>with open("path/to/file", "mode") as fp:\n fp.write(something)\n # something_else = fp.read()\n</code></pre>\n<h2>Comments vs docstrings</h2>\n<p>Use docstrings instead of comments when describing what a function does. The spec can be found <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">on PEP-257</a>.</p>\n<hr />\n<p>PS: A lot of your code appears to be doing unnecessary work due to usage of string operations, instead of proper inbuilt methods. Few examples:</p>\n<ol>\n<li>iterating over path string character by character to get extension instead of using <a href=\"https://docs.python.org/3/library/os.path.html#os.path.splitext\" rel=\"nofollow noreferrer\"><code>os.path.splitext</code></a> (pathlib has similar functions)</li>\n<li>generating path yourself, instead of having a glob based iteration over directory tree</li>\n<li>stripping <code>\\n</code> from extension, but not really overwriting the variable itself (<code>extension.strip("\\n")</code>)</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T04:19:29.810",
"Id": "250820",
"ParentId": "250818",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "250820",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T02:05:35.590",
"Id": "250818",
"Score": "3",
"Tags": [
"python",
"file",
"windows"
],
"Title": "program that fully documents every file on drive"
}
|
250818
|
<p>I wrote this code in python and it works fine for me but I do know that the code is not optimised and a lot of refactoring needs to be done. So I need review on how this code can be improved. I started writing this when <a href="https://pypi.org/project/wget/" rel="noreferrer"><strong>WGET</strong></a> library was not working for me and I wanted a light weight script for my other projects. I am also thinking of replacing <strong>requests</strong> library with <strong>aiohttp</strong> .Being a beginner in this, I look forward for your reviews.</p>
<p>Thank You.</p>
<p><strong>Requirements</strong>:- <a href="https://pypi.org/project/tqdm/" rel="noreferrer">tqdm</a>, <a href="https://pypi.org/project/requests/" rel="noreferrer">requests</a></p>
<p><strong>Implementation:-</strong> <strong>downloader.py</strong></p>
<pre><code>import requests
import os
from uuid import uuid4
from urllib.parse import urlparse, unquote
import re
from datetime import datetime
from requests.exceptions import HTTPError, ReadTimeout,InvalidSchema
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
from tqdm import tqdm
class Rget:
def __init__(self, url, dest=os.getcwd(), filename=None, progress_bar=True, headers=None):
self.url = url
self.dest = self.check_if_dir_exist(dest)
self.filename = filename
self.progress_bar = progress_bar
# self.headers = self.fetch_headers(headers)
def check_if_dir_exist(self, dest):
"""
Function to check whether the directory exist.
If Directory is not present it creates one and returns the path.
"""
if not os.path.exists(dest):
os.makedirs(dest)
return dest
def detect_filename(self, url, response):
"""
Function to autodetect file name from url and content disposition
headers.
"""
if not self.filename == None:
self.filename = self.get_valid_filename(self.filename)
else:
if 'filename' in response.headers.get('Content-Disposition'):
filename = response.headers.get('Content-Disposition') \
.split('filename=')[1].split(';')[0].replace('"', '')
else:
filename = os.path.basename(urlparse(unquote(response.url))[2])
self.filename = self.get_valid_filename(filename)
def get_valid_filename(self, filename):
"""
Return the given string converted to a string that can be used for a clean
filename. Remove leading and trailing spaces; convert other spaces to
underscores; and remove anything that is not an alphanumeric, dash,
underscore, or dot.
https://github.com/django/django/blob/master/django/utils/text.py
"""
s = str(filename).strip()
separator = ' '
return re.sub(r'(?u)[^-\w.]', separator, s)
def fix_existing_filename(self, filename, dest):
"""
Function that checks whether the file is already downloaded(exists)
If already downloaded adds a prefix of current timestamp and returns
the filename along with proper extension
"""
name, ext = filename.rsplit('.', 1)
time = datetime.now().strftime('%m-%d-%Y_%I.%M.%S%p')
name = name+'_'+time
return name+'.'+ext
def requests_retry_session(self,
retries=3,
backoff_factor=0.3,
status_forcelist=(500, 502, 504),
session=None,
):
"""
A high level function that I certainly didnot write
and I don't remember where I copied it from so if somebody knows whose code
this is then inform me.
What it bascially does is it automatically retries the request be it
HEAD, POST, GET, DELETE for 3 times(defalut) can be changed.
"""
session = session or requests.Session()
retry = Retry(
total=retries,
read=retries,
connect=retries,
backoff_factor=backoff_factor,
status_forcelist=status_forcelist,
)
adapter = HTTPAdapter(max_retries=retry)
session.mount('http://', adapter)
session.mount('https://', adapter)
return session
def download(self):
"""
Function to download file into a temporary file and rename
it to user provided filename or autodetected filename.
"""
try:
with self.requests_retry_session().get(self.url, stream=True, timeout=3) as response:
response.raise_for_status()
self.detect_filename(self.url, response)
self.file_size = int(response.headers['Content-Length'].strip())
with open(os.path.join(self.dest, 'rget_'+str(uuid4())+'.tmp'), 'wb+') as temp:
with tqdm(
total = self.file_size,
initial=0,
unit='B',
desc=self.filename,
ascii=True,
unit_scale=True,
unit_divisor=1024,
) as progressBar:
for chunk in response.iter_content(chunk_size=8192):
temp.write(chunk)
progressBar.update(len(chunk))
if os.path.exists(os.path.join(self.dest, self.filename)):
self.filename = self.fix_existing_filename(self.filename, self.dest)
os.rename(temp.name, os.path.join(self.dest, self.filename))
return self.filename
#* A bit of Exception handling to showoff ;)
except ReadTimeout:
return('Maximum Retries reached, Check your internet connection and try again')
except:
return 'Please check the url and try again'
</code></pre>
<p><strong>Usage:-</strong></p>
<pre><code># importing Rget class from downloader.py
from downloader import Rget
url = 'https://drive.google.com/u/0/uc?id=18dn4ha9Lyb1MqjYEjtRAEA5uEKxjPkwD&export=download'
# Optional parameters like destination and fileName can also be provided
file = Rget(url = url)
# printing the fileName once the file gets downloaded
# since download funtion returns the filename
print(file.download())
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T06:08:41.280",
"Id": "493457",
"Score": "1",
"body": "any reason why headers are commented out?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T07:46:43.333",
"Id": "493460",
"Score": "1",
"body": "Actually I was thinking of adding support for custom user-agents and other optional headers. Once I get review on current code maybe I will implement this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T19:17:01.810",
"Id": "493520",
"Score": "0",
"body": "Why wasn't wget working for you?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T10:30:53.687",
"Id": "493549",
"Score": "0",
"body": "What if something goes wrong somewhere? Is raising an exception and exiting acceptable ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T17:17:18.757",
"Id": "493591",
"Score": "0",
"body": "@Mast I was getting some sort of error which I don't exactly remember since I wrote this code 5-6 months back. I recently found out about \"CodeReview\" on stackexchange so I posted my code here for reviewing."
}
] |
[
{
"body": "<p>First, a couple of style/linting things:</p>\n<ol>\n<li>You are importing HTTPError and InvalidSchema from requests.exceptions but are not using them.</li>\n<li>Be consistent about your indentation. 4 spaces is the recommended number by PEP8 and it's OK if you don't want to follow that, but try not to mix 2 and 4 space indentation in the same project, like you're doing inside <code>requests_retry_session()</code></li>\n<li>Try to use string formatting instead of concatenating with <code>+</code>. This saves you the trouble of manually converting values to <code>str</code> (like you do with the uuid in <code>download()</code>) and it's also easier to read. Take a look at f-strings if you're on Python 3.6+ (which you should): <a href=\"https://realpython.com/python-f-strings/\" rel=\"noreferrer\">https://realpython.com/python-f-strings/</a></li>\n<li>Do not compare to <code>None</code> with <code>==</code>. Using the <code>is</code> keyword is the more idiomatic way of doing it. The first line in <code>detect_filename()</code> can be rewritten as <code>if self.filename is not None</code>. See: <a href=\"https://stackoverflow.com/questions/14247373/python-none-comparison-should-i-use-is-or\">https://stackoverflow.com/questions/14247373/python-none-comparison-should-i-use-is-or</a></li>\n<li>As a general rule, commented code is something we don't need, so you we might as well delete it completely. If you ever need that line back you can always get it from your git history. Because you're using git, right? RIGHT??</li>\n</ol>\n<p>Minor, nitpicky things:</p>\n<ol>\n<li>The last bit of <code>download()</code> uses a bare except, which is usually a bad idea because it catches some exceptions you probably don't want to catch. See: <a href=\"https://stackoverflow.com/questions/54948548/what-is-wrong-with-using-a-bare-except\">https://stackoverflow.com/questions/54948548/what-is-wrong-with-using-a-bare-except</a></li>\n<li>Your docstring for <code>fix_existing_filename()</code> says it checks if the filename already exists, but it doesn't actually do that.</li>\n<li>In <code>download()</code>, you don't need to open the file as read-write if you don't intend to actually read from it. Setting your open mode to just <code>wb</code> makes it clearer for the reader that you only intend to write to that file.</li>\n<li>In <code>check_if_dir_exist</code> you don't need the <code>if</code> statement, because you can pass <code>exist_ok=True</code> to <code>os.makedirs</code> and that will automatically create the directory only if it doesn't exist. In fact, I would get rid of this method entirely because you can just do everything in one line.</li>\n<li>Instead of generating a temporary file name yourself, take a look at the <code>tempfile</code> module in the standard library. Not only does it solve the same problem you did with <code>uuid4</code>, but it's also a bit clearer for the reader that you are generating a temporary file. See: <a href=\"https://docs.python.org/3/library/tempfile.html#examples\" rel=\"noreferrer\">https://docs.python.org/3/library/tempfile.html#examples</a></li>\n<li><code>requests_retry_session()</code> takes a <code>session</code> argument to allow reusing an existing <code>requests.Session()</code>, but a) you never use that argument and b) it doesn't make much sense. As a reader, I would expect a function like this to create a new session every time. If reconfiguring an existing session is part of the scope of that function, then it should indicate that in the name somehow.</li>\n<li>Also about the sessions, it's a good practice to install a hook on it so that it automatically calls <code>raise_for_status()</code> after every request. That way you don't have to remember to do that manually after every invocation. The syntax may look a bit weird but it's definitely worth it: <a href=\"https://stackoverflow.com/questions/45470226/requests-always-call-raise-for-status\">https://stackoverflow.com/questions/45470226/requests-always-call-raise-for-status</a></li>\n<li>Usage of <code>detect_filename()</code> is a bit weird. I would expect a method like that to return the filename instead of updating the <code>filename</code> attribute and not giving anything back.</li>\n</ol>\n<p>Bigger stuff:</p>\n<ol>\n<li>Avoid making calls in function defaults, like you do in <code>__init__</code>. The call is only performed once at method definition time and stored there forever. While, in this case, your <code>cwd</code> is always the same because you're not changing your current directory anywhere else, it's an antipattern to do things like this in Python. It looks weird and you also may get unexpected results if you ever add a <code>chdir</code> somewhere, because the original result to <code>getcwd()</code> will still be the function default. Instead, you should change the <code>dest</code> to <code>None</code> in the method definition and then add an <code>if dest is None: dest = os.getcwd()</code> inside it.</li>\n<li>Take a look at the <code>pathlib</code> module in the standard library. It can help you simplify most of your file management operations involving <code>os</code> and <code>os.path</code> calls. It is also more robust because it's platform independent. See: <a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"noreferrer\">https://docs.python.org/3/library/pathlib.html</a></li>\n<li>Some of the methods in the class aren't actually related to the class at all. <code>get_valid_filename</code>, <code>fix_existing_filename</code> and <code>requests_retry_session</code> never use <code>self</code>, so it doesn't make a lot of sense for them to be inside the class. Instead you should extract those methods and make them functions. If you really want them to be in a class, use <code>@staticmethod</code> on them so that it's clear that they don't interact with the class or its attributes, but I would recommend the first option.</li>\n<li>It would be a good idea to store your <code>requests.Session</code> as an attribute, so that you don't have to recreate it every time you invoke <code>download()</code>. The whole point of having a session is to be able to reuse it to take advantage of it saving cookies and keeping connections open.</li>\n<li>In <code>download()</code>, you set <code>file_size</code> as a new attribute, but that doesn't make a lot of sense. Do you need that to be an attribute? Is it a property of your object? Will you ever need to use it outside the current method? If the answer to all of those are "no", then keep it as a local variable instead.</li>\n</ol>\n<p>Nice things:</p>\n<ol>\n<li>Good separation of your logic across multiple well-defined methods.</li>\n<li>Informative docstrings, people tend to skip those quite often.</li>\n<li>tqdm! It's an awesome library and you make the most of it by properly specifying things like units and scaling.</li>\n<li>Some exception handling is definitely better than nothing. Totally not a showoff, but something important to keep in mind :)</li>\n<li>Overall it's good code! Don't be discouraged by the number of comments here. You did submit it to this community, so I was nitpicky on purpose, but this code is better than most of what I read at work every day :)</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T11:59:50.850",
"Id": "493474",
"Score": "0",
"body": "Forget the old point #5 of the \"Minor things\" section about `os.makedirs(parents=True)`. That parameter doesn't exist, I got confused with `pathlib.Path.mkdir`. I edited my answer to remove that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T13:05:50.763",
"Id": "493482",
"Score": "0",
"body": "Thank you very much for reviewing my code and I learnt a lot today. I will take my time implementing and understanding each one of the points you mentioned. I started this with functional approach. I wanted to try OOP's and some mistakes are because of this reason as I don't have a good grasp of OOP's. I am also waiting for other's to review my code and yes I use **git**."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T13:08:36.077",
"Id": "493484",
"Score": "0",
"body": "Can you please recommend me some good and small git repo's from which I can learn about programming style."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T14:55:26.827",
"Id": "493491",
"Score": "0",
"body": "@Rohan the only one I can think of right now is one the projects I maintain, so I'm going to shamelessly plug it here: https://github.com/opensistemas-hub/osbrain/. Not a very big codebase, but definitely well maintained, and a lot of attention to detail has been put into it :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T15:15:46.737",
"Id": "493493",
"Score": "1",
"body": "Didn't know about session hooks, very nice!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T11:04:00.240",
"Id": "250828",
"ParentId": "250819",
"Score": "20"
}
}
] |
{
"AcceptedAnswerId": "250828",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T03:45:51.827",
"Id": "250819",
"Score": "15",
"Tags": [
"python",
"python-3.x"
],
"Title": "Downloader in Python"
}
|
250819
|
<p>Recently I became interested in implementing a FORTH language interpreter. That led me to read about memory models etc.
which led me to write this custom memory allocator in c++. It's very dumb as memory allocators go but it seems to be working as intended. I'd like you to confirm that it is and tell me if there is anything wrong
or I should be doing differently.</p>
<p>To explain the code:</p>
<p><code>Storage</code> is the "memory" itself. It consists of an array of MEMSIZE bytes and a bitset
of MEMSIZE length where each bit will be on if the corresponding byte of memory is allocated or not. I also implemented <code>operator<<</code> so I could dump out the bitmap for debugging purposes.</p>
<p><code>Allocator</code> is the allocator itself. It is a template struct which is specialized for each data type that can be constructed. I aimed to fulfill all the requirements for a std::c++ 17 allocator.</p>
<p><code>Cell</code> and <code>Flag</code> are the only valid data types that can be used in this program. <code>Cell</code> is a 64bit value which can be accessed as a 64bit signed integer or as an array of 8 bytes. It must be aligned to an 8 byte boundary. <code>Flag</code> is 1 byte long. Eventually it will be used to implement booleans but here it can be any value from 0 - 255. Both <code>Cell</code> and <code>Flag</code> have custom <code>new</code> and <code>delete</code> methods that use <code>Allocator</code>.</p>
<p><code>main()</code> contains some tests to see if everything works ok.</p>
<p>Here is the code. I also have some questions which I have asked at the end.</p>
<pre><code>#include <array>
#include <bitset>
#include <cstdint>
#include <iostream>
#include <memory>
#include <new>
constexpr std::size_t MEMSIZE = 80;
static struct Storage {
using Memory = std::array<std::uint8_t, MEMSIZE>;
Memory memory_{};
std::bitset<MEMSIZE> free_{};
friend std::ostream& operator<<(std::ostream&, const Storage&);
} storage;
std::ostream& operator<<(std::ostream& out, const Storage& storage) {
for (std::size_t i = 0; i < MEMSIZE; i++) {
out << (storage.free_[i] ? '*' : '_');
}
return out;
}
template<class T>
struct Allocator {
public:
using value_type = T;
Allocator() noexcept {
}
template<class U>
Allocator(const Allocator<U>&) noexcept {
}
T* allocate(std::size_t n) {
for (std::size_t i = 0; i < MEMSIZE; i += alignof(T)) {
bool fits = true;
if (storage.free_[i] == 0) {
for (std::size_t j = i; j < i + n; j++) {
if (storage.free_[j] == 1) {
fits = false;
break;
}
}
if (fits) {
for (std::size_t j = i; j < i + n; j++) {
storage.free_.set(j);
}
return reinterpret_cast<T*>(&storage.memory_[i]);
}
}
}
throw std::bad_alloc();
}
void deallocate(T* p, std::size_t n) {
auto start = std::distance(&storage.memory_[0],
reinterpret_cast<Storage::Memory::pointer>(p));
for (std::size_t i = start; i < start + n; i++) {
storage.free_.reset(i);
}
}
};
template <class T, class U>
constexpr bool operator== (const Allocator<T>& lhs, const Allocator<U>& rhs)
noexcept {
return true;
}
template <class T, class U>
constexpr bool operator!= (const Allocator<T>& lhs, const Allocator<U>& rhs)
noexcept {
return !operator==(lhs, rhs);
}
struct Cell;
static Allocator<Cell> cellAlloc;
struct Cell {
using size_type = std::int64_t;
constexpr static std::size_t CELLSIZE = sizeof(size_type);
explicit Cell() : Cell(0) {
}
Cell(size_type val) : val_{val} {
}
static void* operator new ( std::size_t n ) {
return std::allocator_traits<Allocator<Cell>>::allocate(cellAlloc, n);
}
static void* operator new[] ( std::size_t n ) {
return operator new(n - sizeof(Cell));
}
static void operator delete (void *ptr, std::size_t n = 1) {
std::allocator_traits<Allocator<Cell>>::deallocate(
cellAlloc, static_cast<Cell*>(ptr), n);
}
static void operator delete[] (void *ptr, std::size_t n) {
operator delete(ptr, n - sizeof(Cell));
}
union {
size_type val_;
std::uint8_t bytes_[CELLSIZE];
};
};
struct Flag;
static Allocator<Flag> flagAlloc;
struct Flag {
Flag(std::uint8_t val) : val_{val} {
}
static void* operator new ( std::size_t n ) {
return std::allocator_traits<Allocator<Flag>>::allocate(flagAlloc, n);
}
static void* operator new[] ( std::size_t n ) {
return operator new(n - sizeof(std::uint8_t));
}
static void operator delete (void *ptr, std::size_t n = 1) {
std::allocator_traits<Allocator<Flag>>::deallocate(
flagAlloc, static_cast<Flag*>(ptr), n);
}
static void operator delete[] (void *ptr, std::size_t n) {
operator delete(ptr, n - sizeof(std::uint8_t));
}
std::uint8_t val_;
};
int main() {
std::cout << "The size of Cell is " << sizeof(Cell) << '\n';
std::cout << "The size of Flag is " << sizeof(Flag) << '\n';
std::cout << "Allocating...\n";
Cell* cells[10];
for (auto i = 0; i < 10; i++) {
cells[i] = new Cell(i * 1000);
}
std::cout << storage << '\n';
for (auto i = 0; i < 10; i++) {
std::cout << cells[i]->val_ << ' ';
}
std::cout << '\n';
std::cout << "Allocate one more...\n";
try {
new Cell(10000);
} catch (std::bad_alloc&) {
std::cout << "No, out of memory.\n";
}
std::cout << "Deallocating...\n";
for (auto i = 0; i < 10; i++) {
delete cells[i];
}
std::cout << storage << '\n';
std::cout << "Reallocating...\n";
auto cellarray = new Cell[10]{1, 3, 5, 7, 9, 2, 4, 6, 8, 10};
std::cout << storage << '\n';
for (auto i = 0; i < 10; i++) {
std::cout << cellarray[i].val_ << ' ';
}
std::cout << '\n';
std::cout << "Deallocating...\n";
delete[] cellarray;
std::cout << storage << '\n';
std::cout << "Allocating Flag...\n";
auto flag = new Flag{255};
std::cout << storage << '\n';
std::cout << (int)flag->val_ << '\n';
std::cout << "Flag + Allocating Cell...\n";
auto cell = new Cell(99);
std::cout << storage << '\n';
std::cout << cell->val_ << '\n';
std::cout << "Deallocating Flag...\n";
delete flag;
std::cout << storage << '\n';
std::cout << "Another Cell...\n";
auto cell2 = new Cell(66);
std::cout << storage << '\n';
std::cout << cell2->val_ << ' ' << cell->val_ << '\n';
std::cout << "Deallocating...\n";
delete cell;
delete cell2;
std::cout << storage << '\n';
std::cout << "Enough space...\n";
Flag *flags[MEMSIZE];
for (std::size_t i = 0; i < MEMSIZE; i++) {
flags[i] = new Flag(0);
}
for (std::size_t i = 64; i < 71; i++) {
delete flags[i];
}
try {
new Cell(12345678);
} catch (std::bad_alloc&) {
std::cout << "No, not enough space.\n";
}
std::cout << storage << '\n';
std::cout << "Aligned...\n";
for (std::size_t i = 64; i < 71; i++) {
flags[i] = new Flag(0);
}
for (std::size_t i = 65; i < 73; i++) {
delete flags[i];
}
try {
new Cell(87654321);
} catch (std::bad_alloc&) {
std::cout << "No, misaligned.\n";
}
std::cout << storage << '\n';
}
</code></pre>
<ol>
<li>For <code>Storage</code> I suppose using a bitset like this will not be scalable for large amounts of memory. How big can memory get before it becomes worth my while to implement some other scheme instead?</li>
<li>Am I missing any required functionality from <code>Allocator</code>?</li>
<li>For <code>Allocator</code> I left the constructor and copy constructor empty because the struct has no data
members. If I used <code>=default</code> instead would that work? They are required to be marked <code>noexcept</code>.</li>
<li>Similarly for <code>operator==</code> and <code>!=</code>. All instances of <code>Allocator<T></code> will be equal because they have no data correct?</li>
<li>Must the specialized allocators for each type be static and defined outside the type itself? It seems a bit untidy to me.</li>
</ol>
<p>Your comments/critiques are most welcome.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T16:11:36.480",
"Id": "493495",
"Score": "0",
"body": "I wish I knew how a Forth interpreter may benefit from an allocator."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T05:17:29.217",
"Id": "493654",
"Score": "0",
"body": "@vnp Standard FORTH has words that allocate memory such as ALLOT."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T16:56:34.777",
"Id": "493715",
"Score": "0",
"body": "Yes I am aware. Just keep in mind that ALLOT is not a general purpose allocator, and is typically implemented as a proper Forth word. Yet again, I see no benefit to delegating its functionality to the lower level."
}
] |
[
{
"body": "<ol>\n<li>Looking at this, you have a single static with all the memory packed together and all bits to indicate 'free/available'. I don't see a way to improve the memory usage of these bits. If the MEMSIZE would be variable, you could consider other techniques, though in this case, the bitset looks the most efficient.</li>\n<li>Looking at <a href=\"https://en.cppreference.com/w/cpp/named_req/Allocator\" rel=\"nofollow noreferrer\">the allocator requirements</a>, I believe all required elements are available. You could still add type defs like <code>size_type</code>, <code>difference_type</code>, <code>propagate_on_container_move_assignment</code>, <code>is_always_equal</code> ... to improve some usage by <code>std::vector</code>. These are optional and the provided example on the page doesn't have them either.</li>\n<li><code>= default</code> is a very good choice. Normally, this default method becomes noexcept out of it's own. You could add it, though, if you than change the class so the default behavior no longer is noexcept, it makes the method deleted.</li>\n<li>You are correct, all instances of Allocator can be considered equal. (See the <code>is_always_equal</code> typedef I've mentioned before)</li>\n<li>As your allocators don't have state, you don't need a static variable for them. You could create them when needed. With some CRTP you could reduce the amount of code needed in the classes using it.</li>\n</ol>\n<p>Some other random remarks:</p>\n<ul>\n<li>Storage::operator<< could use a ranged based for loop</li>\n<li>Your allocate function could be optimized, as you don't have to check every combination. (aka: If you encounter 5 free elements and you need to allocate 10, you can jump to after that first used element</li>\n<li>You could replace some of the for-loops with <code>std::all_of</code>/<code>std::none_of</code> (or if you implement the previous <code>std::find</code>)</li>\n<li>You don't have protection for out-of bounds checking in the inner loop. (If you are at index 76 and need to allocate 10 elements)</li>\n<li>Why would you decrement n in the new operator for an array.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T05:07:44.437",
"Id": "493651",
"Score": "0",
"body": "Re 1: The overhead of the bitmap is 1/8 of the size of memory. Eventually linearly searching that bitmap would be too costly but for small sizes it is ok. I was wondering at what size does it make sense to switch but never mind; I will cross that bridge when I come to it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T05:09:55.497",
"Id": "493652",
"Score": "0",
"body": "Re using std algorithms instead of for loops in various places. Unfortunately std::bitset does not have begin() and end() so I can't do that. Or maybe I could switch to std::vector<bool> but I have read that is not recommended. I don't know why though. What do you think?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T05:15:23.777",
"Id": "493653",
"Score": "0",
"body": "Re: Why would you decrement n in the new operator for an array. I was surprised to find that if e.g. you try to allocate 10 cells, instead of allocating 10 * 8 = 80 bytes, it allocates 88. I think it is because the STL allocator stuff is designed to work with containers which must include an extra value to signify end() in iteration. My data types aren't std containers and don't implement iterators."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T05:23:27.843",
"Id": "493655",
"Score": "1",
"body": "Re: bounds-checking. Good catch! I have implemented this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T10:41:32.800",
"Id": "493670",
"Score": "0",
"body": "1. You could add some extra data structure to remember where every free block starts. Could help indeed for performance, though it doesn't change memory of how you know what is empty."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T10:42:40.210",
"Id": "493671",
"Score": "0",
"body": "What you could do instead is a map from first free index to the number of free blocks. Though it raises complexity and could have a larger memory impact if memory is scattered"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T10:46:19.817",
"Id": "493672",
"Score": "0",
"body": "2. Depends, either way, I think that extracting to an algorithm makes sense. Even if you write your own all_of for bitset"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T10:48:01.707",
"Id": "493673",
"Score": "0",
"body": "3. Is this also the case for production builds, or is this only in devel builds where if uses it for more bookkeeping?"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T07:37:09.203",
"Id": "250826",
"ParentId": "250822",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "250826",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T06:07:48.827",
"Id": "250822",
"Score": "2",
"Tags": [
"c++",
"memory-management",
"c++17"
],
"Title": "A custom memory allocator in c++"
}
|
250822
|
<p>This all started when I wanted to make a simple program that takes in a c or c++ file and outputs all the comments found. After doing that I thought why not expand the program to other programming languages which was mostly easy except for rust as it allows nested c style comments. However after completing that and adding support for directories I managed to finish the program</p>
<p><code>comments.c</code></p>
<pre><code>#include <windows.h>
#include <stdbool.h>
#include "argva.c"
HANDLE stdout = NULL;
HANDLE stderr = NULL;
__declspec(noreturn) static void error_messagea(size_t count, char const **messages)
{
for (size_t i = 0; i < count; ++i) {
char const *message = messages[i];
WriteFile(stderr, message, lstrlenA(message), NULL, NULL);
}
ExitProcess(GetLastError());
}
#define error_messagea(...) error_messagea(sizeof((char const*[]){__VA_ARGS__}) / sizeof(char const *), (char const*[]){__VA_ARGS__})
#define WriteFile(filepath, ...) if(!WriteFile(__VA_ARGS__)) { error_messagea("Error could not write to ", filepath); }
typedef enum comment_display
{
NO_COMMENT_DISPLAY = 0x0,
C_COMMENT_DISPLAY = 0x1,
CC_COMMENT_DISPLAY = C_COMMENT_DISPLAY << 1,
ASM_COMMENT_DISPLAY = CC_COMMENT_DISPLAY << 1,
PYTHON_COMMENT_DISPLAY = ASM_COMMENT_DISPLAY << 1,
RUST_COMMENT_DISPLAY = PYTHON_COMMENT_DISPLAY << 1,
AUTO_COMMENT_DISPLAY = RUST_COMMENT_DISPLAY << 1,
C_AND_CC_COMMENT_DISPLAY = C_COMMENT_DISPLAY | CC_COMMENT_DISPLAY,
ALL_COMMENT_DISPLAY = C_COMMENT_DISPLAY | CC_COMMENT_DISPLAY | ASM_COMMENT_DISPLAY
} comment_display;
typedef struct comment_count
{
/* c comment count */
size_t c_comment_count;
/* c++ comment count */
size_t cc_comment_count;
/* asm comment count */
size_t asm_comment_count;
/* python comment count */
size_t python_comment_count;
/* rust comment count */
size_t rust_comment_count;
} comment_count;
static void output_number(size_t number)
{
/* log10(2^64) is around 20 meaning this should be able to hold all numbers inputed */
char digits[20] = { '0' };
/* get the reversed digets of the number */
int i = number == 0 ? 1 : 0; /* check if number is zero */
for (; number != 0; ++i) {
digits[i] = (number % 10) + '0';
number /= 10;
}
/* reverse the reversed digets of the number */
for (int j = 0; j < i - 1; ++j) {
char temp_digit = digits[j];
digits[j] = digits[i - 1 - j];
digits[i - 1 - j] = temp_digit;
}
/* print the reversed number */
WriteFile("stdout", stdout, digits, i, NULL, NULL);
}
static char const *is_continuing_backslash(char const *str)
{
/* NOTE: the loop is needed because cotinuing backslashs can nested like \\\\\ */
if (*str != '\\') return NULL;
while (*str != '\0') {
switch (*str) {
case '\r':
break;
case '\n':
return str + 1;
case '\\':
break;
default:
return NULL;
}
++str;
}
return NULL;
}
static comment_display get_comment_mode(char const *str)
{
char const *file_extension_pos = str;
/* find location of the file extension in the string */
{
char const *temp_pos = NULL;
while (*file_extension_pos != '\0') {
if (*file_extension_pos == '.') {
temp_pos = file_extension_pos;
}
++file_extension_pos;
}
if (temp_pos == NULL) {
return C_AND_CC_COMMENT_DISPLAY;
}
file_extension_pos = temp_pos;
}
/* file extensions of languages the use c/c++ style comments */
static char const *const cc_file_extensions[] = {
".c",
".cpp",
".h",
".hpp",
".cc",
".hh",
".java",
".cs",
".cu",
".cuh",
".go"
".hxx",
".cxx",
".c++",
".h++",
};
/* check if the file extension is of a programming language that uses c/c++ style comments */
for (size_t i = 0; i < (sizeof(cc_file_extensions) / sizeof(char const *const)); ++i) {
if (!lstrcmpiA(file_extension_pos, cc_file_extensions[i])) {
return C_AND_CC_COMMENT_DISPLAY;
}
}
if (!lstrcmpiA(file_extension_pos, ".asm") || !lstrcmpiA(file_extension_pos, ".s")) {
return ASM_COMMENT_DISPLAY;
}
else if (!lstrcmpiA(file_extension_pos, ".py")) {
return PYTHON_COMMENT_DISPLAY;
}
else if (!lstrcmpiA(file_extension_pos, ".rs")) {
return RUST_COMMENT_DISPLAY;
}
else {
return NO_COMMENT_DISPLAY;
}
}
/* NOTE: this function requires a null terminated string */
static comment_count read_comments(char const *str, bool show_lines, comment_display comment_mode)
{
/* check if can even display comments */
if (comment_mode == NO_COMMENT_DISPLAY) {
return (comment_count) { 0 };
}
comment_count result = { 0 };
/* keep reading the next char until we reach a null terminator*/
size_t bytes_since_newline = 1;
size_t newline_count = 1;
while (*str != '\0') {
switch (*str) {
/* handle "" and '' */
case '"':
case '\'': {
/* we need to read the current char to know what type of quote we are using
* once we have already read the current char so we need to go to the next one
*/
char quote_type = *str++;
/* check for python doc string */
if (str[0] == quote_type && str[1] == quote_type) {
++result.python_comment_count;
if ((comment_mode & PYTHON_COMMENT_DISPLAY)) {
/* add space before comment*/
do {
WriteFile("stdout", stdout, " ", 1, NULL, NULL);
} while (bytes_since_newline-- != 0);
++bytes_since_newline;
str += 2;
while (*str != '\0') {
if (str[0] == quote_type && str[1] == quote_type && str[2] == quote_type) {
if (show_lines) {
WriteFile("stdout", stdout, " ", 1, NULL, NULL);
output_number(newline_count);
}
str += 2;
if (str[1] == '\n' || (str[1] == '\r' && str[2] == '\n')) {
str += str[0] == '\n' ? 1 : 2;
++newline_count;
}
break;
}
WriteFile("stdout", stdout, str, 1, NULL, NULL);
++str;
while (str[0] == '\n' || (str[0] == '\r' && str[1] == '\n')) {
if (show_lines) {
/* output a number before the end of the line */
WriteFile("stdout", stdout, " ", 1, NULL, NULL);
output_number(newline_count);
}
WriteFile("stdout", stdout, "\r\n", 2, NULL, NULL);
str += str[0] == '\n' ? 1 : 2;
++newline_count;
}
}
WriteFile("stdout", stdout, "\r\n", 2, NULL, NULL);
}
break;
}
while (*str != '\0' && *str != quote_type) {
/* just skip escape codes as the could containe " or ' */
if (*str == '\\') {
++str;
}
if (*str == '\n') {
++newline_count;
}
++str;
}
break;
}
case '/':
++str;
switch (*str) {
case '/':
++result.cc_comment_count;
++result.rust_comment_count;
if ((comment_mode & RUST_COMMENT_DISPLAY) || (comment_mode & CC_COMMENT_DISPLAY)) {
/* add space before comment*/
do {
WriteFile("stdout", stdout, " ", 1, NULL, NULL);
} while (bytes_since_newline-- != 0);
++bytes_since_newline;
if (RUST_COMMENT_DISPLAY & comment_mode) {
if (str[1] == '!') {
str += 2;
}
else if (str[1] == '/') {
WriteFile("stdout", stdout, " ", 1, NULL, NULL);
str += str[2] == '!' ? 3 : 2;
}
else {
++str;
}
}
else {
++str;
}
while (*str != '\0') {
/* stop when we reach the end of the line */
if (str[0] == '\n' || (str[0] == '\r' && str[1] == '\n')) {
if (show_lines) {
WriteFile("stdout", stdout, " ", 1, NULL, NULL);
output_number(newline_count);
}
/* NOTE: when we increment the string before going to the end of loop
* we must add to the string pointer by 1 less since we already
* increment the string pointer at the end of the loop
*/
str += str[0] == '\n' ? 0 : 1;
++newline_count;
break;
}
/* if we detect \\ treat the next line as a comment */
char const *continuing_backslash_pos;
if ((continuing_backslash_pos = is_continuing_backslash(str)) != NULL) {
/* since we are moving to a newline output the current line number */
if (show_lines) {
WriteFile("stdout", stdout, " ", 1, NULL, NULL);
output_number(newline_count);
}
WriteFile("stdout", stdout, "\r\n", 2, NULL, NULL);
str = continuing_backslash_pos;
++newline_count;
}
WriteFile("stdout", stdout, str, 1, NULL, NULL);
++str;
}
WriteFile("stdout", stdout, "\r\n", 2, NULL, NULL);
}
break;
case '*':
if (comment_mode & RUST_COMMENT_DISPLAY) {
++result.rust_comment_count;
/* add space before comment */
do {
WriteFile("stdout", stdout, " ", 1, NULL, NULL);
} while (bytes_since_newline-- != 0);
++bytes_since_newline;
size_t bracket_count = 1;
str += str[1] == '!' ? 2 : 1;
while (*str != '\0' && bracket_count != 0) {
while (str[0] == '/' && str[1] == '*') {
str += str[2] == '!' ? 4 : 3;
++bracket_count;
}
if (str[0] == '*' && str[1] == '/') {
if (show_lines) {
WriteFile("stdout", stdout, " ", 1, NULL, NULL);
output_number(newline_count);
}
++str;
if (str[1] == '\n' || (str[1] == '\r' && str[2] == '\n')) {
WriteFile("stdout", stdout, "\r\n", 2, NULL, NULL);
str += str[0] == '\n' ? 1 : 2;
++newline_count;
}
--bracket_count;
}
else {
if (str[0] == '\n' || (str[0] == '\r' && str[1] == '\n')) {
if (show_lines) {
/* output a number before the end of the line */
WriteFile("stdout", stdout, " ", 1, NULL, NULL);
output_number(newline_count);
}
WriteFile("stdout", stdout, "\r\n", 2, NULL, NULL);
str += str[0] == '\n' ? 0 : 1;
++newline_count;
}
else {
WriteFile("stdout", stdout, str, 1, NULL, NULL);
}
}
++str;
}
WriteFile("stdout", stdout, "\r\n", 2, NULL, NULL);
}
else if ((comment_mode & C_COMMENT_DISPLAY)) {
++result.c_comment_count;
/* add space before comment */
do {
WriteFile("stdout", stdout, " ", 1, NULL, NULL);
} while (bytes_since_newline-- != 0);
++bytes_since_newline;
while (*str != '\0') {
++str;
if (str[0] == '*' && str[1] == '/') {
if (show_lines) {
WriteFile("stdout", stdout, " ", 1, NULL, NULL);
output_number(newline_count);
}
++str;
if (str[1] == '\n' || (str[1] == '\r' && str[2] == '\n')) {
str += str[0] == '\n' ? 1 : 2;
++newline_count;
}
break;
}
if (str[0] == '\n' || (str[0] == '\r' && str[1] == '\n')) {
if (show_lines) {
/* output a number before the end of the line */
WriteFile("stdout", stdout, " ", 1, NULL, NULL);
output_number(newline_count);
}
WriteFile("stdout", stdout, "\r\n", 2, NULL, NULL);
str += str[0] == '\n' ? 0 : 1;
++newline_count;
}
else {
WriteFile("stdout", stdout, str, 1, NULL, NULL);
}
}
WriteFile("stdout", stdout, "\r\n", 2, NULL, NULL);
}
break;
}
break;
case '\n':
bytes_since_newline = 0;
++newline_count;
break;
case ';':
++result.asm_comment_count;
if ((comment_mode & ASM_COMMENT_DISPLAY)) {
/* add space before comment*/
do {
WriteFile("stdout", stdout, " ", 1, NULL, NULL);
} while (bytes_since_newline-- != 0);
++bytes_since_newline;
++str;
while (*str != '\0') {
if (str[0] == '\n' || (str[0] == '\r' && str[1] == '\n')) {
if (show_lines) {
WriteFile("stdout", stdout, " ", 1, NULL, NULL);
output_number(newline_count);
}
++newline_count;
break;
}
WriteFile("stdout", stdout, str, 1, NULL, NULL);
++str;
}
WriteFile("stdout", stdout, "\r\n", 2, NULL, NULL);
}
break;
case '#':
++result.python_comment_count;
if ((comment_mode & PYTHON_COMMENT_DISPLAY)) {
/* add space before comment*/
do {
WriteFile("stdout", stdout, " ", 1, NULL, NULL);
} while (bytes_since_newline-- != 0);
++bytes_since_newline;
++str;
while (*str != '\0') {
if (str[0] == '\n' || (str[0] == '\r' && str[1] == '\n')) {
if (show_lines) {
WriteFile("stdout", stdout, " ", 1, NULL, NULL);
output_number(newline_count);
}
str += str[0] == '\n' ? 0 : 1;
++newline_count;
break;
}
WriteFile("stdout", stdout, str, 1, NULL, NULL);
++str;
}
WriteFile("stdout", stdout, "\r\n", 2, NULL, NULL);
}
break;
}
++str;
bytes_since_newline += *str == '\t' ? 4 : 1; /* handle tabs */
}
return result;
}
static void read_file_comments(char const *filename, comment_display comment_mode, bool show_line_number, bool display_comment_count)
{
if (comment_mode & AUTO_COMMENT_DISPLAY) {
comment_mode = get_comment_mode(filename);
}
if (comment_mode & ~NO_COMMENT_DISPLAY) {
WriteFile("stdout", stdout, filename, lstrlenA(filename), NULL, NULL);
WriteFile("stdout", stdout, ": \r\n", 4, NULL, NULL);
}
else {
return;
}
HANDLE file_handle = CreateFileA(filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN | FILE_ATTRIBUTE_NORMAL, NULL);
if (file_handle == INVALID_HANDLE_VALUE) {
error_messagea("Error: could not open file \"", filename, "\"");
}
/* get the file size */
LARGE_INTEGER file_size;
if (GetFileSizeEx(file_handle, &file_size) == FALSE) {
error_messagea("Error: could not get the file size of \"", filename, "\\");
}
char *file_buffer = HeapAlloc(GetProcessHeap(), 0, file_size.QuadPart + 1);
file_buffer[file_size.QuadPart] = '\0'; /* add a null terminator */
/* read the file into the file buffer */
DWORD bytes_read = 0;
if (ReadFile(file_handle, file_buffer, file_size.LowPart, &bytes_read, NULL) == FALSE || bytes_read != file_size.QuadPart) {
error_messagea("Error: could not read ", filename);
}
/* process the file and read the comments */
{
comment_count count = read_comments(file_buffer, show_line_number, comment_mode);
if (display_comment_count) {
if (comment_mode & CC_COMMENT_DISPLAY) {
WriteFile("stdout", stdout, "c++ style comments: ", 20, NULL, NULL);
output_number(count.cc_comment_count);
WriteFile("stdout", stdout, "\r\n", 2, NULL, NULL);
}
if (comment_mode & C_COMMENT_DISPLAY) {
WriteFile("stdout", stdout, "c style comments: ", 18, NULL, NULL);
output_number(count.c_comment_count);
WriteFile("stdout", stdout, "\r\n", 2, NULL, NULL);
}
if (comment_mode & RUST_COMMENT_DISPLAY) {
WriteFile("stdout", stdout, "rust style comments: ", 21, NULL, NULL);
output_number(count.rust_comment_count);
WriteFile("stdout", stdout, "\r\n", 2, NULL, NULL);
}
if (comment_mode & ASM_COMMENT_DISPLAY) {
WriteFile("stdout", stdout, "asm style comments: ", 20, NULL, NULL);
output_number(count.asm_comment_count);
WriteFile("stdout", stdout, "\r\n", 2, NULL, NULL);
}
if (comment_mode & PYTHON_COMMENT_DISPLAY) {
WriteFile("stdout", stdout, "python style comments: ", 23, NULL, NULL);
output_number(count.python_comment_count);
WriteFile("stdout", stdout, "\r\n", 2, NULL, NULL);
}
}
}
}
typedef struct string
{
size_t size;
size_t capacity;
char *data;
} string_t;
string_t make_string(char const *string)
{
/* get the length of the string */
size_t string_length = lstrlenA(string);
string_t result = {
.size = string_length,
.capacity = string_length,
.data = HeapAlloc(GetProcessHeap(), 0, string_length + 1)
};
/* copy the string to result */
for (char *first = result.data; first != result.data + result.size; ) {
*first++ = *string++;
}
/* null terminator */
result.data[result.size] = '\0';
return result;
}
void string_cat(string_t *self, char const *string)
{
if (string[0] == '\0') return;
size_t string_length = lstrlenA(string);
self->size += string_length;
if (self->size > self->capacity) {
self->capacity = self->size * 2;
self->data = HeapReAlloc(GetProcessHeap(), 0, self->data, (self->capacity + 1));
}
lstrcatA(self->data, string);
}
void string_free(string_t self)
{
HeapFree(GetProcessHeap(), 0, self.data);
}
void read_comments_in_directory(char const *input_path, comment_display comment_mode, bool show_line_number, bool display_comment_count)
{
size_t stack_capacity = 1000;
size_t stack_size = 1;
string_t *stack_base = HeapAlloc(GetProcessHeap(), 0, sizeof(string_t) * stack_capacity);
string_t *stack_ptr = stack_base;
*stack_ptr++ = make_string(input_path);
while (stack_ptr != stack_base) {
string_t path = stack_ptr[-1];
string_t spec = make_string(path.data);
string_cat(&spec, "\\*");
--stack_ptr;
--stack_size;
WIN32_FIND_DATAA file_find_data;
HANDLE find_handle = FindFirstFileA(spec.data, &file_find_data);
if (find_handle == INVALID_HANDLE_VALUE) {
string_free(spec);
string_free(path);
HeapFree(GetProcessHeap(), 0, stack_base);
error_messagea("Error: FindFirstFileA failed");
}
do {
if (lstrcmpA(file_find_data.cFileName, ".") != 0 &&
lstrcmpA(file_find_data.cFileName, "..") != 0) {
if (file_find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
++stack_size;
if (stack_size > stack_capacity) {
stack_capacity = stack_size * 2;
stack_base = HeapReAlloc(GetProcessHeap(), 0, stack_base, sizeof(string_t) * stack_capacity);
stack_ptr = stack_base + stack_size - 1;
}
*stack_ptr++ = make_string(path.data);
string_cat(stack_ptr - 1, "\\");
string_cat(stack_ptr - 1, file_find_data.cFileName);
}
else {
string_t file_name = make_string(path.data);
string_cat(&file_name, "\\");
string_cat(&file_name, file_find_data.cFileName);
read_file_comments(file_name.data, comment_mode, show_line_number, display_comment_count);
string_free(file_name);
}
}
} while (FindNextFileA(find_handle, &file_find_data) != 0);
if (GetLastError() != ERROR_NO_MORE_FILES) {
FindClose(find_handle);
error_messagea("Error: FindNextFileA failed");
}
FindClose(find_handle);
string_free(spec);
string_free(path);
}
HeapFree(GetProcessHeap(), 0, stack_base);
}
void read_comments_in_directory_non_recursive(char const *input_path, comment_display comment_mode, bool show_line_number, bool display_comment_count)
{
string_t spec = make_string(input_path);
string_cat(&spec, "\\*");
WIN32_FIND_DATAA file_find_data;
HANDLE find_handle = FindFirstFileA(spec.data, &file_find_data);
if (find_handle == INVALID_HANDLE_VALUE) {
string_free(spec);
error_messagea("Error: FindFirstFileA failed");
}
string_t file_name = make_string(input_path);
string_cat(&file_name, "\\");
do {
if (lstrcmpA(file_find_data.cFileName, ".") != 0 &&
lstrcmpA(file_find_data.cFileName, "..") != 0) {
if (file_find_data.dwFileAttributes & ~FILE_ATTRIBUTE_DIRECTORY) {
string_cat(&file_name, file_find_data.cFileName);
read_file_comments(file_name.data, comment_mode, show_line_number, display_comment_count);
file_name.data[spec.size - 1] = '\0';
file_name.size = spec.size - 1;
}
}
} while (FindNextFileA(find_handle, &file_find_data) != 0);
FindClose(find_handle);
string_free(spec);
string_free(file_name);
}
void __cdecl mainCRTStartup(void)
{
static char const *help_message = "Usage: comments [--help] [-r false or true or --recursive= false or true] [-l or --line] [-c or --count] [-nl or --no_line] [-e [mode] or --enable=[mode]] [-m [mode] or --mode=[mode]] [-d [mode] or --disable=[mode]] [--display_comment_count or -dcc] [--hide_comment_count -hcc] [file1 ...]\n\
Flags: \n\
--help: displays this message \n\
-r or --recursive=: using this with true enables recursive directory searching and using with false disables recursive directory search\n\
-l or --line(disabled by default): makes it so the program shows the line number of each comment\n\
-nl or --no_line: has the oppsite effect of -l\n\
-e [mode] or --enable=[mode]: enables the comment mode to [mode] for example -e asm enables asm comments\n\
-m [mode] or --mode=[mode]: sets the comment mode to [mode] for example -m asm only allows only asm comments\n\
-d [mode] or --disable=[mode]: disables the comment mode to [mode] for example -d asm disables asm comments\n\
[mode](the default mode auto): the different modes are \n\
c++ style comments //(cc, cxx, cpp), \n\
c style comments /**/ (c), \n\
python style comments (py), \n\
asm style comments ;(asm), \n\
c and c++ style comments /**/ //(c|c++), \n\
rust style comments which enables rust style comments /*/* comments can be nested */*/ // /// //!(rs), \n\
auto which detects the comment style based on file extension(auto), \n\
and all which enables all the available comment styles(all) \n\
-dcc or --display_comment_count(enabled by defualt): displays the number of comments found \n\
-hcc or --hides_comment_count: hides the number of comments found \n\
";
stdout = GetStdHandle(STD_OUTPUT_HANDLE);
stderr = GetStdHandle(STD_ERROR_HANDLE);
/* get command line args */
int argc;
char **argv = CommandLineToArgvA(GetCommandLineA(), &argc) + 1;
--argc;
bool show_lines = false;
bool recursive_directory_search = false;
bool display_comment_count = true;
comment_display comment_mode = AUTO_COMMENT_DISPLAY;
DWORD file_type = -1;
/* this makes it easier to add flags */
#define FIND_ARG(op) \
if (!lstrcmpiA(argv[i], "cc") || !lstrcmpiA(argv[i], "cxx") \
|| !lstrcmpiA(argv[i], "cpp")) { \
comment_mode op CC_COMMENT_DISPLAY; \
} else if (!lstrcmpiA(argv[i], "c")) { \
comment_mode op C_COMMENT_DISPLAY; \
} else if (!lstrcmpiA(argv[i], "asm")) { \
comment_mode op ASM_COMMENT_DISPLAY; \
} else if (!lstrcmpiA(argv[i], "c|c++")) { \
comment_mode op C_AND_CC_COMMENT_DISPLAY; \
} else if (!lstrcmpiA(argv[i], "auto")) { \
comment_mode op AUTO_COMMENT_DISPLAY; \
} else if(!lstrcmpiA(argv[i], "py")) { \
comment_mode op PYTHON_COMMENT_DISPLAY; \
} else if(!lstrcmpiA(argv[i], "rs")) { \
comment_mode op (RUST_COMMENT_DISPLAY); \
} else if (!lstrcmpiA(argv[i], "all")) { \
comment_mode op ALL_COMMENT_DISPLAY; \
} else { \
error_messagea("Error: invalid arguments\n", help_message); \
} \
/* parse command line args */
for (int i = 0; i < argc; ++i) {
if (!lstrcmpA(argv[i], "--line") || !lstrcmpA(argv[i], "-l")) {
show_lines = true;
}
else if (i + 1 < argc && !lstrcmpA(argv[i], "-r")) {
++i;
if (!lstrcmpiA(argv[i], "true")) {
recursive_directory_search = true;
}
else if (!lstrcmpiA(argv[i], "false")) {
recursive_directory_search = false;
}
else {
error_messagea("Error: invalid arguments\n", help_message);
}
}
else if (argv[i][0] == '-' && argv[i][1] == '-'
&& argv[i][2] == 'r' && argv[i][3] == 'e'
&& argv[i][4] == 'c' && argv[i][5] == 'u'
&& argv[i][6] == 'r' && argv[i][7] == 's'
&& argv[i][8] == 'i' && argv[i][9] == 'v'
&& argv[i][10] == 'e' && argv[i][11] == '=') {
argv[i] += 12;
if (!lstrcmpiA(argv[i], "true")) {
recursive_directory_search = true;
}
else if (!lstrcmpiA(argv[i], "false")) {
recursive_directory_search = false;
}
else {
error_messagea("Error: invalid arguments\n", help_message);
}
}
else if (!lstrcmpA(argv[i], "--no_line") || !lstrcmpA(argv[i], "-nl")) {
show_lines = false;
}
else if (!lstrcmpA(argv[i], "--display_comment_count") || !lstrcmpA(argv[i], "-dcc")) {
display_comment_count = true;
}
else if (!lstrcmpA(argv[i], "--hide_comment_count") || !lstrcmpA(argv[i], "-hcc")) {
display_comment_count = false;
}
else if (argv[i][0] == '-' && argv[i][1] == '-'
&& argv[i][2] == 'm' && argv[i][3] == 'o'
&& argv[i][4] == 'd' && argv[i][5] == 'e'
&& argv[i][6] == '=') {
argv[i] += 7;
FIND_ARG(= );
}
else if (i + 1 < argc && !lstrcmpA(argv[i], "-m")) {
++i;
FIND_ARG(= );
}
else if (argv[i][0] == '-' && argv[i][1] == '-'
&& argv[i][2] == 'm' && argv[i][3] == 'o'
&& argv[i][4] == 'd' && argv[i][5] == 'e'
&& argv[i][6] == '=') {
argv[i] += 7;
FIND_ARG(= );
}
else if (i + 1 < argc && !lstrcmpA(argv[i], "-e")) {
++i;
FIND_ARG(|= );
}
else if (argv[i][0] == '-' && argv[i][1] == '-'
&& argv[i][2] == 'd' && argv[i][3] == 'i'
&& argv[i][4] == 's' && argv[i][5] == 'a'
&& argv[i][6] == 'b' && argv[i][7] == 'l'
&& argv[i][8] == 'e' && argv[i][9] == '=') {
argv[i] += 10;
FIND_ARG(&= ~);
}
else if (i + 1 < argc && !lstrcmpA(argv[i], "-d")) {
++i;
FIND_ARG(&= ~);
}
else if (!lstrcmpiA(argv[i], "--help")) {
WriteFile("stdout", stdout, help_message, lstrlenA(help_message), NULL, NULL);
}
else if (((file_type = GetFileAttributesA(argv[i])) & ~FILE_ATTRIBUTE_DIRECTORY) && file_type != INVALID_FILE_ATTRIBUTES) {
read_file_comments(argv[i], comment_mode, show_lines, display_comment_count);
}
else if (file_type != INVALID_FILE_ATTRIBUTES && (file_type & FILE_ATTRIBUTE_DIRECTORY)) {
if (recursive_directory_search) {
read_comments_in_directory(argv[i], comment_mode, show_lines, display_comment_count);
}
else {
read_comments_in_directory_non_recursive(argv[i], comment_mode, show_lines, display_comment_count);
}
}
else {
error_messagea("Error: invalid arguments\n", help_message);
}
}
/* cleanup */
LocalFree(argv - 1);
ExitProcess(0);
}
</code></pre>
<p><code>argva.c</code></p>
<pre><code>/* from https://stackoverflow.com/a/42048224 also how hard is it to provide an ansi version of CommandLineToArgW windows? */
/*************************************************************************
* CommandLineToArgvA [SHELL32.@]
*
* MODIFIED FROM https://www.winehq.org/ project
* We must interpret the quotes in the command line to rebuild the argv
* array correctly:
* - arguments are separated by spaces or tabs
* - quotes serve as optional argument delimiters
* '"a b"' -> 'a b'
* - escaped quotes must be converted back to '"'
* '\"' -> '"'
* - consecutive backslashes preceding a quote see their number halved with
* the remainder escaping the quote:
* 2n backslashes + quote -> n backslashes + quote as an argument delimiter
* 2n+1 backslashes + quote -> n backslashes + literal quote
* - backslashes that are not followed by a quote are copied literally:
* 'a\b' -> 'a\b'
* 'a\\b' -> 'a\\b'
* - in quoted strings, consecutive quotes see their number divided by three
* with the remainder modulo 3 deciding whether to close the string or not.
* Note that the opening quote must be counted in the consecutive quotes,
* that's the (1+) below:
* (1+) 3n quotes -> n quotes
* (1+) 3n+1 quotes -> n quotes plus closes the quoted string
* (1+) 3n+2 quotes -> n+1 quotes plus closes the quoted string
* - in unquoted strings, the first quote opens the quoted string and the
* remaining consecutive quotes follow the above rule.
*/
LPSTR *WINAPI CommandLineToArgvA(LPSTR lpCmdline, int *numargs)
{
DWORD argc;
LPSTR *argv;
LPSTR s;
LPSTR d;
LPSTR cmdline;
int qcount, bcount;
if (!numargs || *lpCmdline == 0)
{
SetLastError(ERROR_INVALID_PARAMETER);
return NULL;
}
/* --- First count the arguments */
argc = 1;
s = lpCmdline;
/* The first argument, the executable path, follows special rules */
if (*s == '"')
{
/* The executable path ends at the next quote, no matter what */
s++;
while (*s)
if (*s++ == '"')
break;
}
else
{
/* The executable path ends at the next space, no matter what */
while (*s && *s != ' ' && *s != '\t')
s++;
}
/* skip to the first argument, if any */
while (*s == ' ' || *s == '\t')
s++;
if (*s)
argc++;
/* Analyze the remaining arguments */
qcount = bcount = 0;
while (*s)
{
if ((*s == ' ' || *s == '\t') && qcount == 0)
{
/* skip to the next argument and count it if any */
while (*s == ' ' || *s == '\t')
s++;
if (*s)
argc++;
bcount = 0;
}
else if (*s == '\\')
{
/* '\', count them */
bcount++;
s++;
}
else if (*s == '"')
{
/* '"' */
if ((bcount & 1) == 0)
qcount++; /* unescaped '"' */
s++;
bcount = 0;
/* consecutive quotes, see comment in copying code below */
while (*s == '"')
{
qcount++;
s++;
}
qcount = qcount % 3;
if (qcount == 2)
qcount = 0;
}
else
{
/* a regular character */
bcount = 0;
s++;
}
}
/* Allocate in a single lump, the string array, and the strings that go
* with it. This way the caller can make a single LocalFree() call to free
* both, as per MSDN.
*/
argv = LocalAlloc(LMEM_FIXED, (argc + (size_t)1) * sizeof(LPSTR) + (strlen(lpCmdline) + 1) * sizeof(char));
if (!argv)
return NULL;
cmdline = (LPSTR)(argv + argc + 1);
lstrcpyA(cmdline, lpCmdline);
/* --- Then split and copy the arguments */
argv[0] = d = cmdline;
argc = 1;
/* The first argument, the executable path, follows special rules */
if (*d == '"')
{
/* The executable path ends at the next quote, no matter what */
s = d + 1;
while (*s)
{
if (*s == '"')
{
s++;
break;
}
*d++ = *s++;
}
}
else
{
/* The executable path ends at the next space, no matter what */
while (*d && *d != ' ' && *d != '\t')
d++;
s = d;
if (*s)
s++;
}
/* close the executable path */
*d++ = 0;
/* skip to the first argument and initialize it if any */
while (*s == ' ' || *s == '\t')
s++;
if (!*s)
{
/* There are no parameters so we are all done */
argv[argc] = NULL;
*numargs = argc;
return argv;
}
/* Split and copy the remaining arguments */
argv[argc++] = d;
qcount = bcount = 0;
while (*s)
{
if ((*s == ' ' || *s == '\t') && qcount == 0)
{
/* close the argument */
*d++ = 0;
bcount = 0;
/* skip to the next one and initialize it if any */
do {
s++;
} while (*s == ' ' || *s == '\t');
if (*s)
argv[argc++] = d;
}
else if (*s == '\\')
{
*d++ = *s++;
bcount++;
}
else if (*s == '"')
{
if ((bcount & 1) == 0)
{
/* Preceded by an even number of '\', this is half that
* number of '\', plus a quote which we erase.
*/
d -= bcount / 2;
qcount++;
}
else
{
/* Preceded by an odd number of '\', this is half that
* number of '\' followed by a '"'
*/
d = d - bcount / 2 - 1;
*d++ = '"';
}
s++;
bcount = 0;
/* Now count the number of consecutive quotes. Note that qcount
* already takes into account the opening quote if any, as well as
* the quote that lead us here.
*/
while (*s == '"')
{
if (++qcount == 3)
{
*d++ = '"';
qcount = 0;
}
s++;
}
if (qcount == 2)
qcount = 0;
}
else
{
/* a regular character */
*d++ = *s++;
bcount = 0;
}
}
*d = '\0';
argv[argc] = NULL;
*numargs = argc;
return argv;
}
</code></pre>
<p>to build use</p>
<pre><code>@echo off
cl.exe -nologo -Oi -O2 -GS- comments.c -link -subsystem:console -nodefaultlib kernel32.lib shell32.lib
</code></pre>
|
[] |
[
{
"body": "<h1>Use the standard library</h1>\n<blockquote>\n<p>This all started when I wanted to make a simple program [...]</p>\n</blockquote>\n<p>Your program is much more complicated than necessary because you are not using the standard library. While it may be an interesting challenge to see how to write a program without using the standard library, <a href=\"https://codereview.stackexchange.com/questions/248175/simple-windows-implementation-of-the-cat-command\">you already did that</a>. Now it just is not a productive use of your time. It makes the program much longer than necessary, which means the chances of there being bugs in your code is also higher than necessary. Also, your program is not portable to other operating systems.</p>\n<p>So, to improve your program: rewrite it so it is portable C code that uses the standard library.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T11:33:13.693",
"Id": "250829",
"ParentId": "250824",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "250829",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T06:50:00.523",
"Id": "250824",
"Score": "3",
"Tags": [
"c"
],
"Title": "code comment finder"
}
|
250824
|
<p>I needed a <strong>simple</strong> parser that could do both logical and math operations expressed in a string, as well as being able to use variables stored in json.</p>
<p>None of what I found online seemed to do all of the above, so I came up with my own. Below is the source code for my <code>ExpressionParser</code> as well as my <code>JExpressionParser</code>, in case your variables are stored in a JSON.</p>
<p>Hopefully this post will help someone, as well as allow others to improve my code.</p>
<p>Here is the base parser:</p>
<pre><code>using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
public class ExpressionParser
{
public virtual IDictionary<string, object> Variables { get; }
protected ExpressionParser() { }
protected virtual DataTable GetComputer()
{
var computer = new DataTable();
if (Variables != null)
{
computer.Columns.AddRange(Variables.Select(v => new DataColumn(v.Key) { DataType = v.Value.GetType() }).ToArray());
computer.Rows.Add(Variables.Values.ToArray());
}
return computer;
}
public ExpressionParser(IDictionary<string, object> variables = null)
{
Variables = variables ?? new Dictionary<string, object>();
}
public object Compute(string expression)
{
StringBuilder sb = new StringBuilder(expression);
foreach (var key in Variables.Keys)
sb.Replace(key, $"Sum({key})");
sb.Replace("==", "=");
using (var computer = GetComputer())
return computer.Compute(sb.ToString(), null);
}
}
</code></pre>
<p>And here is one that works with json objects:</p>
<pre><code>using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
public class JExpressionParser : ExpressionParser
{
public JObject JVariables { get; set; }
public override IDictionary<string, object> Variables =>
JVariables.Properties().ToDictionary(p => p.Name, p => p.Value.ToObject(conversions[p.Value.Type]));
static readonly Dictionary<JTokenType, Type> conversions = new Dictionary<JTokenType, Type>()
{
[JTokenType.Integer] = typeof(int),
[JTokenType.Float] = typeof(float),
[JTokenType.Boolean] = typeof(bool),
};
public JExpressionParser(JObject jVariables = null)
{
JVariables = jVariables ?? new JObject();
}
}
</code></pre>
<p>Usage:</p>
<pre><code>var variables = new Dictionary<string, object>() { ["budget"] = 1000, ["cost"] = 965 };
var parser = new ExpressionParser(variables);
Console.WriteLine("We have $" + parser.Compute("budget - cost") + " of budget left.");
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T11:16:42.943",
"Id": "493470",
"Score": "6",
"body": "Could you give us a sample of a JSON that you can apply this parser to it ? I'm trying to figure out what drives you to take this approach, as parsing an open string expression would be hard to maintain, but if we have the full picture, we could give you a better answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T11:24:36.223",
"Id": "493472",
"Score": "0",
"body": "Why do you want to use expression instead of `Linq expression` because even in your example can be done in `Linq` ? what do you actually need and expect from your code ? What your `ExpressionParser` covers that `LINQ` doesn't ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T00:49:15.427",
"Id": "493534",
"Score": "0",
"body": "@iSR5 By providing the following JSON to the parser {\"age\": 19, \"year\": 2020}; you could evaluate the following expression: \"year - age\", which would give you the year I was born. The idea is to allow users to insert math expressions in text or word files that can be replaced dinamically depending on the provided JSON."
}
] |
[
{
"body": "<p>I can see three small improvement areas:</p>\n<h3>Use ctor instead of object initializer</h3>\n<p>Instead of this:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>new DataColumn(v.Key) { DataType = v.Value.GetType() }\n</code></pre>\n<p>Use this:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>new DataColumn(v.Key, v.Value.GetType())\n</code></pre>\n<p>Object initializer will run after ctor. If ctor accepts that parameter then prefer to provide it in the ctor.</p>\n<h3>Use early exist instead of guard expression</h3>\n<p>Instead of this:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>if (Variables != null)\n{\n computer.Columns.AddRange(Variables.Select(v => new DataColumn(v.Key, v.Value.GetType())).ToArray());\n computer.Rows.Add(Variables.Values.ToArray());\n}\nreturn computer;\n</code></pre>\n<p>Use this:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>if ((Variables?.Any() ?? true)) return computer;\n\ncomputer.Columns.AddRange(Variables.Select(v => new DataColumn(v.Key, v.Value.GetType())).ToArray());\ncomputer.Rows.Add(Variables.Values.ToArray());\nreturn computer;\n</code></pre>\n<p>Yes, I know it's against the single return statement. But with this approach you streamline your logic.</p>\n<h3>Use immutable collection instead of just <code>readonly</code> access modifier</h3>\n<p>Instead of this:</p>\n<pre><code>static readonly Dictionary<JTokenType, Type> conversions = new Dictionary<JTokenType, Type>()\n{\n [JTokenType.Integer] = typeof(int),\n [JTokenType.Float] = typeof(float),\n [JTokenType.Boolean] = typeof(bool),\n};\n</code></pre>\n<p>Use this:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>static readonly ImmutableDictionary<JTokenType, Type> conversions = new Dictionary<JTokenType, Type>()\n{\n [JTokenType.Integer] = typeof(int),\n [JTokenType.Float] = typeof(float),\n [JTokenType.Boolean] = typeof(bool),\n}.ToImmutableDictionary();\n</code></pre>\n<p>With <code>readonly</code> you only prevent to replace the whole object. But you can still add and remove new items to the dictionary:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>//Invalid operations\nconversions = null;\nconversions = new Dictionary<string, JTokenType> {};\n\n//Valid operations\nconversions.Add(JTokenType.Array, typeof(Array));\nconversions.Remove(JTokenType.Integer);\n</code></pre>\n<p>With <code>ImmutableDictionary</code> the <code>Add</code> and <code>Remove</code> will return a new <code>ImmutableDictionary</code> so it will not have any effect on the original collection. Visual Studio will even worn you about it:</p>\n<p><a href=\"https://i.stack.imgur.com/UTNRr.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/UTNRr.png\" alt=\"enter image description here\" /></a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T19:17:39.943",
"Id": "493604",
"Score": "3",
"body": "That's great! I didn't know ImmutableDictionary existed. It shouldn't matter too much since it's private but it's a good practice, and should be useful for other projects."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T13:37:02.110",
"Id": "250868",
"ParentId": "250825",
"Score": "5"
}
},
{
"body": "<ul>\n<li><p><code>ExpressionParser</code> is too general, you might need to renamed it to be specific such as <code>MathExpressionParser</code>.</p>\n</li>\n<li><p><code>ExpressionParser</code> should be <code>abstract</code> class along with <code>Variables</code> property.</p>\n</li>\n<li><p><code>Computer</code> in <code>ExpressionParser</code> can be declared globally, and used across the class.</p>\n</li>\n<li><p>in the <code>Compute</code> method, you're not validating the string, you should add some validations such as null, empty, whitespace, and any related possible validations.</p>\n</li>\n<li><p>it's not a good practice to default constructor arguments, instead you can do this :</p>\n<pre><code>public ExpressionParser() : this(null) { }\n\npublic ExpressionParser(IDictionary<string, object> variables)\n{\n Variables = variables ?? new Dictionary<string, object>();\n}\n</code></pre>\n</li>\n</ul>\n<p>As I mentioned in the comments, maintaining an open-string expression it's not an easy work, so you will need to add some restrictions to it.\nFor now, you're depending on <code>DataColumn</code> expression restrictions, if you have any plan to expand this to cover than what <code>DataColumn</code> covers, then I would suggest using another approach such as <code>Roslyn</code> script engine.\nBasically, you can use this engine to convert a raw string to an instance of <code>Func</code> lambda dynamically. with that, it'll add more fixability to your work, such as object-model, Linq ..etc. Adding more open-possibilities to your expression features, with possibility to be adopt any sort of structured data. (for instance, you can integrated with <code>Json.NET</code>, <code>XDocument</code>, <code>Razor</code> ..etc. Which would be useful in different areas.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T03:45:27.387",
"Id": "250890",
"ParentId": "250825",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "250890",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T07:11:14.037",
"Id": "250825",
"Score": "4",
"Tags": [
"c#",
"parsing",
".net"
],
"Title": "C# Logical and Math expression parser"
}
|
250825
|
<p>I've been learning MASM64 over the last few days and written a simple demo, so I can get feedback on my understanding of x64 assembly programming.</p>
<p>It's really basic: it asks the user for their name, greets them, and then reverses the name string.</p>
<p>The point of this question is to get a confirmation I understand the basic stuff like calling convention, stack alignment, etc. correctly. It's surely <strong>not</strong> about performance.</p>
<p>The complete code:</p>
<pre><code>extrn GetStdHandle : proc
extrn WriteConsoleA : proc
extrn ReadConsoleA : proc
.const
STDIN_HANDLE_ID equ -10
STDOUT_HANDLE_ID equ -11
INVALID_HANDLE_VALUE equ -1
NULL equ 0
.data
promptText db "Enter your name: ", 0
greetingText db "Hello, ", 0
backwardsText db "Your name backwards is: ", 0
.code
; Counts characters in a null-terminated string.
; Parameters:
; 1. Pointer to string.
; Return value:
; -> string length (without the terminator).
;
stringLength proc
; No need for shadow space.
mov rdx, rcx
mov rcx, -1
_nextChar:
inc rcx
mov al, byte ptr [rdx + rcx]
test al, al
jnz _nextChar
mov rax, rcx
ret
stringLength endp
; Displays a null-terminated string.
; Parameters:
; 1. Pointer to string to be displayed.
; 2. Number of characters to be displayed.
; Return value:
; -> On success: 0.
; -> On failure: -1.
;
stringPrint proc
; Reserve shadow space.
sub rsp, 48h
; Save string address for later use.
mov [rsp + 38h], rcx
call stringLength
; If (length == 0), just end the function.
test rax, rax
jz _stringPrintEnd
; Save string length for later use.
mov [rsp + 40h], rax
mov rcx, STDOUT_HANDLE_ID
call GetStdHandle
cmp rax, INVALID_HANDLE_VALUE
je _stringPrintEnd
mov qword ptr [rsp + 28h], NULL
mov r9, NULL
mov r8d, [rsp + 40h]
mov rdx, [rsp + 38h]
mov rcx, rax ; console handle
call WriteConsoleA
test rax, rax
jz _stringPrintError
xor rax, rax
_stringPrintEnd:
; Free shadow space.
add rsp, 48h
ret
_stringPrintError:
mov rax, -1
jmp _stringPrintEnd
stringPrint endp
; Reads count-1 characters from the standard input.
; Parameters:
; 1. Pointer to buffer to store the characters.
; 2. Character count.
; Return value:
; -> On success: 0.
; -> On error: -1.
;
stringRead proc
; Reserve shadow space.
sub rsp, 48h
; Save volatile registers for later use.
mov [rsp + 38h], rcx
mov [rsp + 40h], rdx
mov rcx, STDIN_HANDLE_ID
call GetStdHandle
cmp rax, INVALID_HANDLE_VALUE
je _stringReadError
mov qword ptr [rsp + 20h], NULL
lea r9, [rsp + 28h]
mov r8, [rsp + 40h]
mov rdx, [rsp + 38h]
mov rcx, rax
call ReadConsoleA
test rax, rax
jz _stringReadError
xor rax, rax
_stringReadError:
; Free shadow space.
add rsp, 48h
ret
stringRead endp
; Reverses a null-terminated string.
; Parameters:
; 1. Pointer to string to be reversed.
; 2. Pointer to buffer to store the output.
;
stringReverse proc
; Reserve shadow space.
sub rsp, 38h
; Save volatile registers.
mov [rsp + 28h], rcx ; src buffer
mov [rsp + 30h], rdx ; dst buffer
; RCX is already set.
call stringLength
test rax, rax
jz _stringReverseEnd
mov rcx, [rsp + 28h]
dec rcx
mov rdx, [rsp + 30h]
add rdx, rax
; Terminate the dst buffer.
mov byte ptr [rdx], 0
_reverseNextChar:
inc rcx
dec rdx
mov al, byte ptr [rcx]
; Check for terminator in src buffer.
test al, al
jz _stringReverseEnd
mov byte ptr [rdx], al
jmp _reverseNextChar
_stringReverseEnd:
xor rax, rax
; Free shadow space.
add rsp, 38h
ret
stringReverse endp
main proc
; Reserve shadow space: 20h for calls + 28h for buffers.
sub rsp, 48h
; Zero the buffers.
mov qword ptr [rsp + 20h], 0
mov qword ptr [rsp + 28h], 0
mov qword ptr [rsp + 30h], 0
mov qword ptr [rsp + 38h], 0
mov qword ptr [rsp + 40h], 0
lea rcx, promptText
call stringPrint
mov rdx, 14h
lea rcx, [rsp + 20h] ; reading buffer
call stringRead
lea rdx, [rsp + 34h] ; destination buffer
lea rcx, [rsp + 20h] ; source buffer
call stringReverse
lea rcx, greetingText
call stringPrint
lea rcx, [rsp + 20h]
call stringPrint
lea rcx, backwardsText
call stringPrint
lea rcx, [rsp + 34h]
call stringPrint
xor rax, rax
; Free shadow space.
add rsp, 48h
ret
main endp
end
</code></pre>
<p>Thanks for the help.</p>
|
[] |
[
{
"body": "<p>The <em>stringLength</em> leaf function (no prolog/epilog) could still be a bit simpler:</p>\n<pre><code>stringLength proc\n mov rax, -1\n _nextChar:\n inc rax\n cmp byte ptr [rcx + rax], 0\n jne _nextChar\n ret\nstringLength endp\n</code></pre>\n<hr />\n<p>The comments on the <em>stringPrint</em> frame function suggest that a second parameter exists.</p>\n<pre><code>; Displays a null-terminated string.\n; Parameters:\n; 1. Pointer to string to be displayed.\n; 2. Number of characters to be displayed.\n</code></pre>\n<p>This is not the case.</p>\n<p>When the call to <em>GetStdHandle</em> fails, you jump to <em>_stringPrintEnd</em> where I think you could jump to <em>_stringPrintError</em>.</p>\n<p>The 5th parameter for <em>WriteConsoleA</em>, the one that goes onto the stack, must go to <code>[rsp + 20h]</code> right above the register home area. You wrote <code>[rsp + 28h]</code>.</p>\n<p>A simpler exit is:</p>\n<pre><code> test rax, rax\n mov rax, -1\n jz _stringPrintEnd\n xor rax, rax\n_stringPrintEnd:\n add rsp, 48h\n ret\n</code></pre>\n<hr />\n<p>The exit from the <em>stringRead</em> frame function is not very useful. It will always return <code>RAX=0</code>. In other words: the test is redundant.</p>\n<pre><code> test rax, rax\n jz _stringReadError\n xor rax, rax\n_stringReadError:\n</code></pre>\n<hr />\n<p>In the <em>stringReverse</em> proc, it is easy to write the loop using a single conditional jump, omitting the second jump. I know that you're not seeking performance but then again this is assembly...</p>\n<pre><code> mov al, 0 ; To terminate the dst buffer.\n_reverseNextChar:\n inc rcx\n mov [rdx], al\n dec rdx\n mov al, [rcx]\n test al, al \n jnz _reverseNextChar\n</code></pre>\n<hr />\n<h2>Some ideas</h2>\n<ul>\n<li><p>Instead of determining the string length yourself, why don't you use the <em>lpNumberOfCharsRead</em> that you receive from invoking <em>ReadConsoleA</em>?</p>\n</li>\n<li><p>Why do you bother to zero your source and destination buffers. That's not a useful operation (unless you doubt that the input from <em>ReadConsoleA</em> will be zero-terminated by default).<br />\nAnd if you insist on clearing these buffers then please try not to use that many bytes. Next is much smaller:</p>\n<pre><code> xor eax, eax\n mov [rsp + 20h], rax\n mov [rsp + 28h], rax\n mov [rsp + 30h], rax\n mov [rsp + 38h], rax\n mov [rsp + 40h], rax\n</code></pre>\n</li>\n<li><p>It will be much nicer if you introduced a couple of newlines in the output:</p>\n<pre><code> greetingText db 13, 10, "Hello, ", 0\n backwardsText db 13, 10, "Your name backwards is: ", 0\n</code></pre>\n</li>\n</ul>\n<blockquote>\n<p>The point of this question is to get a confirmation I understand the basic stuff like calling convention, stack alignment, etc. correctly.</p>\n</blockquote>\n<p>Except for that 5th parameter on <em>WriteConsoleA</em>, this seems to be fine. Well done.</p>\n<p>For maximum adherence to the conventions you could store the register parameters <code>RCX</code> and <code>RDX</code> in the shadow memory that the caller had to set aside for that purpose.<br />\nBelow is how it changes <em>stringRead</em> (similar for <em>stringPrint</em> and <em>stringReverse</em>):</p>\n<pre><code>stringRead proc\n ; Save volatile registers in register home area for later use.\n mov [rsp + 8], rcx\n mov [rsp + 16], rdx\n ; Reserve shadow space, local storage and alignment\n sub rsp, 38h\n \n mov rcx, STDIN_HANDLE_ID\n call GetStdHandle\n \n ...\n \n mov qword ptr [rsp + 20h], NULL\n lea r9, [rsp + 28h]\n mov r8, [rsp + 38h + 16]\n mov rdx, [rsp + 38h + 8]\n mov rcx, rax\n call ReadConsoleA\n \n ...\n\n add rsp, 38h\n ret\nstringRead endp\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T09:16:17.950",
"Id": "493661",
"Score": "1",
"body": "Thanks for taking the time to read it and for your commentary. I can't believe I didn't spot at least some of those errors, haha. Also, the suggestion to use the caller-allocated shadow space was an eye-opener, made me realize I didn't **fully** understand the convention. Once again - thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-19T20:00:07.333",
"Id": "497241",
"Score": "0",
"body": "Since this is x86-64, the standard way to store a bunch of zeros is with SSE or SSE2. `xorps xmm0,xmm0` / `movaps [rsp + 20h], xmm0` etc. (With the last store being `movlps [rsp+40h], xmm0` if you need to store an odd multiple of 8.)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T21:12:16.193",
"Id": "250843",
"ParentId": "250830",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "250843",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T12:28:00.847",
"Id": "250830",
"Score": "4",
"Tags": [
"beginner",
"assembly",
"winapi",
"amd64"
],
"Title": "Trivial string-reverser in MASM64"
}
|
250830
|
<p>This code write to determine a way to place the N horses into the K stables, so that the total coefficient of unhappiness is minimized.</p>
<p>I use python to write a code and I want to reduce the running time and memory used. Or maybe shorten the code. What should I do?</p>
<p>My memory used is about 67,000- 80,000 KB.</p>
<p>My running time is about 0.25 - 0.28 miliseconds</p>
<p>Should I try to change the ways I acquire all possible combinations in <code>printAllKLength()</code> or get all the for loops outside of function inside the related function.</p>
<p>Question link: <a href="https://acm.timus.ru/problem.aspx?space=1&num=1167" rel="nofollow noreferrer">https://acm.timus.ru/problem.aspx?space=1&num=1167</a></p>
<blockquote>
<p>This algorithm do as places the 1st <span class="math-container">\$ P_1 \$</span> horses in the first
stable, the next <span class="math-container">\$ P_2 \$</span> in the 2nd stable and so on. Moreover, any
of the K stables cannot be empty, and no horse must be left outside.
There are black or white horses, which don't really get along too
well. If there are <span class="math-container">\$ i \$</span> black horses and <span class="math-container">\$ j \$</span> white horses in
one stable, then the coefficient of unhappiness of that stable is <span class="math-container">\$ i
* j \$</span>. The total coefficient of unhappiness is the sum of the coefficients of unhappiness of every of the K stables.</p>
<p>Determine a way to place the N horses into the K stables, so that the
total coefficient of unhappiness is minimized.</p>
<p>Input: On the 1st line there are 2 numbers: <span class="math-container">\$ N (1 \le N \le 500) \$</span> and <span class="math-container">\$ K (1 \le
K \le N) \$</span>. On the next N lines there are N numbers. The i-th of these
lines contains the color of the i-th horse in the sequence: 1 means
that the horse is black, 0 means that the horse is white.</p>
<p>Output: You should only output a single number, which is the minimum
possible value for the total coefficient of unhappiness.</p>
<p>Sample Input and Output</p>
<p>Input:</p>
<pre><code>6 3
1
1
0
1
0
1
</code></pre>
<p>Output:</p>
<pre><code>2
</code></pre>
</blockquote>
<hr />
<pre><code>import sys
inputs = list(map(int, input().split()))
n = inputs[0] #n = no. of horse
k = inputs[1] #k = no. of stable
seq = [] #seq = keep input horse sequence
options = [] #options = keep the options of place no. of horse
combi = [] #keep all combinations based on options in list of string element
#maxc = To find the maximum no of horse should be place consider that left no
# empty stable and at least place one horse in first stable
maxc = n-(k-1)
#To run loop and append the input sequence into ‘seq’ list.
for i in range(n):
s = int(input())
seq.append(s)
#find options to place horse = 1,2,3,4 if n = 6
#because all the stable cannot be empty and therefore must at least put horse
#in one stable, so in one stable cannot put horse more than n-(k-1)
#to run loop and append options to place horses based on ‘maxc’ value into ‘options’ list.
for i in range(maxc):
options.append(str(i+1))
#functions to get all combination of no. of horse per stable based on options
#It is mainly a wrapper over recursive function printAllKLengthRec()
def printAllKLength(set, kk):
size_of_list = len(set)
printAllKLengthRec(set, "", size_of_list, kk)
# The main recursive method to print all possible strings of length k
def printAllKLengthRec(set, prefix, size_of_list, kk):
# Base case: kk is 0,
# print prefix
if (kk == 0) :
combi.append(prefix)
return
# One by one add all characters
# from set and recursively
# call for k equals to k-1
for i in range(size_of_list):
# Next character of input added
newPrefix = prefix + set[i]
# k is decreased, because
# we have added a new character
printAllKLengthRec(set, newPrefix, size_of_list, kk - 1)
printAllKLength(options, k)
#Function to convert teh string element list to int element list and
#check if sums of element in sublist are equal to 'n'
def convert(the_list):
#change list of str elements to int elements instead
#Run the for loop to convert from string value to list of int value for one
#combination and substitute the converted into ‘the_list’ at the same index
#‘i’ that currently perform conversion on that combination.
for i in range(len(the_list)):
digits = [int(x) for x in str(the_list[i])]
the_list[i] = digits
b_list = []
#check if all sum of each combination from function is actually
#equal to input no. of horse
#Create a temporary list ‘b_list’ to compute the sum of each
#combination(‘a_list[i]’) and check condition if the sum is equal to ‘n’ value
#(Total number of horse). If so, then append ‘a_list[i]’ combination and the
#‘convert_check()’ function
for i in range(len(the_list)):
sums = sum(the_list[i])
if sums == n:
the_list.append(the_list[i])
return b_list
pos_ways = convert(combi)
#Function to split a seq of horse into stable based on no. of horse per stable
from itertools import islice
def split(the_list, combi_list):
j = 0
result_list = []
while j < len(combi_list):
the_list_iter = iter(the_list)
re2 = [list(islice(the_list_iter, length)) for length in combi_list[j]]
result_list.append(re2)
j += 1
return result_list
#find the no of black & white horse in each placed sequence of each combination
#re_seq = [[1],[1],[0,1,0,1]]
def find_bw(the_list):
black = 0
white = 0
for i in range(len(the_list)):
o = the_list[i]
if the_list[i] == 0:
white += 1
elif the_list[i] == 1:
black += 1
s = (white, black)
return s
#find the no of black & white horse in all seq of all combination
#all_re_seq = [[[1],[1],[0,1,0,1]],[[1,1],[0],[1,0,1]],......]
def find_bw2(the_list2):
for i in range(len(the_list2)):
s2 = find_bw(the_list2[i])
the_list2[i] = s2
return the_list2
re_seq = split(seq, pos_ways)
no_of_horse = []
#to get no. of black and white horse in each stable
for i in range(len(re_seq)):
go = find_bw2(re_seq[i])
no.append(go)
#to get the coefficient unhappiness in each stable by
#no. of black horse * no. of white horse
def mul_co(the_list):
for i in range(len(the_list)):
tu = the_list[i]
t1 = tu[0]
t2 = tu[1]
the_list[i] = t1*t2
return the_list
#keep all coefficient unhappiness in each stable for all possible ways
coef = [-1]*len(no)
#run function and store all coefficient unhappiness in each stable
#for all possible ways
for i in range(len(no)):
ko = mul_co(no[i])
coef[i] = ko
max_value = sys.maxsize
#to find the minimum of coefficient happiness
def coef_un(the_list):
minimum = max_value
for j in range(len(the_list)):
sums = 0
for i in range(len(the_list[j])):
sums += the_list[j][i]
the_list[j] = sums
minimum = min(minimum, the_list[j])
return minimum
print(coef_un(coef))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T16:23:07.657",
"Id": "493498",
"Score": "3",
"body": "\"My running time is about 0.25 - 0.28.\" Years? Minutes? Milliseconds?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T19:22:57.960",
"Id": "493523",
"Score": "1",
"body": "The time limit is 1 second, so your \"0.25 - 0.28 miliseconds\" is already thousands of times faster than it needs to be. Well done! Unless you work [at Verizon](http://verizonmath.blogspot.com/2006/12/verizon-doesnt-know-dollars-from-cents.html) :-P"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T05:59:46.813",
"Id": "493536",
"Score": "0",
"body": "there are just far too many comments instead of code itself.... :|"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T06:11:46.253",
"Id": "493537",
"Score": "0",
"body": "also, the code raises an error when testing with provided input values. https://tinyurl.com/codereview-250833"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T06:48:00.713",
"Id": "493541",
"Score": "0",
"body": "I think `no.append(go)` should've been `no_of_horse.append(go)` (similar for `coef = [-1]*len(no)`, the code presented will not run because `no` is never defined."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T15:33:44.613",
"Id": "250833",
"Score": "2",
"Tags": [
"python",
"algorithm",
"python-3.x",
"programming-challenge"
],
"Title": "Getting the minimum possible value from list consist of '0' and '1' by multiply no. of [0,1] and add the result after sliced in 'k' section"
}
|
250833
|
<p>I am trying to code a sin wave with 5 sliders: frequency, amplitude, phase change, number of data points, and time. I am currently trying to link my phase change slider with my graph so that it updates it when I move the slider. I realize that my code is probably quite messy and could be more concise but I can adjust that later.</p>
<p>I think adding a phase change slider and length of time the function is plotted for would be good too, like the frequency and amplitude sliders (which do work).</p>
<p>For those who aren't familiar with the physics terms:
amplitude: height of the wave (in y-axis)</p>
<ul>
<li>frequency: number of times a wave passes a certain point per unit time. 1 Hertz = 1 wave passing per second</li>
<li>Phase difference: the change in the starting position of the current wave where amplitude = 0 at t = 0. A 90-degree phase change would shift the function the left or right, then representing a cos function rather than sine.</li>
</ul>
<p>Any advice for my current code would be much appreciated!</p>
<p>My code so far:</p>
<pre><code>import tkinter
import numpy as np
from scipy import signal
from scipy.fft import fft, ifft as sc
from matplotlib import pyplot as p, animation
# Implement the default Matplotlib key bindings.
from matplotlib.backend_bases import key_press_handler
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
from matplotlib.figure import Figure
from matplotlib.widgets import Slider
root = tkinter.Tk()
root.wm_title("Embedding in Tk")
fig = Figure(figsize=(6, 5), dpi=100)
t = np.linspace(0, 5, 200)
f = 1
time = np.linspace(0, 100, 101)
y = np.sin(f*t)
fig.subplots_adjust(left=0.15, bottom=0.45) # Adjust subplots region leaving room for the sliders
and buttons
canvas = FigureCanvasTkAgg(fig, master=root) # A tk.DrawingArea.
canvas.draw()
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
toolbar = NavigationToolbar2Tk(canvas, root)
toolbar.update()
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
def on_key_press(event):
print("you pressed {}".format(event.key))
key_press_handler(event, canvas, toolbar)
canvas.mpl_connect("key_press_event", on_key_press)
def _quit():
root.quit() # stops mainloop
root.destroy()
button = tkinter.Button(master=root, text="Quit", command=_quit)
button.pack(side=tkinter.BOTTOM)
# Amplitude slider
initiala = 1 # starting value of amplitude on graph
asliderax = fig.add_axes([0.25, 0.15, 0.65, 0.03]) # setting amplitude slider position
aslider = Slider(asliderax, 'Amp', 0.1, 10.0, valinit=initiala) # setting amplitude slider values
# Frequency slider
initialf = 1 # starting value of frequency on graph
fsliderax = fig.add_axes([0.25, 0.1, 0.65, 0.03]) # setting frequency slider position
fslider = Slider(fsliderax, 'Freq', 0.1, 3.0, valinit=initialf) # setting frequency slider values
# Time slider
initialt = 1 # starting value of time on graph
tsliderax = fig.add_axes([0.25, 0.2, 0.65, 0.03]) # setting time slider position
tslider = Slider(tsliderax, 'Time', 0.1, 100.0, valinit=initialt) # setting time slider values
# Number of Points slider
initialp = 99 # starting value of number of points on graph
psliderax = fig.add_axes([0.25, 0.25, 0.65, 0.03]) # setting points slider position
pslider = Slider(psliderax, 'Points', 3, 30.0, valinit=initialp) # setting frequency points values
# Phase slider
initialph = 0 # starting value of number of points on graph
phsliderax = fig.add_axes([0.25, 0.3, 0.65, 0.03]) # setting points slider position
phslider = Slider(phsliderax, 'Phase Change', 0, np.pi*2, valinit=initialph) # setting frequency
points values
def update(val):
amp = aslider.val
freq = fslider.val
t = np.linspace(0, 5, 200)
y.set_ydata(amp*np.sin(2*np.pi*freq*t))
fslider.on_changed(update)
aslider.on_changed(update)
tslider.on_changed(update)
pslider.on_changed(update)
tkinter.mainloop()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T17:03:55.447",
"Id": "493505",
"Score": "0",
"body": "About this: _I can't quite think how to add the phase change slider like the frequency and amplitude sliders_ - Code Review cannot help you. We review code that is working. Given that your code is \"mostly working\", if you edit your question to focus on review, it will be on-topic; but any emphasis on fixing your slider problem will keep it off-topic. For that problem you're best off asking Stack Overflow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T19:11:30.887",
"Id": "493518",
"Score": "0",
"body": "@Reinderien So if I ask 'How can this code be developed/improved' or something similar and more specific then this would be on-topic? Just want to check I understand you correctly. Apologies if I misunderstood you"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T19:17:49.030",
"Id": "493521",
"Score": "0",
"body": "Exactly right "
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T20:41:30.390",
"Id": "493526",
"Score": "3",
"body": "Can you also put in some links and images showing current app, and reference to the phase, amplitude relations etc. It has been years since I studied physics"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T21:15:10.637",
"Id": "493528",
"Score": "0",
"body": "@Reinderien is this what you had in mind? I think the original title was fine, but somehow *I can't quite think how to add the phase change slider like the frequency and amplitude sliders* got left in the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T15:26:13.247",
"Id": "493574",
"Score": "0",
"body": "@pacmaninbw I think this is better? please let me know if it still needs changing"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T15:27:59.887",
"Id": "493575",
"Score": "0",
"body": "@hjpotter92 I have added definitions for you, but the photo I took of the graph was too large to add. I will try and take another photo of less than 2 MB. For now, if you google 'sin graph' and 'fft of sin graph' you should find both of the functions I have. Again sorry for the inconvenience."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T16:28:58.330",
"Id": "493585",
"Score": "0",
"body": "I've made a few minor changes, that you should look at, especially the one right before the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T06:36:42.613",
"Id": "493659",
"Score": "2",
"body": "@pacmaninbw just a note, \"realise\" is also correct :) https://www.merriam-webster.com/words-at-play/realize-vs-realise-difference"
}
] |
[
{
"body": "<p>Seems to me you just need to add the phase to the angle in <code>update()</code>.</p>\n<pre><code>def update(val):\n amp = aslider.val\n freq = fslider.val\n phase = phslider.val\n t = np.linspace(0, 5, 200)\n\n y.set_ydata(amp*np.sin(2*np.pi*freq*t + phase)) # << add phase here\n\n\nfslider.on_changed(update)\naslider.on_changed(update)\ntslider.on_changed(update)\npslider.on_changed(update)\nphslider.on_changed(update) # update on slider change\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T18:20:15.513",
"Id": "250920",
"ParentId": "250834",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T16:06:14.593",
"Id": "250834",
"Score": "5",
"Tags": [
"python",
"tkinter"
],
"Title": "Sinewaves and FFT plotter"
}
|
250834
|
<p>This is a game for children 3years+ to learn Hand-Eye Coordination with Mouse Movement.<br />
Goal is to catch all dinosaurs in the jungle, get the egg reward and then repeat the game.</p>
<p>I tried to add sounds but unfortunately chrome rules say if the user doesn't interact with the page (aka click, etc.) no sound play is allowed so I wasn't able to do a hover sound for collecting a dino.</p>
<p>Same goes for background music. Getting a button which was first hidden to press for restart the game also didn't work so I did an delayed 8 seconds reload.<br />
Maybe I do it in PHP?</p>
<p>For best experience press F11 for Browser Full Screen :D<br />
With Pics
<a href="https://github.com/CodeLegend27/Hand-Eye-Coordination-Child-3y-plus" rel="nofollow noreferrer">https://github.com/CodeLegend27/Hand-Eye-Coordination-Child-3y-plus</a><br />
Pure Code
<a href="https://codepen.io/CodeLegend27/pen/RwRRGNa" rel="nofollow noreferrer">https://codepen.io/CodeLegend27/pen/RwRRGNa</a></p>
<p>Kind regards</p>
<p><strong>HTML</strong></p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>Child Game</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<link rel='stylesheet' type='text/css' media='screen' href='dist/main.css'>
<script src='main.js'></script>
</head>
<body style="overflow: hidden;">
<div id="egg" style="display: none;">
</div>
<div id="egg" style="display: none;">
</div>
<img id="gg" src="img/net-3850048_960_720.png" style="position:absolute; width: 50px; overflow: hidden;">
<script>
$(document).mousemove(function(e){
$("#gg").css({left:e.pageX, top:e.pageY});
});
</script>
<div class="main">
<div class="row">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"><p>&#128512;</p></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>
<div class="row">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>
<div class="row">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>
<div class="row">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>
<div class="row">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>
</div>
</body>
</html>
</code></pre>
<p><strong>CSS</strong></p>
<pre><code>.main {
height: 100vh;
width: 100%;
}
.row {
display: flex;
}
.square {
display: flex;
width: 10vw;
height: 20vh;
align-items: center;
justify-content: center;
}
p {
font-size: 15em;
height: 100%;
cursor: pointer;
width: 100%;
display: none;
}
body {
cursor: url("../img/net-3850048_960_720.png"), auto;
height: 100vh;
/* background: rgb(18, 4, 250);
background: linear-gradient(180deg, rgba(18, 4, 250, 1) 0%, rgba(0, 212, 255, 1) 100%); */
background-image: url("../img/jungle-4003374_1920.jpg");
background-size: cover;
}
* {
margin: 0;
padding: 0;
}
#egg {
position: absolute;
bottom: 30px;
display: inline-block;
width: 126px;
height: 60px;
padding-top: 120px;
text-align: center;
text-shadow: 1px 1px rgba(250, 249, 246, 0.9);
color: rgba(168, 168, 168, 0.8);
font-weight: 900;
border-radius: 63px 63px 63px 63px/108px 108px 72px 72px;
background: radial-gradient(75% 100% at 63px 15px, #f7f7f2 0%, #eaeae3 30%, #b1ac9d 100%);
box-shadow: 0px 3px 18px -4px rgba(40, 40, 40, 0.9);
margin: 20px;
margin-right: 45px;
transition: all 0.2s linear 0;
-webkit-transition: 0.2s;
-webkit-transition-timing-function: linear;
-webkit-animation: anime_egg_move 3s infinite;
-webkit-animation-timing-function: linear;
-webkit-animation-direction: alternate;
}
@-webkit-keyframes anime_egg_move {
to {
-webkit-transform: rotate(360deg);
margin-left: 700px;
}
}
</code></pre>
<p><strong>JS</strong></p>
<pre><code>//
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
alert("Please Play on Desktop PC")
}
// IMG ARRAY
var images = ['dino8.png', 'dino1.png', 'dino2.png','dino3.png', 'dino4.png', 'dino5.png', 'dino6.png', 'dino7.png'];
$( document ).ready(function() {
// POPULATE SITE WITH IMAGES -- Randomly, Random size
$('.square').each(function() {
var randNumb = Math.floor(Math.random() * 71) + 30;
var rand = Math.floor(Math.random() * images.length);
$(this).append('<img class="dino" src="img/' + images[rand] + '"/ width="'+ randNumb +'%" height="'+randNumb+'%">');
});
// COUNT TILL GAME FINISH, Show Egg and smiley, RELOAD PAGE
let x = 0;
$('.dino').hover(function(){
$(this).remove();
x++
if (x == 50){
$("#egg").css("display", "block");
$("p").css("display", "block");
setTimeout(location.reload.bind(location), 8000);
}
console.log(x);
});
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T18:14:07.170",
"Id": "493510",
"Score": "0",
"body": "thanks for input i thought github and codepen is enough, my first time here. i did added the code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T18:18:49.580",
"Id": "493511",
"Score": "2",
"body": "btw, you can use github pages instead of codepen to deploy the page :)"
}
] |
[
{
"body": "<p><strong>Indentation</strong> Much of the indentation in the HTML, CSS, and JS is inconsistent, which makes the code moderately harder to read than would be ideal. Consider using an IDE which automatically formats code properly so things can be made readable without having to mess with it manually.</p>\n<p><strong>Duplicate IDs are invalid HTML</strong> You have two elements with <code>div id="egg"</code>, which isn't permitted in HTML. The <code>$("#egg")</code> will only select the first one, because jQuery is only expecting one such element to exist in the document. Maybe just completely remove the second one?</p>\n<p><strong>gg?</strong> You have <code>img id="gg"</code>. It's not entirely clear what this refers to just from reading the markup. I initially thought it might be a reference to "good game" and would appear after the game is over, but it's not, it's an image that follows the mouse. Maybe call it <code>mouseImage</code> instead, or something like that?</p>\n<p>Or, you could set the <em>whole cursor</em> to the image <a href=\"https://stackoverflow.com/questions/18551277/using-external-images-for-css-custom-cursors\">via CSS</a>, which might be even better, allowing you to remove that element entirely:</p>\n<pre class=\"lang-css prettyprint-override\"><code>cursor:url(/img/net-3850048_960_720.png), auto;\n</code></pre>\n<p><strong>Smiley face?</strong> You render the smiley by putting it inside a square:</p>\n<pre><code><div class="square"><p>&#128512;</p></div>\n</code></pre>\n<p>and by hiding the <code><p></code> until the game is over. This is very confusing; I'd expect the squares to contain <em>only</em> the dino pictures. Something completely unrelated should be in a separate element, outside of the <code><div class="row"></code>s. It's not at all clear what the purpose of the HTML entity is either - consider using an <code><img></code> instead so it can be understood at a glance.</p>\n<pre><code><img src="smiley.png">\n</code></pre>\n<pre><code>$('img[src="smiley.png"]').css('display', 'block');\n</code></pre>\n<p><strong>Inline CSS</strong> You have a number of inline styles, like</p>\n<pre><code><body style="overflow: hidden;">\n <div id="egg" style="display: none;">\n</div>\n</code></pre>\n<p>Best to separate concerns; better to put them all in one place, in the CSS file, so that you can then do</p>\n<pre><code><body>\n <div id="egg">\n </div>\n</code></pre>\n<p>in the HTML.</p>\n<p><strong>Refuse to run on mobile</strong> Since <code>hover</code> events are required for the app to work, rather than <em>just</em> <code>alert</code>ing that the app should be run on a desktop, consider <em>not running the app at all</em> if mobile is detected. For example, you could do something like:</p>\n<pre><code>if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {\n $('.error').text("Please Play on Desktop PC");\n} else {\n main();\n}\n</code></pre>\n<p>where <code>main</code> runs the main script.</p>\n<p>As shown above, better to display messages to the user in the HTML rather than <code>alert</code>, which <em>blocks</em> the browser and is quite user-unfriendly.</p>\n<p><strong>Readyness</strong> Rather than wrapping everything in:</p>\n<pre><code>$( document ).ready(function() {\n</code></pre>\n<p>Consider using the more standard form nowadays of</p>\n<pre><code>$(function() {\n</code></pre>\n<p>Or, even better, remove it entirely, and use the HTML to ensure the JS only runs once the DOM is populated: either give your script the <code>defer</code> attribute (best option IMO), or move your script to right above the bottom of the <code><body></code>. Then there's no need for <code>$( document ).ready(function() {</code>, or to wait for <code>DOMContentLoaded</code>, or anything like that.</p>\n<p><strong>Images array</strong> Rather than hard-coding:</p>\n<pre><code>var images = ['dino8.png', 'dino1.png', 'dino2.png','dino3.png', 'dino4.png', 'dino5.png', 'dino6.png', 'dino7.png'];\n</code></pre>\n<p>Consider simply choosing a random number from 1 to 8 instead, and interpolating that into the middle of <code>dino#.png</code> (see below).</p>\n<p><strong>randNumb and rand?</strong> What's the difference? It's not obvious at a glance what the difference is or what those variables mean without continuing below. Give them better names that indicate what they're used for:</p>\n<pre><code>const totalImages = 8;\n$('.square').each(function() {\n const widthAndHeight = Math.floor(Math.random() * 71) + 30;\n const src = `img/dino${1 + Math.floor(Math.random() * totalImages)}.png`;\n $(this).append(`<img class="dino" src="${src}" width="${widthAndHeight}%" height="${widthAndHeight}%"`);\n});\n</code></pre>\n<p>You could also use <code>.attr</code> instead of directly concatenating HTML strings - concatenating HTML strings can result in odd display issues, unexpected elements appearing in the DOM, and arbitrary code execution when the input isn't trustworthy. While the input <em>happens</em> to be trustworthy here, it'd probably a good habit to get into to avoid concatenating when possible:</p>\n<pre><code>const src = `img/dino${1 + Math.floor(Math.random() * totalImages)}.png`;\n$('<img />')\n .appendTo(this)\n .attr({\n src,\n width: widthAndHeight + '%',\n height: widthAndHeight + '%',\n });\n</code></pre>\n<p>That's not only better practice, it's also easier to read.</p>\n<p>Note the use of ES2015 syntax - you can count on the vast majority of users to be using browsers that support ES2015. Very few people are still using IE11, and those that are (old business enterprise networks, mostly) are less likely to have overlap with teaching children. If you want IE11 support, the most maintainable solution IMO is to write in (clean, readable, concise) modern syntax and then <a href=\"https://babeljs.io/\" rel=\"nofollow noreferrer\">automatically transpile down to ES5</a> for production.</p>\n<p><strong>End condition</strong> Rather than doing <code>if (x == 50){</code> to check if all dinos have been removed, consider checking whether the <code>.dino</code> selector string returns any elements instead - this'll let you avoid hard-coding the number, and will let you remove the <code>x</code> variable entirely:</p>\n<pre><code>if (!$('.dino').length) {\n // show egg\n}\n</code></pre>\n<p><strong>No need for <code>hover</code></strong> Since you aren't attaching a mouseleave event, the <code>hover</code> handler isn't so appropriate - you only want to listen for <code>mouseenter</code> events:</p>\n<pre><code>$('.dino').on('mouseenter', function() {\n // ...\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T00:42:36.983",
"Id": "250853",
"ParentId": "250838",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "250853",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T18:04:53.910",
"Id": "250838",
"Score": "4",
"Tags": [
"javascript",
"jquery",
"game",
"html"
],
"Title": "Children's Mini Game Handy-Eye Coordination"
}
|
250838
|
<p>I need to parse simple DSLs in a few projects. Since I don't know BNF or other grammars, I figured an alternative would be to use a simple parser generator.</p>
<p>I'm looking for improvements to the lexer/parser in order to be able to use it to parse more complex languages in future projects while keeping a relatively simple interface to define a grammar.</p>
<p>Feedback to increase code quality would be highly appreciated.</p>
<p>I'd also like to know if I'm missing crucial features a lexer/parser would have to include.</p>
<p>If I'm doing anything inherently wrong or do use inappropriate techniques, that would be helpful to know as well.</p>
<p>I'll include a simple usage example at the beginning and post the code and snippet at the bottom. I think in that order it's easier to follow the code.</p>
<p>Here's an example of how to tokenize a basic arithmetic expression like <code>1+2+3*4*5*6+3</code>;</p>
<pre class="lang-javascript prettyprint-override"><code>const tokenDefinitions = [
TokenFactory({type:'Whitespace', ignore: true}).while(/^\s+$/),
TokenFactory({type:'Integer'}).start(/-|\d/).next(/^\d$/),
TokenFactory({type:'Paren'}).start(/^[()]$/),
TokenFactory({type:'Addition'}, true).start(/^\+|-$/),
TokenFactory({type:'Multiplication'}, true).start(/^\*|\\$/),
];
const src = '1 + 2 + 3 * 4 * 5'
const lexer = Lexer(tokenDefinitions);
const tokens = lexer(src).filter(t => !t.ignore);
</code></pre>
<p>Here's an example to parse the tokens to an AST.</p>
<pre><code>const Any = new Driver('Any').match(_ => true);
const Number = new Driver('Number').match(type('Integer')).bind(0, 0);
const RParen = new Driver('RParen').match(value(')')).bind(100, 0);
const Expression = new Driver('Expression').match(value('(')).consumeRight().end(value(')')).bind(0, 99)
const MulOperator = new Driver('Operator').match(type('Multiplication')).consumeLeft(Any).consumeRight().bind(60,60)
const AddOperator = new Driver('Operator').match(type('Addition')).consumeLeft(Any).consumeRight().bind(50,50)
const nodeDefinitions = [
MulOperator,
AddOperator,
Number,
Expression,
RParen,
];
const parse = Parser(nodeDefinitions);
const ast = parse(tokens);
</code></pre>
<p><sub>This example uses left and right binding powers to define the precedence of the multiplication over addition. You can get the same result by using <code>.until</code>, but that feels kind of wrong.</sub></p>
<pre><code>const Any = new Driver('Any').match(_ => true);
const Number = new Driver('Number').match(type('Integer'));
const RParen = new Driver('RParen').match(value(')'));
const Expression = new Driver('Expression').match(value('(')).consumeRight().until(value(')')).end(value(')'))
const MulOperator = new Driver('Operator').match(type('Multiplication')).consumeLeft(Any).consumeRight().until(parentOr(type('Addition')))
const AddOperator = new Driver('Operator').match(type('Addition')).consumeLeft(Any).consumeRight().until(parent)
</code></pre>
<p><sub>In this example, the multiplication operator consumes tokens until it encounters an addition token, or if inside an expression, a right parenthesis.</sub></p>
<p>Both examples produce the following AST.</p>
<pre class="lang-javascript prettyprint-override"><code>[
{
children: [
{ children: [], token: { value: '1' }, id: 'Number' },
{
children: [
{ children: [], token: { value: '2' }, id: 'Number' },
{
children: [
{
children: [
{ children: [], token: { value: '3' }, id: 'Number' },
{
children: [
{
children: [],
token: { value: '4' },
id: 'Number'
},
{
children: [
{
children: [],
token: { value: '5' },
id: 'Number'
},
{
children: [],
token: { value: '6' },
id: 'Number'
}
],
token: { type: 'Multiplication', value: '*' },
id: 'Operator'
}
],
token: { type: 'Multiplication', value: '*' },
id: 'Operator'
}
],
token: { type: 'Multiplication', value: '*' },
id: 'Operator'
},
{ children: [], token: { value: '3' }, id: 'Number' }
],
token: { type: 'Addition', value: '+' },
id: 'Operator'
}
],
token: { type: 'Addition', value: '+' },
id: 'Operator'
}
],
token: { type: 'Addition', value: '+' },
id: 'Operator'
}
]
</code></pre>
<p><sub>You can flatten the recursive structure of the AST by changing the grammar of addition and multiplication tokens to repeatedly parse its RHS while its condition matches by using <code>.repeat</code>, or by using <code>.unfold</code> which recurses first and flattens the structure after parsing the node. This can reduce the size of the AST a lot.</sub></p>
<pre><code>[
{
children: [
{ children: [], token: { value: '1' }, id: 'Number' },
{ children: [], token: { value: '2' }, id: 'Number' },
{
children: [
{ children: [], token: { value: '3' }, id: 'Number' },
{ children: [], token: { value: '4' }, id: 'Number' },
{ children: [], token: { value: '5' }, id: 'Number' },
{ children: [], token: { value: '6' }, id: 'Number' }
],
token: { type: 'Multiplication', value: '*' },
id: 'Operator'
},
{ children: [], token: { value: '3' }, id: 'Number' }
],
token: { type: 'Addition', value: '+' },
id: 'Operator'
}
]
</code></pre>
<pre><code>const AddOperator = new Driver('Operator').match(type('Addition')).consumeLeft(Any).consumeRight().until(parent).repeat()
</code></pre>
<p>Here's an example of how to interpret the AST.<br />
<sub>It doesn't matter if the AST is flattened or not, all versions (bind/until, repeat/unfold) will be interpreted correctly as the semantic doesn't change*</sub></p>
<pre><code>const operators = {
'+': (a,b) => a+b,
'-': (a,b) => a-b,
'*': (a,b) => a*b,
'/': (a,b) => a/b,
};
const hasId = id => token => token.id === id;
const tokenValue = node => node.token.value;
const NrBh = new Behaviour(hasId('Number'), n => +tokenValue(n))
const OpBh = new Behaviour(hasId('Operator'), (node, _eval) => node.children.map(c => _eval(c)).reduce(operators[tokenValue(node)]));
const ExprBh = new Behaviour(hasId('Expression'), (node, _eval) => _eval(node.rhs));
const behaviours = [NrBh, OpBh, ExprBh];
const res = Behaviour.eval(ast[0], behaviours); // 63
</code></pre>
<p>Here's the code for the lexer.</p>
<pre><code>//Matcher.js
const setInstanceProp = (instance, key, value) => (instance[key] = value, instance);
/**
* The Matcher defines multiple regular expressions or functions that are matched against a single character at different positions.
*/
class Matcher {
constructor (transform) {
/** Can be given a transform function that transforms the token value */
if (typeof transform === 'function')
this._transform = transform
}
/** Consumes a character once at the beginning.*/
start (regExp) {return setInstanceProp(this, '_start', regExp)}
/** Consumes a character each step*/
next (regExp) {return setInstanceProp(this, '_next', regExp)}
/** Consumes a character and terminates the current token*/
end (regExp) {return setInstanceProp(this, '_end', regExp)}
/** Consumes characters as long as the regExp matches */
while (regExp) {return setInstanceProp(this, '_while', regExp)}
/** Tests a regex or function against a character */
_test (obj, char) {
if (typeof obj === 'function')
return obj(char);
if (obj instanceof RegExp)
return obj.test(char);
return false;
}
/** Tests a character and token against the defined regexes/functions. Can be given a hint to test a specific regex/fn */
test (char, token = '', hint) {
if (hint === null) return false;
if (hint) return this._test(hint, char)
if (this._start && !token) return this._test(this._start, char);
if (this._next) return this._test(this._next, char);
if (this._while) return this._test(this._while, token + char);
return false;
}
/** Default transform behaviour. Returns the primitive token value */
_transform (token) {
return token;
}
/** Called by the tokenizer to transform the primitive token value to an object*/
transform (token) {
return this._transform(token);
}
}
/** Creates a matcher that transforms the matched token into an object with a prototype that shares common information*/
const TokenFactory = (proto, assign) => new Matcher((value) => {
if (typeof value === 'object') return value
if (assign)
return Object.assign({}, proto, {value})
return Object.assign(Object.create(proto), {value})
});
module.exports = {Matcher, TokenFactory};
</code></pre>
<pre><code>//Lexer.js
const {Matcher} = require('./Matcher');
const Lexer = (def) => (src) => {
return src.split('').reduce((acc, char, i, arr) => {
let [token, lastMatcher, tokens] = acc;
const {_end = null} = lastMatcher; let ret;
if (lastMatcher.test(char, token, _end)) {
ret = [lastMatcher.transform(token+char), new Matcher, tokens];
} else if (lastMatcher.test(char, token)) {
ret = [token+char, lastMatcher,tokens];
} else {
const matcher = def.find(matcher => matcher.test(char));
if (!matcher) throw new Error(`No matcher found for character '${char}'.`);
token && tokens.push(lastMatcher.transform(token));
ret = [char, matcher, tokens];
lastMatcher = matcher;
}
if (i === arr.length - 1) {
tokens.push(lastMatcher.transform(ret[0]));
ret = tokens;
}
return ret;
}, ['', new Matcher, []]);
}
module.exports = {Lexer};
</code></pre>
<p>Here's the code of the parser.</p>
<pre><code>//Driver.js
class Driver {
constructor (id, transform) {
this.id = id;
this._transform = transform;
this.bind();
};
match (token) {
this._match = token;
return this;
}
consumeLeft (token) {
this._consumeLeft = token;
return this;
}
consumeRight (token = true, n = Infinity) {
this._consumeRight = token;
this.n = n;
return this;
}
end (token) {
this._end = token;
return this;
}
unfold () {
this._unfold = true;
return this;
}
until (token, lookAhead = 0) {
this._until = token;
this._lookAhead = lookAhead;
return this;
}
repeat (token) {
this._repeat = true;
return this;
}
test (token, nodes = []) {
let ret;
if (typeof this._match === 'function')
ret = this._match(token);
else if (this._match) {
ret = token.type === this._match || token.value === this._match;
}
if (this._consumeLeft) {
const lhs = nodes.slice().pop();
ret = ret && lhs && (lhs.id === this._consumeLeft.id || this._consumeLeft.test(lhs.token));
}
return ret;
}
transform (node) {
if (typeof this._transform === 'function')
return {...this._transform(node), id: this.id};
return {...node, id: this.id};
}
bind (l = 0, r = 0) {
this.lbp = l;
this.rbp = r;
return this;
}
}
module.exports = {Driver};
</code></pre>
<pre><code>//Parser.js
const Parser = nodeDefinitions => {
const nodes = [];
return function parse (tokens, parents = []) {
if (tokens.length === 0)return [];
const [parent, ...rest] = parents;
let i=0;
do {
const token = tokens.shift();
const node = {children:[]};
const cur = nodeDefinitions.find (d => d.test(token, nodes));
if (!cur) {
throw new Error(`Unexpected token ${JSON.stringify(token)}`);
}
let next = tokens[0]
const nextDriver = next && nodeDefinitions.find (d => d.test(next, nodes));
if (parent && nextDriver && parent.rbp < nextDriver.lbp) {
tokens.unshift(token);
break;
}
next = parent && (parent._lookAhead==0?token:tokens[parent._lookAhead - 1]);
if (parent && parent._until && next && parent._until(next, parents, nodes)) {
tokens.unshift(token);
break;
}
if (cur._consumeLeft) {
const lhs = nodes.pop();
if (!cur.test(token, [lhs]))
throw new Error(`Expected token ${cur._consumeLeft._match} but found ${lhs.token.type} instead. ${cur.name}`)
node.children.push(lhs);
}
if (cur._consumeRight) {
let repeat = false;
do {
parse(tokens, [cur, ...parents]);
const rhs = nodes.shift();
node.children.push(rhs);
if (tokens[0] && cur.test(tokens[0], [node.children[0]])) {
tokens.shift();
repeat = true;
} else {
repeat = false;
}
} while (repeat);
}
node.token = token;
if (cur._unfold) {
const rhs = node.children.slice(-1)[0];
const un = rhs.children;
if (node.token.value === rhs.token.value) {
node.children = [node.children[0], ...un];
}
}
if (cur._end && cur._end(tokens[0] || {}, cur, nodes)) {
node.end = tokens.shift();
}
nodes.push(cur.transform(node));
if (parent && ++i === parent.n) break;
} while (tokens.length);
return nodes;
}
}
module.exports = {Parser};
</code></pre>
<p>Here's the code for the interpreter.</p>
<pre><code>//Behaviour.js
class Behaviour {
static eval (ast, behaviours) {
const node = ast;
const beh = behaviours.find(b => b.testFn(ast));
if (!beh)
throw new Error(`No behaviour found for node ${JSON.stringify(node)}`)
return beh.evalFn(node, (node, _behaviours = behaviours) => {
const val = Behaviour.eval(node, _behaviours)
return val;
});
}
constructor (testFn, evalFn) {
this.testFn = testFn;
this.evalFn = evalFn;
}
}
</code></pre>
<p>Here's a fiddle to run the example.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const tokenDefinitions = [
TokenFactory({type:'Whitespace', ignore: true}).while(/^\s+$/),
TokenFactory({type:'Integer'}).start(/-|\d/).next(/^\d$/),
TokenFactory({type:'Paren'}).start(/^[()]$/),
TokenFactory({type:'Addition'}, true).start(/^\+|-$/),
TokenFactory({type:'Multiplication'}, true).start(/^\*|\\$/),
];
const src = '1 + 2 + 3 * 4 * 5 * 6 + 3'
console.log ('Source', src);
const lexer = Lexer(tokenDefinitions);
const tokens = lexer(src).filter(t => !t.ignore);
console.log("Tokens", tokens);
const type = type => token => token.type === type;
const value = value => token => token.value === value;
const parent = (token, parents, nodes) => parents[1] && parents[1]._until(token, parents.slice(1), nodes) ;
const or = (...fns) => (token, parents, nodes) => fns.reduce((a, fn) => a || fn(token, parents, nodes), false);
const and = (...fns) => (token, parents, nodes) => fns.reduce((a, fn) => a && fn(token, parents, nodes), true);
const parentOr = fn => or(parent, fn);
const keyword = token => type('Identifier')(token) && keywords.some(k => value(k)(token));
// const Any = new Driver('Any').match(_ => true);
// const Number = new Driver('Number').match(type('Integer')).bind(0, 0);
// const RParen = new Driver('RParen').match(value(')')).bind(100, 0);
// const Expression = new Driver('Expression').match(value('(')).consumeRight().end(value(')')).bind(0, 99)
// const MulOperator = new Driver('Operator').match(type('Multiplication')).consumeLeft(Any).consumeRight().bind(60,60)
// const AddOperator = new Driver('Operator').match(type('Addition')).consumeLeft(Any).consumeRight().bind(50,50)
const Any = new Driver('Any').match(_ => true);
const Number = new Driver('Number').match(type('Integer'));
const RParen = new Driver('RParen').match(value(')'));
const Expression = new Driver('Expression').match(value('(')).consumeRight().until(value(')')).end(value(')'))
const MulOperator = new Driver('Operator').match(type('Multiplication')).consumeLeft(Any).consumeRight().until(or(parent,type('Multiplication'),type('Addition'))).repeat()
const AddOperator = new Driver('Operator').match(type('Addition')).consumeLeft(Any).consumeRight().until(parentOr(type('Addition'))).repeat();
const nodeDefinitions = [
MulOperator,
AddOperator,
Number,
Expression,
RParen,
];
const parse = Parser(nodeDefinitions);
const ast = parse(tokens);
console.log("AST", ast);
const operators = {
'+': (a,b) => a+b,
'-': (a,b) => a-b,
'*': (a,b) => a*b,
'/': (a,b) => a/b,
};
const hasId = id => token => token.id === id;
const tokenValue = node => node.token.value;
const NrBh = new Behaviour(hasId('Number'), n => +tokenValue(n))
const OpBh = new Behaviour(hasId('Operator'), (node, _eval) => node.children.map(c => _eval(c)).reduce(operators[tokenValue(node)]));
const ExprBh = new Behaviour(hasId('Expression'), (node, _eval) => _eval(node.rhs));
const behaviours = [NrBh, OpBh, ExprBh];
const res = Behaviour.eval(ast[0], behaviours);
console.log ("Result", res)</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script>
const setInstanceProp = (instance, key, value) => (instance[key] = value, instance);
class Matcher {
constructor (transform) {
if (typeof transform === 'function')
this._transform = transform
}
start (r) {return setInstanceProp(this, '_start', r)}
next (r) {return setInstanceProp(this, '_next', r)}
end (r) {return setInstanceProp(this, '_end', r)}
while (r) {return setInstanceProp(this, '_while', r)}
_test (obj, char) {
if (typeof obj === 'function')
return obj(char);
if (obj instanceof RegExp)
return obj.test(char);
return false;
}
test (char, token = '', hint) {
if (hint === null) return false;
if (hint) return this._test(hint, char)
if (this._start && !token) return this._test(this._start, char);
if (this._next) return this._test(this._next, char);
if (this._while) return this._test(this._while, token + char);
return false;
}
_transform (token) {
return token;
}
transform (token) {
return this._transform(token);
}
}
const TokenFactory = (proto, assign) => new Matcher((value) => {
if (typeof value === 'object') return value
if (assign)
return Object.assign({}, proto, {value})
return Object.assign(Object.create(proto), {value})
});
const Lexer = (def) => (src) => {
return src.split('').reduce((acc, char, i, arr) => {
let [token, lastMatcher, tokens] = acc;
const {_end = null} = lastMatcher; let ret;
if (lastMatcher.test(char, token, _end)) {
ret = [lastMatcher.transform(token+char), new Matcher, tokens];
} else if (lastMatcher.test(char, token)) {
ret = [token+char, lastMatcher,tokens];
} else {
const matcher = def.find(matcher => matcher.test(char));
if (!matcher) throw new Error(`No matcher found for character '${char}'.`);
token && tokens.push(lastMatcher.transform(token));
ret = [char, matcher, tokens];
lastMatcher = matcher;
}
if (i === arr.length - 1) {
tokens.push(lastMatcher.transform(ret[0]));
ret = tokens;
}
return ret;
}, ['', new Matcher, []]);
}
class Driver {
constructor (id, transform) {
this.id = id;
this._transform = transform;
this.bind();
};
match (token) {
this._match = token;
return this;
}
consumeLeft (token) {
this._consumeLeft = token;
return this;
}
consumeRight (token = true, n = Infinity) {
this._consumeRight = token;
this.n = n;
return this;
}
end (token) {
this._end = token;
return this;
}
unfold () {
this._unfold = true;
return this;
}
until (token, lookAhead = 0) {
this._until = token;
this._lookAhead = lookAhead;
return this;
}
repeat (token) {
this._repeat = true;
return this;
}
test (token, nodes = []) {
let ret;
if (typeof this._match === 'function')
ret = this._match(token);
else if (this._match) {
ret = token.type === this._match || token.value === this._match;
}
if (this._consumeLeft) {
const lhs = nodes.slice().pop();
ret = ret && lhs && (lhs.id === this._consumeLeft.id || this._consumeLeft.test(lhs.token));
}
return ret;
}
transform (node) {
if (typeof this._transform === 'function')
return {...this._transform(node), id: this.id};
return {...node, id: this.id};
}
bind (l = 0, r = 0) {
this.lbp = l;
this.rbp = r;
return this;
}
}
const Parser = nodeDefinitions => {
const nodes = [];
return function parse (tokens, parents = []) {
if (tokens.length === 0)return [];
const [parent, ...rest] = parents;
let i=0;
do {
const token = tokens.shift();
const node = {children:[]};
const cur = nodeDefinitions.find (d => d.test(token, nodes));
if (!cur) {
throw new Error(`Unexpected token ${JSON.stringify(token)}`);
}
let next = tokens[0]
const nextDriver = next && nodeDefinitions.find (d => d.test(next, nodes));
if (parent && nextDriver && parent.rbp < nextDriver.lbp) {
tokens.unshift(token);
break;
}
next = parent && (parent._lookAhead==0?token:tokens[parent._lookAhead - 1]);
if (parent && parent._until && next && parent._until(next, parents, nodes)) {
tokens.unshift(token);
break;
}
if (cur._consumeLeft) {
const lhs = nodes.pop();
if (!cur.test(token, [lhs]))
throw new Error(`Expected token ${cur._consumeLeft._match} but found ${lhs.token.type} instead. ${cur.name}`)
node.children.push(lhs);
}
if (cur._consumeRight) {
let repeat = false;
do {
parse(tokens, [cur, ...parents]);
const rhs = nodes.shift();
node.children.push(rhs);
if (tokens[0] && cur.test(tokens[0], [node.children[0]])) {
tokens.shift();
repeat = true;
} else {
repeat = false;
}
} while (repeat);
}
node.token = token;
if (cur._unfold) {
const rhs = node.children.slice(-1)[0];
const un = rhs.children;
if (node.token.value === rhs.token.value) {
node.children = [node.children[0], ...un];
}
}
if (cur._end && cur._end(tokens[0] || {}, cur, nodes)) {
node.end = tokens.shift();
}
nodes.push(cur.transform(node));
if (parent && ++i === parent.n) break;
} while (tokens.length);
return nodes;
}
}
class Behaviour {
static eval (ast, behaviours) {
const node = ast;
const beh = behaviours.find(b => b.testFn(ast));
if (!beh)
throw new Error(`No behaviour found for node ${JSON.stringify(node)}`)
return beh.evalFn(node, (node, _behaviours = behaviours) => {
const val = Behaviour.eval(node, _behaviours)
return val;
});
}
constructor (testFn, evalFn) {
this.testFn = testFn;
this.evalFn = evalFn;
}
}
</script></code></pre>
</div>
</div>
</p>
<hr />
<p>Edit:</p>
<p>A few thoughts from my side. I don't really like prefixing methods or properties with a <code>_</code>. I think I can move the regular expression into an own object as they aren't tied to the instance. I think I can get rid of the <code>_transform</code> method by overriding <code>transform</code> in the constructor. I just thought that storing a function in a property that gets called by a class method is convenient since you could use it to validate input. If there's a cleaner way of doing this, that would be nice. I could use a <code>Map</code> store the function, then I wouldn't have to expose a <code>_transform</code> property.</p>
<p>I think that the binding powers should be changed to compare the current token against the next token. Currently, they work as follows. Given the source <code>1 + 2 * 3</code> and binding powers <em>50/50, 60/60</em> for the tokens <em>+</em> and *, the + token will compete with the * token over the <em>2</em> token. I thought that's easier to grasp, but it turns out that you can't use it to break out of the current parsing step, without using <code>until</code>. Which is a likely need. f.e. using <code>)</code> to designate the end of an expression. This only works if I compare the binding powers of two adjacent tokens.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T04:46:51.590",
"Id": "495326",
"Score": "2",
"body": "My biggest feedback: add documentation to the lexer and parser! Writing your own parser generator is NOT more readable and maintainable than writing a custom parser, unless you write very clearly what exactly each piece is supposed to do, and it is foolproof."
}
] |
[
{
"body": "<h3>Disclaimer: Not a Code Reviewer</h3>\n<p>Your code looks pretty good! Just briefly commenting:</p>\n<ul>\n<li><p>My guess is that maybe you might want to design some low-complexity algorithms to do the parsing (if not using an already developed parser – which would have been my first choice – browsing through GitHub), rather than using operational-intensive string manipulations with <a href=\"https://stackoverflow.com/questions/764247/why-are-regular-expressions-so-controversial\">fledgling regular expressions</a>.</p>\n</li>\n<li><p>Here is just an example using stack:</p>\n</li>\n</ul>\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 parser = function(s) {\n\n if (s.length === 0) {\n return 0;\n }\n\n\n let stack = [];\n let operation = \"+\";\n\n for (let index = 0, num = 0; index <= s.length; ++index) {\n if (s[index] === ' ') {\n continue;\n }\n\n\n if (s[index] >= '0' && s[index] <= '9') {\n num *= 10;\n num += parseInt(s[index]);\n continue;\n }\n\n if (operation === '+') {\n stack.push(num);\n\n } else if (operation === '-') {\n stack.push(-num);\n\n } else if (operation === '*') {\n stack.push(stack.pop() * num);\n\n } else if (operation === '/') {\n stack.push(Math.trunc(stack.pop() / num));\n }\n\n operation = s[index];\n num = 0;\n }\n\n return stack.reduce((a, b) => a + b, 0);\n};\n\n\nconsole.log(parser(\" 1 + 2 + 3 * 4 * 5 * 6 + 3 \"));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h3>Happy Coding!! ( ˆ_ˆ )</h3>\n<hr />\n<h3>Reference</h3>\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/63745538/prefix-calculator-using-stack-in-javascript\">Prefix calculator using stack in javascript</a></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T05:25:35.897",
"Id": "251639",
"ParentId": "250839",
"Score": "2"
}
},
{
"body": "<p>I haven’t done much thinking about lexers since I was a university student 14 years ago and was in a compilers class. I have been working with Javascript since then.</p>\n<p>Overall the code looks well-written. Variables are declared well using <code>const</code> and <code>let</code> appropriately. Many other ES6 features appear to be applied appropriately. Strict comparisons are utilized to avoid needless type coercions.</p>\n<p>I agree with removing the underscores from method and property names. This would follow recommendations of popular style guides- e.g. <a href=\"https://github.com/airbnb/javascript#naming--leading-underscore\" rel=\"nofollow noreferrer\">AirBNB</a>.</p>\n<p>I see these lines of code in the <code>Parser</code> function <code>parse()</code></p>\n<blockquote>\n<pre><code>let repeat = false;\ndo {\n parse(tokens, [cur, ...parents]);\n const rhs = nodes.shift();\n node.children.push(rhs);\n if (tokens[0] && cur.test(tokens[0], [node.children[0]])) {\n tokens.shift();\n repeat = true;\n } else {\n repeat = false;\n }\n} while (repeat);\n</code></pre>\n</blockquote>\n<p>The <code>do</code> loop could be changed to a <code>for</code> loop, and variable <code>rhs</code> is only used once after assignment so it doesn’t need to be stored.</p>\n<pre><code>for (let repeat = true; repeat; ) {\n parse(tokens, [cur, ...parents]);\n node.children.push(nodes.shift());\n if (tokens[0] && cur.test(tokens[0], [node.children[0]])) {\n tokens.shift();\n repeat = true;\n } else {\n repeat = false;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T06:11:31.510",
"Id": "251641",
"ParentId": "250839",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T18:19:12.420",
"Id": "250839",
"Score": "11",
"Tags": [
"javascript",
"parsing",
"ecmascript-6",
"lexical-analysis"
],
"Title": "A simple parser generator"
}
|
250839
|
<p>Any critique of my implementation of Merge sort would be much appreciated! I tested it using a driver function (shown below), and everything works. However, it still feels unwieldy, I am a beginner so I really want to hear any criticisms, constructive or not :)</p>
<pre><code>def inplace_merge_sort( lst, start = 0 , end = None ):
def inplace_merge( lst1_start, lst1_end , lst2_start, lst2_end ): #needs to take in two sets of unsorted indices
start, end = lst1_start, lst2_end
for _ in range( (end - start) ):
if(lst[lst1_start] < lst[lst2_start]):
lst1_start += 1
else:
lst.insert(lst1_start , lst[lst2_start])
del lst[lst2_start + 1]
lst1_start += 1
lst2_start += 1
if( lst1_start == lst2_start or lst2_start == lst2_end):
break
return start, end #returns indices of sorted newly sublist
if( len(lst) == 1 or len(lst) == 0): #catches edge cases
return lst
if end is None: end = len(lst) #so I don't have to input parameters on first call
length_sublist = end - start
if( length_sublist > 1):
start1, end1 = inplace_merge_sort( lst, start, (end + start) // 2 )
start2, end2 = inplace_merge_sort( lst, (end + start) // 2 , end )
return inplace_merge(start1, end1, start2, end2)
else:
return start, end
</code></pre>
<p>Here is the test function</p>
<pre><code>def inplace_driver_helper(f_n):
def modified_list_returner( lst ):
f_n(lst)
return lst
return modified_list_returner
def driver(f_n):
# NICK I added these two test cases to catch some popular edge cases.
assert f_n([]) == []
assert f_n([4]) == [4]
assert f_n([1,2,3]) == [1,2,3]
assert f_n([3,2,1]) == [1,2,3]
assert f_n([1,2,3,1,2,3]) == [1,1,2,2,3,3]
assert f_n([1,2,3,1,1,2,3]) == [1,1,1,2,2,3,3]
assert f_n([-1,0,46,2,3,1,2,3]) == [-1,0,1,2,2,3,3,46]
</code></pre>
<p>and when we run this,</p>
<pre><code>if __name__ == '__main__':
driver(inplace_driver_helper(inplace_merge_sort))
print('done')
</code></pre>
<p>The output is 'done'!</p>
|
[] |
[
{
"body": "<p>Welcome to Code Review!</p>\n<h2>PEP-8</h2>\n<p>Python has a style guide to help developers write clean, maintainable and readable code. It is referred to <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">as PEP-8</a>. A few points of note:</p>\n<ol>\n<li>Avoid extraneous whitespace in the following situations:</li>\n<li>Use 4 spaces per indentation level.</li>\n</ol>\n<h2>Type hinting</h2>\n<p>Yet another <a href=\"https://www.python.org/dev/peps/pep-0484/\" rel=\"noreferrer\">PEP (PEP-484) for</a> putting in type hints for your variables and function parameters.</p>\n<h2>Comments</h2>\n<p>Except for the comment in testing driver about corner cases, all other comments are actually not needed. The code explains what the comments are trying to say anyway.</p>\n<h2>Loop over range</h2>\n<p>You have a loop with range:</p>\n<pre><code>for _ in range( (end - start) ):\n</code></pre>\n<p>where you actually make use of <code>lst1_start</code>. Why not start iterating from this index itself?</p>\n<h2>Names</h2>\n<p>The variable names: <code>length_sublist</code>, <code>lst1_start/end</code> and similarly <code>lst2_start/end</code> are more readable (and sensible) as <code>sublist_length</code>, <code>start1/end1</code>, <code>start2/end2</code>. Since you do not have 2 different lists anywhere, <code>lst1/2</code> are more confusing.</p>\n<h2>Testing</h2>\n<p>The driver for your test environment requires its own wrapper, which the testing suite needs to incorporate. This feels wrong, and should be handled by the test driver itself. Also, python provides an excellent <a href=\"https://docs.python.org/3.8/library/unittest.html\" rel=\"noreferrer\">testing module, <code>unittest</code></a>. For the driver:</p>\n<pre><code>@inplace_driver_helper\ndef driver(f_n):\n # rest of your code\n</code></pre>\n<p>is enough.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T22:26:29.877",
"Id": "250846",
"ParentId": "250842",
"Score": "8"
}
},
{
"body": "<ul>\n<li>Merge is usually O(m) time, where m is the number of elements involved in the merge. Due to your insertions and deletions, it's rather O(mn), where n is the length of the entire list. That makes your whole sort O(n^2 log n) time instead of mergesort's usual O(n log n).</li>\n<li>You call it inplace sort, which suggests it doesn't return anything, but you do return the list if it's short and you return some start/end indices otherwise. Rather inconsistent and confusing. I'd make it not return anything (other than the default <code>None</code>).</li>\n<li>Your function offers to sort only a part of the list, but you don't test that.</li>\n<li>You use quite a few rather long variable names. I'd use shorter ones, especially <code>i</code> and <code>j</code> for the main running indices.</li>\n<li>You insert before you delete. This might require the entire list to be reallocated and take O(n) extra space if it doesn't have an extra spot overallocated. Deleting (or popping) before inserting reduces that risk and thus increases the chance that you only take O(log n) extra space.</li>\n<li>Mergesort ought to be stable. Yours isn't, as in case of a tie, your merge prefers the right half's next value. For example, you turn <code>[0, 0.0]</code> into <code>[0.0, 0]</code>.</li>\n</ul>\n<p>A modified version:</p>\n<pre><code>def inplace_merge_sort(lst, start=0, stop=None):\n """Sort lst[start:stop]."""\n\n def merge(i, j, stop):\n """Merge lst[i:j] and lst[j:stop]."""\n while i < j < stop:\n if lst[j] < lst[i]:\n lst.insert(i, lst.pop(j))\n j += 1\n i += 1\n\n if stop is None:\n stop = len(lst)\n\n middle = (start + stop) // 2\n if middle > start:\n inplace_merge_sort(lst, start, middle)\n inplace_merge_sort(lst, middle, stop)\n merge(start, middle, stop)\n</code></pre>\n<p>Oh, I renamed <code>end</code> to <code>stop</code>, as that's what Python mostly uses, for example:</p>\n<pre><code>>>> help(slice)\nHelp on class slice in module builtins:\n\nclass slice(object)\n | slice(stop)\n | slice(start, stop[, step])\n</code></pre>\n<pre><code>>>> help(list.index)\nHelp on method_descriptor:\n\nindex(self, value, start=0, stop=9223372036854775807, /)\n</code></pre>\n<pre><code>>>> help(range)\nHelp on class range in module builtins:\n\nclass range(object)\n | range(stop) -> range object\n | range(start, stop[, step]) -> range object\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T15:19:59.390",
"Id": "493573",
"Score": "0",
"body": "Thank you, this is so much cleaner! To confirm my understanding, your new function fixes the return issue (bullet two) because now if the length of the sub-list is <1 the function just does nothing.\n \nAlso a second question I had regarding bullet one, would your new function still be O(mn) because insert and pop operations are linear? Would a way around this be to use a Linked List or something?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T15:29:51.877",
"Id": "493576",
"Score": "1",
"body": "@JosephGutstadt Yes, as I don't have an explicit `return ...`, it only returns the default `None`. Not the list and not the start/end. Yes, the complexity is still the same, as I kept your insert/delete way (it's the only thing that makes it different from normal implementations, and thus the only thing that makes it interesting :-). And if the data is *given* as a linked list, then yes, you can merge with O(m) time and O(1) space. Of course if you're given a `list` and then convert it to some linked list, that extra linked list then costs O(n) space."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T15:48:21.727",
"Id": "493577",
"Score": "0",
"body": "Nice that makes sense, but wait if it was a LinkedList wouldn't the List accesors inside of the merge function take extra time? Sorry just trying to figure out how inplace merge could be O(log(n)*n) in time, since regular merge is"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T15:53:23.957",
"Id": "493580",
"Score": "1",
"body": "@JosephGutstadt What do you mean with list accessors? Like `lst[i]`? That would cost extra time, yes. Which is why you wouldn't do that :-). You'd work with references to the current list nodes, so accessing their values is O(1)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T15:56:50.487",
"Id": "493581",
"Score": "0",
"body": "yes that was what I was talking about :). I think that makes sense, so at a high level we would replace the start, middle, and stop indices with actual pointers to parts in the LL?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T15:57:34.600",
"Id": "493583",
"Score": "0",
"body": "@JosephGutstadt Yes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T16:48:16.617",
"Id": "493713",
"Score": "0",
"body": "\"Deleting (or popping) before inserting reduces that risk and thus increases the chance that you only take O(log n) extra space.\" While technically true, this doesn't affect big-O, and it's unlikely to matter; both `insert` and `del` are `O(n)` operations; even when no reallocation is needed, they need to move every element above the point of insertion/deletion. Sure, the real work might drop from `n` (in the rare cases the `insert` requires a realloc) to `n/2` (on average), but most of the time you wouldn't be paying the `n` anyway, and you still need to pay the `n/2` regardless."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T18:36:09.857",
"Id": "493719",
"Score": "0",
"body": "@ShadowRanger Not sure why you're talking about *time* there. I'm talking about *space* there. Note that the OP even put \"space efficiency\" into the title. And they're clearly trying to use little extra space. So I'd say space usage really *does* matter here. And in most cases they will use only O(log n) extra space, especially when they delete/pop before inserting. My bullet point about *time* complexity is four bullet points further up and already contains what you just said."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-25T16:38:46.047",
"Id": "494267",
"Score": "0",
"body": "hey superb, was just looking at this again, shouldn't we replace \"lst.insert(i, lst.pop(j))\" with something like lst[i], lst[j] = lst[j], lst[i]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-25T17:22:14.383",
"Id": "494274",
"Score": "0",
"body": "@JosephGutstadt And then do what?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-25T18:43:43.743",
"Id": "494277",
"Score": "0",
"body": "I think that is sufficient, because swapping the two elements is constant time, whereas insert and delete is n time?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-25T19:41:11.123",
"Id": "494281",
"Score": "0",
"body": "@JosephGutstadt Sure, it becomes faster, but it also becomes wrong. So how do you make up for that?"
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T00:36:05.730",
"Id": "250852",
"ParentId": "250842",
"Score": "16"
}
},
{
"body": "<ul>\n<li><p>You define <code>inplace_merge()</code> inside the definition of <code>inplace_merge_sort()</code>, but it doesn't use any of the context of <code>inplace_merge_sort()</code>, so it isn't necessary.</p>\n<p>If you defined it outside of the definition (perhaps with a leading underscore in the identifier to warn clients it was not meant to be used directly), you would get three advantages:</p>\n<ul>\n<li>The definition would only be executed once on import, and not on every call.</li>\n<li>It could be tested directly.</li>\n<li>The <code>start</code> and <code>end</code> identifiers wouldn't hide other identifiers of the same name, and risk confusing a reader about which they referred to.</li>\n</ul>\n</li>\n<li><p>If you replaced:</p>\n<pre><code> if( len(lst) == 1 or len(lst) == 0): #catches edge cases\n</code></pre>\n<p>with</p>\n<pre><code> if len(lst) <= 1:\n</code></pre>\n</li>\n</ul>\n<p>then the length wouldn't need to be calculated twice (which, to be fair, is probably not a slow operation).</p>\n<ul>\n<li>I agree with other answers that there should be no return value, but if there is, you should be testing it. (In fact, I would test that it always returns None.)</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T10:53:12.153",
"Id": "493553",
"Score": "1",
"body": "What do you mean with \"doesn't use any of the context\"? It does use `lst`. Very good points, though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T11:21:09.407",
"Id": "493557",
"Score": "0",
"body": "@superbrain: *squints* Oh dear. You are absolutely right. Sorry to the OP. I would still recommend moving it out, but a speed test might be worthwhile to see if the extra parameter requited makes it take longer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T11:30:14.447",
"Id": "493559",
"Score": "1",
"body": "I do see a significant speed difference in [a pure test](https://repl.it/repls/DemandingLoyalVisitors#main.py), but I suspect in the real code with the high merge costs, it'll be invisible. But might make a slight noticeable difference with a normal merge."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T12:08:07.987",
"Id": "493560",
"Score": "1",
"body": "@superbrain: That timing test supports my naive recommendation to move the function out (presumably because of the reason I cited: \"The definition would only be executed once on import, and not on every call.\") But based on your observation that `lst` is used in the function, an additional `lst` parameter would need to be added to the function, and that may have a greater impact (because it is frequently called) that outweighs the small benefit. [A timing test confirmed at about 10-20 calls, the cost of the param outweighs the cost of the definition.]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T12:31:05.810",
"Id": "493561",
"Score": "0",
"body": "Right, a test [with a list](https://repl.it/repls/QuickwittedExcellentRule#main.py) is more relevant. The nested function seems to suffer *more* from that, though."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T08:47:40.710",
"Id": "250863",
"ParentId": "250842",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T19:40:39.017",
"Id": "250842",
"Score": "13",
"Tags": [
"python",
"beginner",
"sorting",
"mergesort"
],
"Title": "Python3 - merge sort, O(n) space efficiency"
}
|
250842
|
<p>Can you please give feedback on my C++ code so I can get better at writing code? I want a code that is well written.</p>
<p>This Code uses the cstdio include for good performance and cstdint include because it has the int8_t data type to save memory. What this code does is if you type a number it will output something like I don't know how to describe:</p>
<pre><code>#include <cstdio>
#include <cstdint>
int main()
{
int8_t input {};
printf("Welcome Type 1 or 2 or 3: ");
scanf("%i", &input);
switch(input)
{
case 0:
printf("OK!");
break;
case 1:
printf("Yuo kown tsih is Cdeo");
break;
case 2:
printf("Ediot Besh yor stoped");
break;
case 3:
printf("WhY dId YoU eVeN cHoOsE tHiS");
break;
case -9:
printf("01001110 01001111 01010100 00100000 01001100 01000101 01000111 01001001 01010100");
break;
default:
printf("idk what to output");
break;
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T21:28:19.413",
"Id": "493529",
"Score": "1",
"body": "This is really weird code....What does the third phrase mean? (Case 2)"
}
] |
[
{
"body": "<h1>Don't optimize prematurely</h1>\n<blockquote>\n<p>This Code uses the cstdio include for good performance</p>\n</blockquote>\n<p>If you write C++ code, it is better to use the C++ way of doing things. While <code>stdio</code> is generally slightly faster than <code>iostream</code>s, if printing to standard output is not the performance critical part of your program, you shouldn't switch to <code>printf()</code>, as you lose all of the benefits of <code>iostream</code>s, like type safety and interoperability with other C++ features.</p>\n<p>Since you tagged the question C++20, you should know that <a href=\"https://en.cppreference.com/w/cpp/utility/format/format\" rel=\"noreferrer\"><code>std::format</code></a> is even faster than <code>stdio</code> at formatting output, and combines the best of both worlds.</p>\n<p>In the code you posted, you only output string literals, so no formatting is involved and likely all three methods will perform similarly.</p>\n<h1>Type safety</h1>\n<p>I already mentioned that <code>stdio</code> is less type safe. And indeed you have an error: <code>scanf("%i", ...)</code> expects a pointer to an <code>int</code>, not an <code>int8_t</code>. This means you potentially overwrite the stack here. This problem would not have happened with <code>iostream</code>s, although <code>std::cin >> input</code> will likely not give the result you expect. When reading in an integer, just use <code>int</code>.</p>\n<p>Again, this is likely premature and misguided optimization. A single <code>int8_t</code> will not be more efficient than an <code>int</code>, and in fact might be less efficient. Only if you store large amounts of values, such as in an array, will it make sense to use small integer types to save memory space and bandwidth.</p>\n<h1>Don't forget to add newlines</h1>\n<p>You print strings without <code>\\n</code> at the end. This might cause the output to not appear immediately (standard output is usually line-buffered), and the next print statement will print on the same line, which is probably not what you want.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T21:44:12.607",
"Id": "493530",
"Score": "4",
"body": "Good review for what is there, but I don't think I would have answered, since it looks like a troll is at work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T21:47:31.483",
"Id": "493531",
"Score": "2",
"body": "I was unsure whether to answer as well, but it does have value in case the OP is legitemately interested in a review or if another beginner programmer finds this post somehow."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T21:32:23.530",
"Id": "250845",
"ParentId": "250844",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T21:18:04.163",
"Id": "250844",
"Score": "-7",
"Tags": [
"c++",
"gcc"
],
"Title": "Can you please give feedback on my C++ Code?"
}
|
250844
|
<p><em>This is a Hackerrank problem (<a href="https://www.hackerrank.com/challenges/sparse-arrays/problem" rel="noreferrer">https://www.hackerrank.com/challenges/sparse-arrays/problem</a>)</em>.</p>
<p>We're given an array of strings and an array of queries, and have to return an array of the number of occurrences of each query in the array of strings.
For example: s = ['ab', 'abc', 'aba', 'ab']. q = ['ab', atr', 'abc]. We need to return [2, 0, 1].</p>
<p>The constraints are <code>1 <= n <= 1000</code>, <code>1 <= q <= 1000</code>, where <code>n</code> and <code>q</code> are the number of strings and queries respectively, and <code>1 <= |strings[i]|, |queries[i]| <= 20</code>.</p>
<p><strong>Here is my code</strong>:</p>
<pre><code>def matchingStrings(strings, queries):
results = []
dic = {q:0 for q in queries}
for s in strings:
if s in dic: dic[s] += 1
for q in queries:
if q in dic: results.append(dic[q])
return results
</code></pre>
<p>Is there anything I can optimize? Speed, memory usage? Anything else?</p>
|
[] |
[
{
"body": "<p>Any time you are using a dict, and you need to do something special the first time a key is used, take a look at <a href=\"https://docs.python.org/3.7/library/collections.html#collections.defaultdict\" rel=\"noreferrer\"><code>collections.defaultdict()</code></a>.</p>\n<pre><code>from collections import defauldict\n\ndef matchingStrings(strings, queries):\n results = []\n\n counts = defaultdict(int)\n for s in strings:\n counts[s] += 1\n\n results = [counts[q] for q in queries]\n\n return results\n</code></pre>\n<p>Any time you need to count things, take a look at <a href=\"https://docs.python.org/3.7/library/collections.html#collections.Counter\" rel=\"noreferrer\"><code>collections.Counter()</code></a>.</p>\n<pre><code>from collections import Counter\n\ndef matchingStrings(strings, queries):\n counts = Counter(strings)\n return [counts[q] for q in queries]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T22:47:44.240",
"Id": "250848",
"ParentId": "250847",
"Score": "8"
}
},
{
"body": "<ul>\n<li><code>if q in dic</code> is pointless. You initialized <code>dic</code> so that it does have all queries.</li>\n<li><code>dic = dict.fromkeys(queries, 0)</code> should be a bit faster.</li>\n<li><code>dic</code> is not a particularly meaningful name, <code>counter</code> or <code>ctr</code> would be better.</li>\n<li>Creating <code>results</code> at the start of the function gives the false impression that it's needed there already. I'd create it right before the loop that builds it. Then you'd have the complete counting part first, and the complete querying part afterwards. Or better yet, ...</li>\n<li>... use a list comprehension, which is faster and nicer.</li>\n<li>Python already has a <code>Counter</code> class that does a lot for you and is probably faster.</li>\n</ul>\n<pre><code>from collections import Counter\n\ndef matchingStrings(strings, queries):\n ctr = Counter(strings)\n return [ctr[q] for q in queries]\n</code></pre>\n<p>For fun: 1000*1000 isn't super big, and HackerRank's calling code really only needs an iterable, so... this also gets accepted:</p>\n<pre><code>def matchingStrings(strings, queries):\n return map(strings.count, queries)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T14:05:21.297",
"Id": "493570",
"Score": "0",
"body": "I'll buy that a list comp is nicer, but faster? That's more difficult to claim. I'd enjoy looking at a profile."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T14:08:08.520",
"Id": "493572",
"Score": "0",
"body": "@Reinderien It's common knowledge and I've done that comparison too many times. Since you apparently never have, I encourage you to do it now :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T15:51:14.157",
"Id": "493578",
"Score": "0",
"body": "@Reinderien Btw, after seeing some people claim that list comprehension is *always* faster, a while ago I even *tried* to find a case where it isn't. I thought maybe I could relatively slow down the list comp by using outside variables so it would be a more expensive lookup or so. I failed. Whatever I tried, list comp was always significantly faster."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T15:11:30.653",
"Id": "493936",
"Score": "0",
"body": "Without diving into a profiling session myself, there is ample evidence that some comprehensions are slower; take https://stackoverflow.com/a/27906182/313768 for instance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T15:56:01.220",
"Id": "493946",
"Score": "0",
"body": "@Reinderien Sure, if you artificially slow them down like that with something you're not doing in the loop version. But can you show a *proper* comparison where they're slower?"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T22:49:54.260",
"Id": "250849",
"ParentId": "250847",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "250849",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T22:30:55.680",
"Id": "250847",
"Score": "7",
"Tags": [
"python",
"algorithm",
"strings",
"array",
"hash-map"
],
"Title": "Number of occurrences of strings in array"
}
|
250847
|
<p>Library management system is a object oriented program that takes care of the basic housekeeping of a library.
This is the third part of a series. The first iteration of the project is found <a href="https://codereview.stackexchange.com/questions/250668/library-management-system-with-oop">here</a> and the second iteration is also found <a href="https://codereview.stackexchange.com/questions/250769/library-management-system-oop-with-c-part2-of-a-series">here</a></p>
<p>The major actors are the Librarian, Member, and the System.</p>
<h3>Major Concern</h3>
<p>I made member and Librarian friends of the system class and also composed the system class with Librarian and Member. I felt "System is composed of a Librarian and members" sounds better than "System is a friend of a Librarian and members". Does this follow the common design patterns?</p>
<p>In my previous post, I wasn't cleared well enough on why a std::vector should be preferable than std::list in this situation due to the fact that the system would perform insertion frequently. Would std::vector be more scalable and versatile whilst taking speed and efficiency into consideration?</p>
<p>Any other observation on potential pitfalls, traps and common bad practice can be pointed out.</p>
<p><strong>Date.hh</strong></p>
<pre><code>#ifndef DATE_HH
#define DATE_HH
class Date {
friend std::ostream &operator<<( std::ostream &, const Date & );
private:
/* data-members */
unsigned month = 1;
unsigned day = 1;
unsigned year = 1970;
/* utility functions */
bool validateDate( unsigned m, unsigned d = 1, unsigned y = 1970 );
bool checkDay( unsigned m, unsigned d, unsigned y ) const;
bool isLeapYear( unsigned y ) const { return ( y % 400 == 0 ) || ( y % 4 == 0 && y % 100 != 0 ); }
public:
static constexpr unsigned int monthsPerYear = 12;
/* ctors */
Date() = default;
Date( unsigned m, unsigned d, unsigned y );
Date( unsigned m );
Date( unsigned m, unsigned d );
/* copy operations */
Date( const Date &d ) = default;
Date &operator=( const Date &d ) = default;
/* equality test operations */
bool operator==( const Date &d ) const;
bool operator!=( const Date &d ) const { return !( *this == d ); }
/* method-functions */
void setDate( unsigned m = 1, unsigned d = 1, unsigned y = 1970 );
unsigned getMonth() const;
unsigned getDay() const;
unsigned getYear() const;
void nextDay();
const std::string toString() const;
// dtor
~Date(){};
};
#endif
</code></pre>
<p><strong>Date.cc</strong></p>
<pre><code>#include <iostream>
#include <string>
#include <stdexcept>
#include <array>
#include "../headers/Date.hh"
Date::Date( unsigned m, unsigned d, unsigned y ) {
if ( validateDate(m, d, y ) ) {
month = m; day = d; year = y;
}
}
Date::Date( unsigned m ) {
if( validateDate( m ) )
month = m;
}
Date::Date( unsigned m, unsigned d ) {
if ( validateDate( m, d ) ) {
month = m; day = d;
}
}
void Date::setDate( unsigned m, unsigned d, unsigned y ) {
if ( validateDate( m, d, y ) ) {
month = m; day = d; year = y;
}
}
void Date::nextDay() {
day += 1;
try {
checkDay( month, day, year );
} catch ( std::invalid_argument &e ) {
month += 1;
day = 1;
}
if ( month % 12 == 0 ) {
year += 1;
month = 1;
}
}
bool Date::operator==( const Date &d ) const {
if( month != d.month ) return false;
if ( day != d.day ) return false;
if ( year != d.year ) return false;
return true;
}
std::ostream &operator<<( std::ostream &os, const Date &d ) {
os << d.month << "/" << d.day << "/" << d.year;
return os;
}
// utility function
bool Date::validateDate( unsigned m, unsigned d, unsigned y ) {
// validate month
if ( m < 1 || m >= 13 )
throw std::invalid_argument( "Month must be between 1-12" );
// validate day
if ( checkDay( m, d, y ) == false )
throw std::invalid_argument( "Invalid day for current month and year" );
// validate year
if ( y < 1970 )
throw std::invalid_argument( "year must be greater than 1969" );
return true;
}
const std::string Date::toString() const {
return std::to_string(month) + "/" + std::to_string(day) + "/" + std::to_string(year);
}
bool Date::checkDay( unsigned testMonth, unsigned testDay, unsigned testYear ) const {
static const std::array < unsigned, monthsPerYear + 1 > daysPerMonth = { 0,31,28,31,30,31,30,31,31,30,32,30,31};
if ( testDay > 0 && testDay <= daysPerMonth[ testMonth ] )
return true;
if ( testMonth == 2 && testDay == 29 && isLeapYear( testYear ) )
return true;
return false;
}
</code></pre>
<p><strong>BookItem.hh</strong></p>
<pre><code>#ifndef BOOKITEM_HH
#define BOOKITEM_HH
#include <iostream>
#include <string>
#include <string_view>
#include "Date.hh"
enum class BookStatus : unsigned { RESERVED, AVAILABLE, UNAVAILABLE, REFERENCE, LOANED, NONE };
enum class BookType : unsigned { HARDCOVER, MAGAZINE, NEWSLETTER, AUDIO, JOURNAL, SOFTCOPY };
class BookItem {
friend std::ostream &operator<<( std::ostream &, const BookItem & );
private:
/* data-members */
std::string title;
std::string author;
std::string category;
Date pubDate;
std::string isbn;
BookStatus status;
BookType type;
/* user connected to this book */
std::string bookcurrentUser;
public:
/* ctors */
BookItem() = default;
BookItem( const std::string &title, const std::string &author, const std::string &cat, const Date &pubDate, \
const std::string &isbn, const BookType type, const BookStatus status = BookStatus::AVAILABLE );
bool operator==( const BookItem &bookItem ) const;
bool operator!=( const BookItem &bookItem ) const { return !( *this == bookItem); };
/* method-functions */
void setStatus( BookStatus s ) { status = s; };
void setType( BookType t ) { type = t;};
void setCategory( const std::string &c ) { category = c; }
void setBookCurrentUser( std::string userName ) { bookcurrentUser = userName; }
std::string_view getBookCurrentUser() const { return bookcurrentUser; }
std::string_view getStatus() const;
std::string_view getType() const;
std::string_view getTitle() const { return title; }
std::string_view getAuthor() const { return author; }
std::string_view getCategory() const { return category; };
std::string_view getIsbn() const { return isbn; }
Date &getPubDate() { return pubDate; }
void printPubDate() const { std::cout << pubDate; }
const BookStatus getStatusByEnum() const { return status; }
const BookType getTypeByEnum() const { return type; }
// dtor
~BookItem() = default;
};
#endif
</code></pre>
<p><strong>BookItem.cc</strong></p>
<pre><code>
#include <iostream>
#include "../headers/BookItem.hh"
BookItem::BookItem( const std::string &t, const std::string &a, const std::string &c, const Date &d, \
const std::string &i, const BookType ty, const BookStatus s ) {
title = t, author = a, category = c, pubDate = d, isbn = i;
setStatus( s );
setType( ty );
}
bool BookItem::operator==( const BookItem &bookItem ) const {
if ( title != bookItem.title ) return false;
if ( author != bookItem.author ) return false;
if ( category != bookItem.category ) return false;
if ( pubDate != bookItem.pubDate ) return false;
if ( isbn != bookItem.isbn ) return false;
if ( status != bookItem.status ) return false;
if ( type != bookItem.type ) return false;
return true;
}
std::string_view BookItem::getStatus() const {
switch( status ) {
case BookStatus::AVAILABLE:
return "AVAILABLE";
case BookStatus::REFERENCE:
return "REFERENCE";
case BookStatus::UNAVAILABLE:
return "UNAVAILABLE";
case BookStatus::LOANED:
return "LOANED";
case BookStatus::RESERVED:
return "RESERVED";
default:
return "NONE";
}
}
std::string_view BookItem::getType() const {
switch( type ) {
case BookType::AUDIO:
return "AUDIO";
case BookType::HARDCOVER:
return "HARDCOVER";
case BookType::JOURNAL:
return "JOURNAL";
case BookType::MAGAZINE:
return "MAGAZINE";
case BookType::NEWSLETTER:
return "NEWSLETTER";
case BookType::SOFTCOPY:
return "SOFTCOPY";
default:
return "NONE";
}
}
std::ostream &operator<<( std::ostream &os, const BookItem &b ) {
os << "\nName of book: " << b.getTitle();
os << "\nAuthor of book: " << b.getAuthor();
os << "\nBook category: " << b.getCategory();
os << "\nPublication date: " << b.pubDate;
os << "\nISBN number: " << b.getIsbn();
os << "\nStatus of book: " << b.getStatus();
os << "\nType of book: " << b.getType();
return os;
}
</code></pre>
<p><strong>Librarian.hh</strong></p>
<pre><code>#ifndef LIBRARIAN_HH
#define LIBRARIAN_HH
#include <iostream>
#include <string>
#include "BookItem.hh"
class System;
class Librarian {
public:
/* data-members */
std::string name;
Date dateOfHire;
/* ctors */
Librarian() = default;
Librarian( const std::string &name, const Date &dateOfHire );
// basic method-function
void printDateOfHire() const { std::cout << dateOfHire; }
/* core functionalities */
void addBook( System &sys, const BookItem &isbn );
void removeBook( System &sys, const std::string &isbn );
void auditLibrary( const System &sys ) const;
// dtor
~Librarian(){}
};
#endif
</code></pre>
<p><strong>Librarian.cc</strong></p>
<pre><code>#include <iostream>
#include "../headers/System.hh"
#include "../headers/Librarian.hh"
Librarian::Librarian( const std::string &n, const Date &d ) {
name = n;
dateOfHire = d;
}
void Librarian::addBook(System &sys, const BookItem &book ) {
if ( sys.books.empty() ) {
sys.books.push_front( book );
return;
}
for ( auto bptr = sys.books.cbegin(); bptr != sys.books.cend(); ++bptr ) {
if( book.getTitle() <= bptr->getTitle() ) {
sys.books.insert(bptr, book);
return;
}
}
sys.books.push_back( book );
}
void Librarian::removeBook( System &sys, const std::string &isbn ) {
BookItem book = sys.getBook( isbn );
for ( auto bptr = sys.books.cbegin(); bptr != sys.books.cend(); ++bptr ) {
if ( book.getIsbn() == bptr->getIsbn() ) {
sys.books.remove(book);
std::cout << "Deleted { " << book.getAuthor() << " : " << book.getTitle() << " } \n";
return;
}
}
throw std::invalid_argument("Book not found");
}
void Librarian::auditLibrary( const System &sys ) const {
std::cout << "\nName of Library: " << sys.libraryName << ", Date created " << sys.dateCreated;
std::cout << "\nLibrarian: " << name << ", Date of hire: " << dateOfHire;
std::cout << "\n\nBooks: ";
for ( auto bptr = sys.books.cbegin(); bptr != sys.books.cend(); ++bptr ) {
std::cout << *bptr << "\n";
std::cout << "This book is linked to: "
<< ( ( bptr->getBookCurrentUser() == "" ) ? "None" : bptr->getBookCurrentUser() ) << "\n";
}
std::cout << "\n\nMembers: ";
for ( auto mPtr = sys.members.cbegin(); mPtr != sys.members.cend(); ++mPtr ) {
std::cout << *mPtr << "\n";
}
}
</code></pre>
<p><strong>Member.hh</strong></p>
<pre><code>#ifndef MEMBER_HH
#define MEMBER_HH
#include <string>
#include <vector>
#include "Date.hh"
#include "BookItem.hh"
class System;
class Member {
friend std::ostream& operator<<( std::ostream&os, const Member &m );
private:
/* data-member */
std::string libraryNumber;
Date dateRegisted;
std::vector<BookItem> checkedOutBooks;
public:
/* data-member */
std::string name;
char sex;
/* ctors */
Member() = default;
Member( const std::string &n, const char s, Date d ) : dateRegisted( d ), name( n ), sex( s ) {}
/* method-functions */
std::string getLibraryNumber() const { return libraryNumber; }
void setLibraryNumber( const std::string &lNum ) { libraryNumber = lNum; };
void checkOut( System &sys, const std::string &isbn );
void returnBook( System &sys, const std::string &isbn );
bool operator==( const Member &m );
bool operator!=( const Member &m ) { return !( *this == m ); }
// dtor
~Member() = default;
};
#endif
</code></pre>
<p><strong>System.cc</strong></p>
<pre><code>#ifndef SYSTEM_HH
#define SYSTEM_HH
#include <string>
#include <list>
#include <vector>
#include "Date.hh"
#include "BookItem.hh"
#include "Librarian.hh"
#include "Member.hh"
class System {
friend class Librarian;
friend class Member;
private:
/* data-members */
std::list<BookItem> books{};
std::vector<Member> members{};
Librarian librarian;
Member member;
public:
/* ctors */
System() = default;
System( const std::string &name, Date &date ) : libraryName( name ), dateCreated( date ) {};
/* method-functions */
const std::string generateLibraryNumber() const;
void addMember( Member &m ) { members.push_back( m ); };
void deleteMember( Member &m );
void displayMembers();
BookItem getBook( const std::string &isbn ) const;
void viewBook( const std::string isbn ) const;
void placeOnReserve( const std::string, const std::string &isbn );
void displayAllBooks() const;
/* data-members */
std::string libraryName;
Date dateCreated;
/* search functionalities */
std::list<BookItem> queryByTitle( const std::string &t ) const;
std::list<BookItem> queryByAuthor( const std::string &a ) const;
std::list<BookItem> queryByPubDate( const Date &d );
std::list<BookItem> queryByStatus( const BookStatus &s ) const;
std::list<BookItem> queryByType( const BookType &ty ) const;
// dtor
~System() = default;
};
#endif
</code></pre>
<p><strong>System.cc</strong></p>
<pre><code>#include <iostream>
#include <set>
#include "../headers/System.hh"
std::list<BookItem> System::queryByTitle( const std::string &t ) const {
std::list<BookItem> queryList;
for ( auto bPtr = books.cbegin(); bPtr != books.cend(); ++bPtr ) {
if ( bPtr->getTitle().find(t) != std::string::npos )
queryList.push_back( *bPtr );
}
return queryList;
}
std::list<BookItem> System::queryByAuthor( const std::string &a ) const {
std::list<BookItem> queryList;
for ( auto bPtr = books.cbegin(); bPtr != books.cend(); ++bPtr ) {
if ( bPtr->getAuthor().find(a) != std::string::npos )
queryList.push_back( *bPtr );
}
return queryList;
}
std::list<BookItem> System::queryByPubDate( const Date &d ) {
std::list<BookItem> queryList;
for ( auto bPtr = books.begin(); bPtr != books.cend(); ++bPtr ) {
if ( bPtr->getPubDate().toString().find(d.toString()) != std::string::npos )
queryList.push_back( *bPtr );
}
return queryList;
}
std::list<BookItem> System::queryByStatus( const BookStatus &s ) const {
std::list<BookItem> queryList;
for ( auto bPtr = books.begin(); bPtr != books.cend(); ++bPtr ) {
if ( bPtr->getStatusByEnum() == s )
queryList.push_back( *bPtr );
}
return queryList;
}
std::list<BookItem> System::queryByType( const BookType &ty ) const {
std::list<BookItem> queryList;
for ( auto bPtr = books.begin(); bPtr != books.cend(); ++bPtr ) {
if ( bPtr->getTypeByEnum() == ty )
queryList.push_back( *bPtr );
}
return queryList;
}
void System::placeOnReserve( const std::string name, const std::string &isbn ) {
for ( auto bPtr = books.begin(); bPtr != books.end(); ++bPtr ) {
if ( bPtr->getIsbn() == isbn ) {
bPtr->setStatus( BookStatus::RESERVED );
bPtr->setBookCurrentUser( name );
}
}
}
BookItem System::getBook( const std::string &isbn ) const {
for ( auto bPtr = books.cbegin(); bPtr != books.cend(); ++bPtr ) {
if ( bPtr->getIsbn() == isbn )
return *bPtr;
}
throw std::invalid_argument("Book is not available at the library");
}
void System::viewBook( const std::string isbn ) const {
std::cout << getBook( isbn );
}
const std::string System::generateLibraryNumber() const {
static std::string Codes[10]{"XGS", "QWT", "OPI", "NMK", "DXF", "PXG", "OPI", "QPU", "IKL", "XYX" };
static std::set< unsigned, std::greater<unsigned> > idSet;
unsigned id;
bool unique = false;
unsigned index = 0 + rand() % 9;
std::string code = Codes[ index ];
while ( unique == false ) {
id = 10000000 + rand() % 9999999;
auto ret = idSet.emplace(id);
if ( !ret.second ) {
std::cout << "unique failed";
unique = false;
continue;
}
else
unique = true;
}
return code + std::to_string( id );
}
void System::deleteMember( Member &m ) {
for ( auto mPtr = members.begin(); mPtr != members.end(); ++mPtr ) {
if ( *mPtr == m ) {
members.erase( mPtr );
std::cout << "Deleted member: { Name: " << m.name << ", Library Number: " << m.getLibraryNumber() <<
" }\n";
return;
}
}
throw std::invalid_argument("No such member found");
}
void System::displayMembers() {
std::cout << "Members of Library: ( count : " << members.size() << " ) " << "\n";
for ( auto mPtr = members.cbegin(); mPtr != members.cend(); ++mPtr ) {
std::cout << *mPtr;
}
}
void System::displayAllBooks() const {
for ( auto bPtr = books.begin(); bPtr != books.end(); ++bPtr ) {
std::cout << *bPtr << "\n\n";
}
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p><strong><code>Date</code>:</strong></p>\n<ul>\n<li><p><code>Date.hh</code> is missing some includes (<code><iostream></code>, <code><string></code>).</p>\n</li>\n<li><p>Don't supply a default constructor. It doesn't make sense to have a default date.</p>\n</li>\n<li><p>Don't supply one- and two-argument constructors. Specifying a month and date in 1970 is unlikely to be very common.</p>\n</li>\n<li><p>We should support years before 1970. There were books back then!</p>\n</li>\n<li><p><code>year</code> should be a signed number (even if that capability is unlikely to be used).</p>\n</li>\n<li><p><code>day</code> and <code>month</code> can be smaller types (e.g. <code>std::uint8_t</code>).</p>\n</li>\n<li><p><code>setDate()</code> is unnecessary, since we have the constructor and assignment.</p>\n</li>\n<li><p>One would expect a function called <code>nextDay()</code> to return a copy, rather than modifying the <code>Date</code> instance (c.f. standard library iterators <code>next</code> and <code>advance</code>).</p>\n</li>\n<li><p>If the destructor does nothing, we can omit it.</p>\n</li>\n<li><p><code>validateDate</code> can never return <code>false</code>, so it should have a <code>void</code> return value (and perhaps be called <code>throwIfInvalid</code> or something similar).</p>\n</li>\n<li><p>Member functions that don't need access to a class instance's member variables (<code>validateDate</code> etc.) can be made <code>static</code>.</p>\n</li>\n<li><p>I'd suggest printing dates as "yyyy-mm-dd" (or printing the month by name). Putting the day in the middle is highly illogical.</p>\n</li>\n<li><p>If you have C++20, use <code>std::chrono::year_month_day</code> instead!</p>\n</li>\n</ul>\n<hr />\n<p><strong><code>BookItem</code>:</strong></p>\n<ul>\n<li><p>We should use the constructor initializer list to initialize member variables.</p>\n</li>\n<li><p>Again, we don't want a default constructor.</p>\n</li>\n<li><p>We don't need to specify a destructor.</p>\n</li>\n<li><p>Note that libraries often have several copies of the same book. When a book has an ISBN (mainstream publications after 1970), we don't need to duplicate the book data (title, author, etc.) for every copy of the book in the library. Perhaps we should move the book data into a separate class, and have a <code>std::variant<ISBN, BookData></code> in <code>BookItem</code>? (But maybe that's going too far for this implementation).</p>\n</li>\n<li><p>We should add a unique identifier for each item the library holds.</p>\n</li>\n</ul>\n<hr />\n<p><strong><code>Librarian</code>:</strong></p>\n<ul>\n<li><p><code>addBook</code> and <code>removeBook</code> should not be part of this class. They modify the <code>System</code> class internals, and should be part of the <code>System</code> class. <code>auditLibrary</code> should be moved there too.</p>\n</li>\n<li><p>The default constructor shouldn't exist. The destructor doesn't need to exist.</p>\n</li>\n<li><p>I don't think this class needs to exist at all for the current library functionality.</p>\n</li>\n</ul>\n<hr />\n<p><strong><code>Member</code>:</strong></p>\n<ul>\n<li><p>Default constructor bad. Destructor unnecessary.</p>\n</li>\n<li><p>We don't really want to store <code>BookItem</code>s here by value. We just need to store an ID for each item they have checked out.</p>\n</li>\n<li><p><code>checkOut</code> and <code>returnBook</code> shouldn't be here, they should be part of <code>System</code>.</p>\n</li>\n</ul>\n<hr />\n<p><strong><code>System</code>:</strong></p>\n<ul>\n<li><p>Shouldn't have <code>friend</code>s.</p>\n</li>\n<li><p>Should perhaps be called <code>Library</code>.</p>\n</li>\n<li><p>Don't worry about speed unless it actually becomes a problem. There's probably no point in even storing books by title (we're as likely to want to search by author or category or publication date or...).</p>\n</li>\n<li><p>(Note that the title search doesn't take into account that the list is sorted by title!)</p>\n</li>\n<li><p><code>std::list</code> has few valid uses. It only becomes faster than <code>std::vector</code> for inserting and removing many (hundreds of thousands) of items from the <em>middle</em> of the list. <code>std::vector</code> would be fine here.</p>\n</li>\n<li><p>Use range-based for loops where appropriate: <code>for (auto const& i: books) { ... }</code>.</p>\n</li>\n<li><p>Note that the <code><algorithm></code> header supplies various functions to find and copy things.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T17:05:46.140",
"Id": "250872",
"ParentId": "250850",
"Score": "3"
}
},
{
"body": "<p>I've read answer by @user673679 and just want address a few issues.</p>\n<p>I strongly disagree with disabling default constructors in classes like <code>Member/Date/BookItem</code>. If class has no default constructor then using it with <code>std::vector</code>, <code>std::map</code> and other template containers becomes very awkward in general. So it is a bad advise.</p>\n<p>Instead you should make default constructed classes such as these be clearly uninitialized and add functions/methods that test it.</p>\n<p>Another note: I want to expand upon <code>std::vector</code> vs <code>std::list</code>. <code>std::list</code> is a very slow container and unsuitable for most purposes. It requires a new allocation for each element and to find a middle element one needs to traverse half the list. So using <code>std::list</code> is almost a sacrilege. There a few rare cases where list could be beneficial but definitely not in this code.</p>\n<p>Use <code>std::vector</code> instead. You'll need to eventually figure out how to properly manage memory and lookup for searching but use <code>std::vector</code> for storing the base classes. For instance, erasing a single element isn't worth rearranging the whole vector. Instead, just keep count of number of empty locations and if the number surpasses half the total size then rearrange it.</p>\n<p>You still lack move constructor and move assignment for <code>BookItem</code>. Having it will improve performance of classes like <code>std::vector</code> that hold the book items.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T18:32:13.953",
"Id": "493600",
"Score": "0",
"body": "I have no idea about move constructor, Am currently learning with c++ primer and I haven't yet gotten to the chapter were move constructors are discussed, I just wrote the program with my current knowledge."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T18:33:37.243",
"Id": "493601",
"Score": "0",
"body": "Please elaborate on \"Instead you should make default constructed classes such as these be clearly uninitialized and add functions/methods that test it.\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T19:22:30.847",
"Id": "493606",
"Score": "0",
"body": "There sometimes are legitimate reasons for disabling default constructors, although here I don't think there is an issue to have default constructors indeed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T21:41:39.260",
"Id": "493623",
"Score": "0",
"body": "@G.Sliepen there are legitimate reasons to disable various constructors including default ones. But the ones listed weren't such."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T21:48:28.193",
"Id": "493624",
"Score": "1",
"body": "@theProgrammer e.g. you can by default instantiate the data with invalid day/month or simply have a boolean that states whether the class was instantiated. You may or may not differentiate the cases \"invalid date\" and \"non initialized date\" - it is up to your choice of design. Though, I believe the two cases are quite different and should be treated differently. Alternatively, you can utilize `std::optional`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T00:31:55.327",
"Id": "493645",
"Score": "0",
"body": "This are way above my level right now, I guess I would just stick to having no default constructors"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T18:13:25.387",
"Id": "250876",
"ParentId": "250850",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "250872",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T23:42:25.980",
"Id": "250850",
"Score": "4",
"Tags": [
"c++",
"beginner",
"object-oriented",
"design-patterns"
],
"Title": "Object Oriented Library Management System"
}
|
250850
|
<p>Im going to start with that im trying to do.</p>
<p>Change this program to loop until it encounters a sentinel value, which is a negative number. The data begins at x3100. Use only one branch command. There will always be at least one positive integer in the list. No count controlled loop.</p>
<p>When the program ends, R2 must contain the number of values summed and R3 must contain the sum of those values.</p>
<pre><code>.ORIG x3000
AND R3, R3, #0
AND R2, R2, #0
ADD R2, R2, #12
BRz #5
LDR R4, R1, #0
ADD R3, R3, R4
ADD R1, R1, #1
ADD R2, R2, #-1
BRnzp #-6
.END
</code></pre>
<p>My textbook along with the professor are not being of much help so i came here to try a get a better understanding.</p>
<p>I know I can remove/get rid of the other two Branch Loop commands as I need only one, but I do not know how to structure that loop and getting R2 and R3 to work, it just seems they want to stay at 0.</p>
<p>EDIT: That was because i did not run it, i only opened it in the simulator.</p>
<p>I'm also not sure how i can just skip from x3000 to x3100 to fill data being provided from this loop.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T23:46:31.420",
"Id": "250851",
"Score": "1",
"Tags": [
"lc-3"
],
"Title": "A Better Understanding of LC-3 - Branch Loop to Stop When Encountering a Negative"
}
|
250851
|
<p>How can I make this code run faster:</p>
<pre><code>for a in range(1,1001):
for b in range(1, 1001):
for c in range(1, 1001):
if pow(a, 2) + pow(b, 2) == pow(c, 2):
print(str(a) + "," + str(b) + "," + str(c))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T00:25:27.823",
"Id": "493644",
"Score": "5",
"body": "You can [generate a tree of all pythagorean triples](https://en.wikipedia.org/wiki/Tree_of_primitive_Pythagorean_triples) using some simple linear algebra."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T16:35:26.460",
"Id": "493709",
"Score": "1",
"body": "@Phylogenesis Very nice, used that in [another answer](https://codereview.stackexchange.com/a/250916/72846)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T16:44:13.337",
"Id": "493710",
"Score": "1",
"body": "Try replacing `pow(X,2` with `(X * X)`. Usually, a single multiplication is faster than a function call."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T22:18:47.330",
"Id": "493745",
"Score": "0",
"body": "The naive approach is O(N^3), since each for-loop runs 1..1001. Also, you can contrain the start and termination values on your c-loop by applying a,b < c (WLOG let a,b be the legs and c the hypotenuse). But even if you don't code the tree-based approach, you can reduce the order enormously by generating all distinct positive-integer candidates (m,n) in Euclid's solution `a = k(m^2 - n^2), b = k(2mn), c = k(m^2 + n^2)`. Now we only need to test up to c = 1000 > m^2 i.e. m < sqrt(1000) = 31 [@StefanPochmann's answer](https://codereview.stackexchange.com/a/250874/10196)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T23:04:48.413",
"Id": "493753",
"Score": "0",
"body": "By the way, using [f-strings](https://docs.python.org/3/whatsnew/3.6.html) in printing is clearer: `print(f'{a},{b},{c}')`"
}
] |
[
{
"body": "<p>There are some obvious optimizations you can do:</p>\n<ul>\n<li>Eliminate duplicate checks: you are checking each possible combination twice. For example, you are checking both a = 2, b = 3 and a = 3, b = 2. The <em>very first</em> two lines your program prints are <code>3,4,5</code> and <code>4,3,5</code>!</li>\n<li>Eliminate impossible checks: you are checking, for example, 1000² + 1000² == 1².</li>\n<li>Eliminate duplicate computations: you are computing the square of the same numbers over and over again.</li>\n<li>Print less: printing to the console is sloooooooooooow. Collect the results in a data structure and only print them once.</li>\n</ul>\n<p>Something like this:</p>\n<pre class=\"lang-python prettyprint-override\"><code>def triplets():\n squares = [pow(n, 2) for n in range(0, 1001)]\n\n for a in range(1, 1001):\n for b in range(a, 1001):\n for c in range(b, 1001):\n if squares[a] + squares[b] == squares[c]:\n yield a, b, c\n\n\nprint(list(triplets()))\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T09:59:57.193",
"Id": "493799",
"Score": "1",
"body": "Given that you've precomputed all the relevant squares, you can just do list membership to see whether the result is a square, making the code about 4 times faster: [Try it online!](https://tio.run/##dY/BCsIwEETv@Yo9JlqkxZvgl5QeErrRhbCtSQr262NTjVXEOSws82aWHed4HfiYUo8WoqfRYQxSnQQsCrdJewxwhpZhBwx28MskBq/5grKp60Z1YmWzpT@sClb3WVQAswH6B8giW462uoP9ezFdTr6270jWTOh6WCpNVaADcY93@adNCTF64igdhSi3v5VK6QE \"Python 3 – Try It Online\")"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T07:14:01.500",
"Id": "250856",
"ParentId": "250855",
"Score": "8"
}
},
{
"body": "<p>Some optimizations and style suggestions:</p>\n<ul>\n<li>After finding a solution you can <code>break</code>:\n<pre><code>for a in range(1,1001):\n for b in range(1, 1001):\n for c in range(1, 1001):\n if pow(a, 2) + pow(b, 2) == pow(c, 2):\n print(str(a) + "," + str(b) + "," + str(c))\n break\n</code></pre>\n</li>\n<li>Use <code>**</code> which is <a href=\"https://stackoverflow.com/a/20970087/8484783\">faster</a> than <code>pow</code>, or just multiply for itself <code>a*a</code>.</li>\n<li>Use Python formatter to print the result: <code>print(f"{a},{b},{c}")</code>.</li>\n<li>Calculate c as <span class=\"math-container\">\\$c=sqrt(a^2+b^2)\\$</span>:\n<pre><code>for a in range(1,1001):\n for b in range(1, 1001):\n c = int(math.sqrt(a ** 2 + b ** 2))\n if a ** 2 + b ** 2 == c ** 2 and c < 1001:\n print(f"{a},{b},{c}")\n</code></pre>\nThe solution now takes <span class=\"math-container\">\\$O(n^2)\\$</span> instead of <span class=\"math-container\">\\$O(n^3)\\$</span>.</li>\n<li>Instead of checking <code>if a ** 2 + b ** 2 == c ** 2:</code>, it's enough verifying that c is an integer:\n<pre><code>for a in range(1,1001):\n for b in range(1, 1001):\n c = math.sqrt(a ** 2 + b ** 2)\n if c.is_integer() and c < 1001:\n print(f"{a},{b},{int(c)}")\n</code></pre>\n</li>\n<li>As already said, you can also start the second for-loop from <code>a</code> to avoid duplicated solutions.</li>\n<li>Put everything into a function:\n<pre><code>def triplets(n):\n for a in range(1, n):\n for b in range(a, n):\n c = math.sqrt(a * a + b * b)\n if c.is_integer() and c <= n:\n print(f"{a},{b},{int(c)}")\ntriplets(1000)\n</code></pre>\n</li>\n</ul>\n<p>Runtime on my machine:</p>\n<pre><code>Original: 868.27 seconds (~15 minutes)\nImproved: 0.27 seconds\n</code></pre>\n<hr />\n<p><strong>EDIT</strong>:</p>\n<p>Since this question got a lot of attention I wanted to add a couple of notes:</p>\n<ol>\n<li>This early answer was for <a href=\"https://codereview.stackexchange.com/revisions/250855/1\">OP's original problem</a> that I interpreted as "find all the triplets in a <strong>reasonable</strong> amount of time".</li>\n<li>There are <strong>definitely</strong> more efficient (and advanced) solutions than this one. If you are interested in finding out more, have a look at other excellent answers on this thread.</li>\n<li>As noted in the comments, the runtime in my answer is a rough calculation. Find a better benchmark on <a href=\"https://codereview.stackexchange.com/a/250874/227157\">@Stefan's answer</a>.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T15:57:19.593",
"Id": "493582",
"Score": "1",
"body": "I was very much in a rush when I wrote my answer. This is orders of magnitude better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T16:31:05.227",
"Id": "493586",
"Score": "2",
"body": "For the runtimes, how did you measure? Asking mainly because you `print` the results."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T16:44:57.583",
"Id": "493588",
"Score": "2",
"body": "You can still improve (slightly) the inner loop by running from `a` up to `sqrt(n**2-a**2)` and discard the `c<=n` test."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T18:03:02.030",
"Id": "493597",
"Score": "0",
"body": "@superbrain you do at the beginning of the file: import time cTime = int(time.time) and at the end put: print(f”Runtime : {int(time.time) - cTime}”)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T02:04:12.690",
"Id": "493646",
"Score": "1",
"body": "@superbrain I used `time.time()` around `triplets(1000)`, that prints to the console. Then I wrapped OP's solution into a function and calculated the runtime the same way. It was just to have a rough idea, a better benchmark is in @Stefan's answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T02:13:03.330",
"Id": "493647",
"Score": "1",
"body": "@Marc Ok, thanks. Printing can be pretty slow, depending on the console, and 0.27 seconds seemed very fast for that. I just tried it, took 12.8 seconds. Without the printing (but still building the strings) it took 0.2 seconds. I used IDLE, I guess you used something much faster."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T02:49:34.570",
"Id": "493649",
"Score": "1",
"body": "@superbrain yes printing is slow in general, but somehow the result is not affected that much on my IDE, PyCharm 2019.2 Community. I run the code within the IDE on a laptop with Intel i5 and 16GB of RAM. Maybe next time I should mention this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T19:12:27.553",
"Id": "493840",
"Score": "1",
"body": "As of Python 3.8, [`math.isqrt(x)`](https://docs.python.org/3/library/math.html?highlight=isqrt#math.isqrt) is preferable to `int(math.sqrt(x))` ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T19:37:29.953",
"Id": "493843",
"Score": "1",
"body": "Performance won't be affected by your IDE; it'll be affected by your build of Python (CPython, etc.) Your IDE will influence the default choice of Python binary, but that's secondary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T19:38:47.560",
"Id": "493844",
"Score": "0",
"body": "Of course that's before taking into account delays introduced by output (@superbrain makes reference to this)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T02:50:37.430",
"Id": "493889",
"Score": "0",
"body": "@Reinderien thanks for the clarification. I just want to point out that the runtime in my answer is not a proper benchmark. I'll omit the details to avoid confusion."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T07:59:45.107",
"Id": "250862",
"ParentId": "250855",
"Score": "20"
}
},
{
"body": "<p>My "review" will have to be <em>"If you really want it fast, you need a completely different approach"</em>. The following <code>~ O(N log N)</code> approach is about 680 times faster than Marc's accepted solution for N=1000:</p>\n<pre><code>from math import isqrt, gcd\n\ndef triplets(N):\n for m in range(isqrt(N-1)+1):\n for n in range(1+m%2, min(m, isqrt(N-m*m)+1), 2):\n if gcd(m, n) > 1:\n continue\n a = m*m - n*n\n b = 2*m*n\n c = m*m + n*n\n for k in range(1, N//c+1):\n yield k*a, k*b, k*c\n</code></pre>\n<p>This uses <a href=\"https://en.wikipedia.org/wiki/Pythagorean_triple#Generating_a_triple\" rel=\"nofollow noreferrer\">Euclid's formula</a>.</p>\n<p>Benchmark results for N=1000:</p>\n<pre><code>Stefan Marc\n0.24 ms 165.51 ms\n0.24 ms 165.25 ms\n0.24 ms 161.33 ms\n</code></pre>\n<p>Benchmark results for N=2000, where it's already about 1200 times faster than the accepted solution:</p>\n<pre><code>Stefan Marc \n0.52 ms 654.72 ms \n0.58 ms 689.10 ms \n0.53 ms 662.19 ms \n</code></pre>\n<p>Benchmark code:</p>\n<pre><code>from math import isqrt, gcd\nimport math\nfrom timeit import repeat\nfrom collections import deque\n\ndef triplets_Stefan(N):\n for m in range(isqrt(N-1)+1):\n for n in range(1+m%2, min(m, isqrt(N-m*m)+1), 2):\n if gcd(m, n) > 1:\n continue\n a = m*m - n*n\n b = 2*m*n\n c = m*m + n*n\n for k in range(1, N//c+1):\n yield k*a, k*b, k*c\n\ndef triplets_Marc(n):\n for a in range(1, n):\n for b in range(a, n):\n c = math.sqrt(a * a + b * b)\n if c.is_integer() and c <= n:\n yield a, b, int(c)\n\nn = 2000\nexpect = sorted(map(sorted, triplets_Marc(n)))\nresult = sorted(map(sorted, triplets_Stefan(n)))\nprint(expect == result)\n\nfuncs = [\n (10**3, triplets_Stefan),\n (10**0, triplets_Marc),\n ]\n\nfor _, func in funcs:\n print(func.__name__.removeprefix('triplets_').ljust(10), end='')\nprint()\n\nfor _ in range(3):\n for number, func in funcs:\n t = min(repeat(lambda: deque(func(n), 0), number=number)) / number\n print('%.2f ms ' % (t * 1e3), end='')\n print()\n</code></pre>\n<p>About runtime complexity: Looks like around O(N log N). See the comments. And if I try larger and larger <code>N = 2**e</code> and divide the times by <code>N log N</code>, they remain fairly constant:</p>\n<pre><code>>>> from timeit import repeat\n>>> from collections import deque\n>>> for e in range(10, 25):\n N = 2**e\n t = min(repeat(lambda: deque(triplets(N), 0), number=1))\n print(e, t / (N * e))\n\n10 5.312499999909903e-08\n11 3.3176491483337275e-08\n12 2.3059082032705902e-08\n13 3.789156400398811e-08\n14 1.95251464847414e-08\n15 1.9453328450880215e-08\n16 1.9563865661601648e-08\n17 1.9452756993864518e-08\n18 1.973256005180039e-08\n19 2.0924497905514347e-08\n20 2.1869220733644352e-08\n21 2.1237255278089392e-08\n22 2.0788834311744357e-08\n23 2.1097218990325713e-08\n24 2.1043718606233202e-08\n</code></pre>\n<p>Also see the comments.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T17:38:00.590",
"Id": "493595",
"Score": "14",
"body": "Yay 2200 year old maths!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T22:27:29.283",
"Id": "493749",
"Score": "0",
"body": "What big-O complexity is this? The naive approach was O(N^3). This one constrains the m-range to ~ O(N^0.5) and n-range to < O(N^0.5) , thus O(N), and the k-range to O(N/c), is that an additional factor of ~ O(logN) (And that's all before we prune for gcd(m, n) > 1)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T22:35:59.747",
"Id": "493750",
"Score": "2",
"body": "@smci I don't know. But yes, looks like around O(N log N)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T22:39:59.413",
"Id": "493751",
"Score": "0",
"body": "How much does the gcd pruning buy us, and is using `numpy.gcd` or other symbolic [sympy gcd](https://docs.sympy.org/latest/search.html?q=gcd) faster? (thunking between Python and C is inefficient, but the low value of N here will obscure the bit-O behavior, so benchmarks on N=1000 don't tell us big-O)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T22:42:34.820",
"Id": "493752",
"Score": "0",
"body": "Also, to clearly show the big-O behavior visually, could plot the two approaches for N=500, 1000, 2000, 5000, 10000..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T23:11:55.447",
"Id": "493756",
"Score": "1",
"body": "@smci I added some timings for larger N at the end (up to \\$N=2^{24}\\$). Don't know about the other gcds, and I'm not sure \"pruning\" is the right word. To me that sounds like a performance optimization and that's how you're treating it, but its real purpose here is to avoid duplicates in the output."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T23:34:51.423",
"Id": "493758",
"Score": "0",
"body": "Stefan: right. I was suggesting a *graph* plotting your/Euclid's approach vs Marc's, for same range of N. That'll make it much clearer that O(N^3) blows up very quickly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T23:36:33.463",
"Id": "493759",
"Score": "1",
"body": "@smci Meh, I don't think we need a graph to know that ~O(N log N) is much faster than O(N^2) and O(N^3) :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T23:37:56.783",
"Id": "493760",
"Score": "0",
"body": "Stefan: obviously not, but would be nice to see all the other approaches in big-O land... also like I said, for small N ~ 1000, non-scaleability can be disguised with numpy or cython thunking."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T11:24:05.227",
"Id": "493810",
"Score": "1",
"body": "It would be really interesting to see how this compares on different Python implementations. The OP's extremely inefficient version runs in ~15 minutes on my laptop using CPython 3.7.3 but in only 22 seconds, i.e. 40x(!!!) faster, on GraalPython 20.2.0. And this is actually still unfair towards GraalPython because I did not account for JVM startup time, JIT warmup, etc. Even more interesting: GraalPython used 200% CPU, so somehow, in some way, shape, or form, it was using multiple threads. No idea how and why and what, though. It can't be the GC since there's not garbage. It can't be the JIT …"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T11:24:22.457",
"Id": "493811",
"Score": "1",
"body": "… because that's basically done after the first 50000 iterations or so. And I don't think it has *actually* vectorized the loops, because then it would be using 8 cores, not 2."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T15:23:14.933",
"Id": "493824",
"Score": "1",
"body": "@JörgWMittag Hmm, I'm not familiar with GraalPython and not in the mood to get into it now :-). Have you tried mine as well with GraalPython?"
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T17:28:20.280",
"Id": "250874",
"ParentId": "250855",
"Score": "16"
}
},
{
"body": "<p>First, I don't know Python, so please don't look to me as setting a stylistic or idiomatic example here. But I think that there are some things that are universal. In particular, try to move calculations out of loops. So in your original (although the same advice applies to all the answers posted so far in some way):</p>\n<pre><code>for a in range(1, 1001):\n square_a = a * a\n for b in range(1, 1001):\n square_c = square_a + b * b\n for c in range(1, 1001):\n if square_c == c * c:\n</code></pre>\n<p>It is possible that the Python compiler or interpreter will do this for you, pulling the invariant calculations out of the loops. But if you do it explicitly, then you know that it will be done.</p>\n<p>You can use the benchmarking techniques in <a href=\"https://codereview.stackexchange.com/a/250874/71574\">Stefan Pochmann's answer</a> to test if it helps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T03:37:10.467",
"Id": "493770",
"Score": "1",
"body": "The most widely used Python implementation, CPython, is a pure interpreter. It won't hoist `a*a` for you. And might not optimize `pow(x, 2)` into a simply multiply. BTW, your way makes the optimization of simply checking if `square_c` is a perfect square between 1 and 1001 more obvious. Like `tmp = sqrt(square_c); if int(tmp) == tmp:` instead of looping. (or something like that; IDK Python either.)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T03:36:11.983",
"Id": "250889",
"ParentId": "250855",
"Score": "5"
}
},
{
"body": "<p><a href=\"https://en.wikipedia.org/wiki/Tree_of_primitive_Pythagorean_triples\" rel=\"nofollow noreferrer\">Trees of primitive Pythagorean triples</a> are great. Here's a solution using such a tree:</p>\n<pre><code>def triplets(N):\n mns = [(2, 1)]\n for m, n in mns:\n c = m*m + n*n\n if c <= N:\n a = m*m - n*n\n b = 2 * m * n\n for k in range(1, N//c+1):\n yield k*a, k*b, k*c\n mns += (2*m-n, m), (2*m+n, m), (m+2*n, n)\n</code></pre>\n<p>And here's one using a heap to produce triples in increasing order of c:</p>\n<pre><code>from heapq import heappush, heappop\n\ndef triplets(N=float('inf')):\n heap = []\n def push(m, n, k=1):\n kc = k * (m*m + n*n)\n if kc <= N:\n heappush(heap, (kc, m, n, k))\n push(2, 1)\n while heap:\n kc, m, n, k = heappop(heap)\n a = m*m - n*n\n b = 2 * m * n\n yield k*a, k*b, kc\n push(m, n, k+1)\n if k == 1:\n push(2*m-n, m)\n push(2*m+n, m)\n push(m+2*n, n)\n</code></pre>\n<p>A node in the <em>primitive</em> triple tree just needs its m and n (from which a, b and c are computed). I instead store tuples <code>(kc, m, n, k)</code> in a heap, where k is the multiplier for the triple and c is the primitive triple's c so that kc is the multiplied triple's c. This way I get all triples in order of increasing (k-multiplied) c. The tree structure makes the expansion of a triple to larger triples really easy and natural. I had tried to do something like this with my loops-solution but had trouble. Also note that I don't need any ugly sqrt-limit calculations, don't need a gcd-check, and don't need to explicitly make sure m+n is odd (all of which I have in my other answer's solution).</p>\n<p>Demo:</p>\n<pre><code>>>> for a, b, c in triplets():\n print(a, b, c)\n \n3 4 5\n6 8 10\n5 12 13\n9 12 15\n15 8 17\n12 16 20\n...\n(I stopped it here)\n</code></pre>\n<p>So if you want the triples up to a certain limit N, you can provide it as argument, or you can just read from the infinite iterator and stop when you exceed the limit or when you've had enough or whatever. For example, the millionth triple has c=531852:</p>\n<pre><code>>>> from itertools import islice\n>>> next(islice(triplets(), 10**6-1, None))\n(116748, 518880, 531852)\n</code></pre>\n<p>This took about three seconds.</p>\n<p>Benchmarks with my other answer's "loops" solution, the unordered "tree1" solution and the ordered-by-c "tree2" solution:</p>\n<pre><code>N = 1,000\nloops tree1 tree2 \n0.25 ms 0.30 ms 1.14 ms \n0.25 ms 0.31 ms 1.18 ms \n0.25 ms 0.32 ms 1.15 ms \n\nN = 2,000\nloops tree1 tree2 \n0.53 ms 0.61 ms 2.64 ms \n0.52 ms 0.60 ms 2.66 ms \n0.51 ms 0.60 ms 2.54 ms \n\nN = 1,000,000\nloops tree1 tree2 \n0.46 s 0.52 s 6.02 s \n0.47 s 0.53 s 6.04 s \n0.45 s 0.53 s 6.08 s \n</code></pre>\n<p>Thanks to @Phylogenesis for <a href=\"https://codereview.stackexchange.com/questions/250855/finding-all-the-pythagorean-triplets-with-all-numbers-less-than-1000/250874#comment493644_250855\">pointing these trees out</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T16:34:37.723",
"Id": "250916",
"ParentId": "250855",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "250862",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T06:31:52.640",
"Id": "250855",
"Score": "9",
"Tags": [
"python",
"performance",
"mathematics"
],
"Title": "Efficiently find all the Pythagorean triplets where all numbers less than 1000"
}
|
250855
|
<p>I had an interview task where I had to output customers who live 100km within a particular latitude and longitude and then output them to a file with their username and ID. The customer file looks like the following:</p>
<pre><code>{"latitude": "52.986375", "user_id": 12, "name": "Christina McArdle", "longitude": "-6.043701"}
{"latitude": "51.92893", "user_id": 1, "name": "Alice Cahill", "longitude": "-10.27699"}
{"latitude": "51.8856167", "user_id": 2, "name": "Ian McArdle", "longitude": "-10.4240951"}
{"latitude": "52.3191841", "user_id": 3, "name": "Jack Enright", "longitude": "-8.5072391"}
</code></pre>
<p>Here is the code to implement the calculation for the great-circle-distance</p>
<pre><code>/**
* solution accuired from
* https://www.movable-type.co.uk/scripts/latlong.html
*/
const greatCircleDistanceCalc = (lat1, lon1, lat2, lon2) => {
const R = 6371; // Radius of the earth in km
const dLat = deg2rad(lat2 - lat1); // deg2rad below
const dLon = deg2rad(lon2 - lon1);
const a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(deg2rad(lat1)) *
Math.cos(deg2rad(lat2)) *
Math.sin(dLon / 2) *
Math.sin(dLon / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
const d = R * c; // Distance in km
return d;
};
const deg2rad = (deg) => {
return deg * (Math.PI / 180);
};
module.exports = {
greatCircleDistanceCalc,
};
</code></pre>
<p>Here is the main app.js where the calculation is used and a customer file is read and a new file is outputted.</p>
<pre><code>const fs = require("fs");
const { greatCircleDistanceCalc } = require("./greatCircleDistanceCalc.js");
const customerFile = fs.readFileSync("./customers.txt", "utf-8"); //Read in file
const customerArr = customerFile.split("\n").map((s) => JSON.parse(s)); //Convert file into array of objects
const dublinOffice = {
latitude: "53.339428",
longitude: "-6.257664",
};
const invitedArr = [];
//Sort data in ascending order
const sortedCustomers = customerArr.sort((a, b) => {
return a.user_id - b.user_id;
});
const closestCustomers = (sortedCustomers, arr) => {
for ({ latitude, longitude, user_id, name } of sortedCustomers) {
if (
greatCircleDistanceCalc(
dublinOffice.latitude,
dublinOffice.longitude,
latitude,
longitude
) <= 100
) {
invitedArr.push(`${name}:${user_id}`);
}
}
writeInvitedCustomer(arr);
};
const writeInvitedCustomer = (arr) => {
const writeStream = fs.createWriteStream("Output.txt");
const pathName = writeStream.path;
arr.forEach((value) => writeStream.write(`${value}\n`));
writeStream.on("finish", () => {
console.log(`wrote all the array data to file ${pathName}`);
});
writeStream.on("error", (err) => {
console.error(`There is an error writing the file ${pathName} => ${err}`);
});
writeStream.end();
};
closestCustomers(sortedCustomers, invitedArr);
</code></pre>
<p>Overall I am happy with the solution but I think the only thing is I am not sure how to write a test for this.</p>
<p>As always any feedback and suggestions are much welcome.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T22:20:35.070",
"Id": "493631",
"Score": "1",
"body": "You 'got away' with it in this instance, but I would advise that you explicitly convert string representations of numbers to numbers if you're to do mathematics with them. Consider what would happen if it had been like 'lat2 + lat1' and not 'lat2 - lat1', you would have concatenated two strings."
}
] |
[
{
"body": "<p>Generally I find the code very unstructured making reading it a bit confusing:</p>\n<p>First you execute some code outside of a function to read the data from a file, then you define a constant (<code>dublinOffice</code>), then you define a variable (<code>invitedArr</code>), but don't use it in the next block of code, then you sort the data, then you define two functions, and finally execute one of the functions.</p>\n<p>Further more the function <code>closestCustomers</code> both gets <code>invitedArr</code> passed an argument (and uses it as such) and uses it directly as a global variable.</p>\n<p>Personally I'd have the main code calling functions first (after defining constants) and then define all functions at the end of the source code using <code>function</code> so that they are <a href=\"https://developer.mozilla.org/en-US/docs/Glossary/Hoisting\" rel=\"nofollow noreferrer\">hoisted</a>. Other people may define the functions first and then use them, but that is a matter of taste, as long it's not all mixed up.</p>\n<p>More, smaller functions would also be helpful. Reading the data should be in its own function and <code>closestCustomers</code> does too much (filtering, converting the objects to strings, and calling <code>writeInvitedCustomer</code>). This would also make testing easier.</p>\n<p>Using the array methods <code>filter()</code> and <code>map()</code> would help the code be more readable. Personally, I'd start with something like:</p>\n<pre><code>const inputFileName = "customers.txt";\nconst outputFileName = "output.txt";\n\nconst dublinOffice = {\n latitude: "53.339428",\n longitude: "-6.257664",\n};\nconst maxDistance = 100;\n\nconst invitedCustomers = readCustomers(inputFileName)\n .filter(withinKms(dublinOffice, maxDistance ))\n .sort(userIdComparator)\n .map(formatCustomerForOutput); // `map` may be considered to be moved inside `writeInvitedCustomers`\n\nwriteInvitedCustomers(invitedCustomers, outputFileName);\n\n\nfunction readCustomers(filename) {\n // ...\n}\n\nfunction withinKms(location, kms) {\n return (customer) => greatCircleDistanceCalc(customer.latitude, customer.longitude, location.latitude, location.longitude) <= kms;\n}\n\nfunction userIdComparator({user_id: userId1}, {user_id: userId2}) {\n return userId1 - userId2;\n}\n\nfunction formatCustomerForOutput({name, user_id}) {\n return `${name}:${user_id}`;\n}\n\n// etc.\n\n</code></pre>\n<p>One other point: I'm not familiar with node's <code>WriteStream</code>, but it looks wrong for me to assign the event handlers after using it by calling its <code>write</code> method. Can't <code>write</code> cause an error?</p>\n<p>NB: This is probably not your choice, if this was an interview task, but I find the file format for <code>customers.txt</code> (multiple JOSN objects in one file) strange. A straight forward JSON array would make more sense.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T09:30:59.147",
"Id": "250865",
"ParentId": "250858",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "250865",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T07:26:14.013",
"Id": "250858",
"Score": "3",
"Tags": [
"javascript",
"node.js"
],
"Title": "Finds customer who live within 100km and output them to a text file"
}
|
250858
|
<p>I'm practicing some python exercise and I have some doubts about the solution of reversing a number. Example, 42 -> 24, -314 -> -413.</p>
<p>The book has this solution:</p>
<blockquote>
<pre><code>def reverse(x: int) -> int:
result, x_remaining = 0, abs(x)
while x_remaining:
result = result * 10 + x_remaining % 10
x_remaining //= 10
return -result if x < 0 else result
</code></pre>
</blockquote>
<p>My solution:</p>
<pre><code>def reverse_digit(x: int) -> int:
s = str(abs(x))
result = s[::-1]
if x >= 0:
return int(result)
else:
return int("-" + result)
</code></pre>
<p>The book says that converting the number to string would be a brute-force solution but don't they have the same time complexity, O(n)?</p>
<p>Is the book solution that much better than mine (that in my opinion is much simpler and easy to read)?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T11:11:11.080",
"Id": "493556",
"Score": "2",
"body": "Since Code Review is a community where programmers improve their skills through peer review, we require that the **code be posted by an author or maintainer of the code**, that the code be embedded directly, and that the poster know why the code is written the way it is. We can not review code that's in a book, there are legal, moral and practical reasons for that. Please take a look at the [help/on-topic]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T13:39:38.703",
"Id": "493564",
"Score": "7",
"body": "@Mast I interpret this differently. The OP has their own code; understands their own code; and wants to know if it's better-structured than the reference implementation. The verbiage might be strengthened to indicate that, but I don't consider this off-topic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T13:44:08.170",
"Id": "493565",
"Score": "2",
"body": "What do you mean with \"n\" in O(n)? If you mean the number of digits, then neither is O(n)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T17:33:13.607",
"Id": "493594",
"Score": "0",
"body": "@saralance does the book contain any clauses (perhaps in the beginning) that limit its contents from being copied, re-distributed, etc.? [relevant meta](https://codereview.meta.stackexchange.com/a/9354/120114) (see comments)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T18:10:34.057",
"Id": "493598",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ I'm not a lawyer, but I think 1) such a clause is not even necessary due to default copyright and 2) neither such a clause nor default copyright prevent this from being fair use."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T19:50:26.983",
"Id": "493609",
"Score": "0",
"body": "@superbrain The law is not the only relevant thing here, site policy is too. See [this FAQ entry](https://codereview.meta.stackexchange.com/q/1294/52915)."
}
] |
[
{
"body": "<p>First, a note on complexity. Both your implementation and the reference implementation do indeed have O(n) complexity <em>in the number of input digits</em> in the best case, but O(log(n)) <em>in the range of the input number</em>.</p>\n<p>This depends, mind you, on the expected range of the input number. For "typical values" below the limit of machine precision, which these days will be <span class=\"math-container\">\\$2^{63}\\$</span> for most people, the contents of the reference implementation's inner loop will be constant-time. However, Python has automatic support for arbitrary precision, and if that support is used, the reference implementation will end up being super-linear in the worst case.</p>\n<p>As for reversal of a negative number, I think it makes less sense to automatically <code>abs()</code> than just to <code>raise</code>, because - if you interpret the number as a string - negative numbers are non-reversible. I say this knowing that it violates the reference implementation if you interpret it as a specification, but I don't think the specification makes much sense.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T13:50:56.547",
"Id": "493566",
"Score": "1",
"body": "First point is not true, second point goes against what's given by the book."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T13:52:17.267",
"Id": "493567",
"Score": "1",
"body": "@superbrain Why? Are you worried that division and modulation have non-constant time? This may be true in the worst case where the integer exceeds the precision of the machine and invokes Python's built-in arbitrary-precision machinery, but not in the best case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T13:55:20.260",
"Id": "493568",
"Score": "1",
"body": "Yes, they're not constant time. And your answer doesn't say best-case and best-case is not particularly interesting. And if you argue with a (not actually given) limit like that, both solutions are not just O(n) but O(1)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T13:59:59.120",
"Id": "493569",
"Score": "1",
"body": "@superbrain Well, I added some colour for both points."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T14:06:59.870",
"Id": "493571",
"Score": "1",
"body": "Seems you forgot the general complexity of the OP's solution."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T13:48:24.377",
"Id": "250869",
"ParentId": "250866",
"Score": "3"
}
},
{
"body": "<p>You could use this function which reverses a string (It's quite similar to your solution but a bit more compact):</p>\n<pre><code>def Reverse(Number):\n if Number > 0:\n return int(str(Number)[::-1])\n else:\n Number = str(abs(Number))\n return int("-" + Number[::-1])\n</code></pre>\n<p>Afterthoughts:\nI did a time test against both of your methods and mine and using this code:\n<a href=\"https://i.stack.imgur.com/AiHou.png\" rel=\"nofollow noreferrer\">https://i.stack.imgur.com/AiHou.png</a> with the last bit calculating the mean of the timings</p>\n<p>I got these results:</p>\n<pre><code>0.07816539287567138 #Book method\n0.10093494892120361 #Your method\n0.09026199817657471 #My method\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T16:07:29.960",
"Id": "250914",
"ParentId": "250866",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T11:01:12.913",
"Id": "250866",
"Score": "5",
"Tags": [
"python",
"comparative-review"
],
"Title": "Solution discussion on the best way to reverse a number in Python"
}
|
250866
|
<p>So what I'm trying to do is to get "bad" ip's from this page</p>
<p><a href="https://raw.githubusercontent.com/stamparm/ipsum/master/ipsum.txt" rel="nofollow noreferrer">https://raw.githubusercontent.com/stamparm/ipsum/master/ipsum.txt</a></p>
<p>Then I made a script that replaces ipsets to block, by replacing old ipset with one that holds the ip numbers from above mentioned place.</p>
<p>Was long time ago I wrote it. Now I came back to it. And I'm not really shure it works. Because when I run <code>ipset list > temporaryfile</code>
then I dont think all numbers in temporaryfile are found in newblacklist.txt
Here is the bash script:</p>
<pre><code>#!/bin/bash
# Variable holding the path to the textfile used in this script
textfile='/home/userName/Blacklist/newblacklist.txt'
# create and add blacklist if not created and add to iptables
created=$(ipset list -name | grep -c blacklist)
if [[ $created == 0 ]]; then
echo creating blacklist
ipset create blacklist hash:net
iptables -I INPUT -m set --match-set blacklist src -j DROP
else
echo blacklist already there
fi
# create and add tempblacklist if not created and add to iptables
created=$(ipset list -name | grep -c tempblacklist)
if [[ $created == 0 ]]; then
echo creating tempblacklist
ipset create tempblacklist hash:net
iptables -I INPUT -m set --match-set tempblacklist src -j DROP
else
echo tempblacklist already there
ipset flush tempblacklist
fi
# create a new blacklis.txt file if not there
# If there, clear it by means of rm and touch
if [ ! -e $textfile ]; then
echo creating new blacklist.txt file
touch $textfile
else
echo Emptying existing blacklist.txt file
rm $textfile;
touch $textfile;
fi
# Get the bad ip list from site and save in newblacklist.txt file
curl --compressed https://raw.githubusercontent.com/stamparm/ipsum/master/ipsum.txt 2>/dev/null>$textfile
#check if there is a list with new bad ips
#$created shows 0 if there is no such list
created=$(ipset list -name | grep -c newblacklist)
# Uses $created to check if there is a newblacklist list in ipset
# If there is no list creates one, otherwise flushes the existing one
if [[ $created == 0 ]]; then
echo Creating new newblacklist list in ipset
ipset create newblacklist hash:net
else
echo Flushing existing list
ipset flush newblacklist
fi
# Clean input from comments and other stuff
variable=$(grep -v "#" $textfile | grep -v -E "\s[1-2]$" | cut -f 1)
for ip in $variable;
do
ipset add newblacklist $ip
done
ipset swap blacklist tempblacklist
ipset flush blacklist
ipset swap newblacklist blacklist
ipset flush tempblacklist
</code></pre>
<p>The newblacklist.txt does seem to look identical to the content in the repo mentioned above.
Basically Im not confident the iptable gets updated to ban whats currently in the repo, when I run the script.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T11:38:37.007",
"Id": "250867",
"Score": "1",
"Tags": [
"bash",
"iptables"
],
"Title": "replace ipset with bash script"
}
|
250867
|
<p>I use the following method to scan and index video files and pass data to an array. I get video file duration, file name, files size.</p>
<p>Is there any better method, or do I need to improve?</p>
<pre><code>public static void load_Directory_Files(File directory) {
File[] fileList = directory.listFiles();
if(fileList != null && fileList.length > 0){
for (int i=0; i<fileList.length; i++){
if(fileList[i].isDirectory()){
load_Directory_Files(fileList[i]);
} else {
String name = fileList[i].getName().toLowerCase();
for (String extension: Constant.videoExtensions){
//check the type of file
if(name.endsWith(extension)){
Constant.allMediaList.add(fileList[i]);
String FileName = fileList[i].getName();
String size = Function.humanReadableByteCountSI(fileList[i].length());
String duration = Function.getDurationFF(fileList[i].getAbsolutePath());
String folderName = fileList[i].getParentFile().getName();
String path = fileList[i].getAbsolutePath();
Log.d(TAG, "load_Directory_Files: "+ duration + "" +size + "" + FileName);
Constant.allMediaListWithModel.add(new AllVideoModel(FileName, path, folderName, size, duration));
//when we found file
break;
}
}
}
}
}
}
public static String getDurationFF(String absolutePathThumb) {
try{
FFmpegMediaMetadataRetriever retriever = new FFmpegMediaMetadataRetriever();
retriever.setDataSource(absolutePathThumb);
String time = retriever.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_DURATION);
long timeInMillisec = Long.parseLong(time);
return convertMillieToHMmSs(timeInMillisec);
}catch(Exception e){
e.printStackTrace();
return null;
}
}
@SuppressLint("DefaultLocale")
public static String convertMillieToHMmSs(long millie) {
long seconds = (millie / 1000);
long second = seconds % 60;
long minute = (seconds / 60) % 60;
long hour = (seconds / (60 * 60)) % 24;
if (hour > 0) {
return String.format("%02d:%02d:%02d", hour, minute, second);
} else {
return String.format("%02d:%02d" , minute, second);
}
}
@SuppressLint("DefaultLocale")
public static String humanReadableByteCountSI(long bytes) {
if (-1000 < bytes && bytes < 1000) {
return bytes + " B";
}
CharacterIterator ci = new StringCharacterIterator("kMGTPE");
while (bytes <= -999_950 || bytes >= 999_950) {
bytes /= 1000;
ci.next();
}
return String.format("%.1f %cB", bytes / 1000.0, ci.current());
}
</code></pre>
<p>The above method works but it takes time to scan and index. So how can I reduce indexing time?</p>
<pre><code>public static String[] videoExtensions = {".mp4",".ts",".mkv",".mov",
".3gp",".mv2",".m4v",".webm",".mpeg1",".mpeg2",".mts",".ogm",
".bup", ".dv",".flv",".m1v",".m2ts",".mpeg4",".vlc",".3g2",
".avi",".mpeg",".mpg",".wmv",".asf"};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-26T14:11:50.197",
"Id": "494350",
"Score": "2",
"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*](http://meta.codereview.stackexchange.com/a/1765)."
}
] |
[
{
"body": "<h1>Naming</h1>\n<p>The method name <code>load_Directory_Files</code> is a bit odd. To follow general Java naming conventions, it would be something like <code>loadDirectoryFiles</code>. This is called camel case.</p>\n<h1>File filtering</h1>\n<p>You can use a <a href=\"https://developer.android.com/reference/java/io/FileFilter\" rel=\"nofollow noreferrer\"><code>FileFilter</code></a> to accept or discard files for the\n<a href=\"https://developer.android.com/reference/java/io/File#listFiles(java.io.FileFilter)\" rel=\"nofollow noreferrer\"><code>listFiles</code></a> call, no need to do it yourself:</p>\n<pre><code>import java.io.File;\nimport java.io.FileFilter;\nimport java.util.List;\nimport java.util.Arrays;\n\npublic class VideoOrDirectoryFilter implements FileFilter {\n\n private static final List<String> ALLOWED_EXTENSIONS = Arrays.asList(\n ".mp4",".ts",".mkv",".mov",".3gp",".mv2",".m4v",".webm",\n ".mpeg1",".mpeg2",".mts",".ogm", ".bup", ".dv",".flv",\n ".m1v",".m2ts",".mpeg4",".vlc",".3g2",".avi",".mpeg",\n ".mpg",".wmv",".asf"\n );\n\n @Override\n public boolean accept(File file) {\n return file.isDirectory() \n || ALLOWED_EXTENSIONS.contains(file.getName().toLowerCase());\n }\n}\n</code></pre>\n<h1>Null check</h1>\n<p>In <code>loadDirectoryFiles</code>, you can return early if the <code>listFiles</code> call is null:</p>\n<pre><code>File[] files = directory.listFiles(new VideoOrDirectoryFilter());\nif (files == null) return;\n</code></pre>\n<h1>Looping</h1>\n<p>Instead of the for loop with an index variable, you could use a <a href=\"https://docs.oracle.com/javase/8/docs/technotes/guides/language/foreach.html\" rel=\"nofollow noreferrer\"><code>foreach</code></a> loop. That makes for cleaner code, as you directly get the object in the list. Also, you don't need to check the length of the list before looping. If it's empty, the loop will be a no-op.</p>\n<pre><code>for (File file : files) {\n // Do your thing with file here\n}\n</code></pre>\n<h1>Reimplementation</h1>\n<p>Here's a reimplementation of the <code>loadDirectoryFiles</code> method with the above enhancements included.</p>\n<pre><code>public static void loadDirectoryFiles(File directory) {\n File[] files = directory.listFiles(new VideoOrDirectoryFilter());\n\n if (files == null) return;\n\n for (File file : files) {\n if (file.isDirectory()){\n loadDirectoryFiles(file);\n } else { \n Constant.allMediaList.add(file);\n String fileName = file.getName();\n String size = Function.humanReadableByteCountSI(file.length());\n String duration = Function.getDurationFF(file.getAbsolutePath());\n String folderName = file.getParentFile().getName();\n String path = file.getAbsolutePath();\n Log.d(TAG, "load_Directory_Files: "+ duration + "" +size + "" + fileName);\n Constant.allMediaListWithModel.add(new AllVideoModel(fileName, path, folderName, size, duration));\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T14:54:33.140",
"Id": "495220",
"Score": "0",
"body": "This is quite good. The only thing I'd suggest changing is `\"load_Directory_Files: \"+ duration + \"\" +size + \"\" + fileName` - that should just be a `format` call."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T14:42:20.540",
"Id": "495555",
"Score": "0",
"body": "i tried but but no files are listed, here is how i implement https://gist.github.com/sanoj26692/5e5e9baedf0d3821213042581d248fc4"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-21T17:52:18.657",
"Id": "497442",
"Score": "0",
"body": "Can you make a github. Bcoz I tried ur code and that doesn't index any files"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T09:16:42.843",
"Id": "251328",
"ParentId": "250870",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T15:06:49.370",
"Id": "250870",
"Score": "8",
"Tags": [
"java",
"android"
],
"Title": "Scanning and indexing files video"
}
|
250870
|
<p>I'm diving into "modern CPP", with wide usage of templates and containers,
So I started with <a href="https://en.wikipedia.org/wiki/Finite_impulse_response" rel="nofollow noreferrer">FIR filter</a>.</p>
<blockquote>
<p>In signal processing, a finite impulse response (FIR) filter is a filter whose impulse response (or response to any finite length input) is of finite duration, because it settles to zero in finite time. This is in contrast to infinite impulse response (IIR) filters, which may have internal feedback and may continue to respond indefinitely (usually decaying).</p>
</blockquote>
<p>So I define FIR filter as a class and apply it to single scalar value or to the vector itself</p>
<p>Could you please review my code in terms of C++ coding?</p>
<pre><code>#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
#include <complex>
#include <cmath>
#include <iomanip>
#include <sstream>
// - Class method : operator(), constructor, various methods
// - Templates class and function
// - List and vector containers
// - Functors
template <typename T> std::string to_str(T & arr){
std::ostringstream os;
os << "["; for (auto x: arr){ os<<" "<< x <<" "; } os << "]\n";
return os.str();
}
template <class T> class FIR {
public:
std::vector< T > coeff; // Array of coefficents is static all the time
std::list< T > taps; // Array of is are shifting each tick
int order;
FIR(std::vector< T > v)
{
coeff = v;
order = coeff.size();
taps = std::list< T > (coeff.size(), 0);
}
void reset(){
taps = std::list< T > (coeff.size(), 0);
}
void append( T x){
taps.push_front( x);
taps.pop_back();
}
auto sum_product(){
T psum = 0;
typename std::list< T >::iterator t;
typename std::vector< T >::iterator c;
// Can we do better here?
for ( c =coeff.begin(), t =taps.begin();
c!=coeff.end(), t !=taps.end();
++c , ++t ){
psum += (*c) * (*t);
}
return psum;
}
auto operator() ( T x){
append(x);
T psum = sum_product();
return psum;
}
auto operator() (std::vector< T > x){
std::vector< T > y( x.size(), 0);
for (int i = 0; i<x.size(); ++i){
y[i] = operator()(x[i]);
}
return y;
}
};
int main()
{
std::vector<double> coeff = {0.0,1.0,5.0, 1.0, 0.0};
FIR<double> fir(coeff);
std::cout <<"Coeff: " << to_str(fir.coeff);
std::cout <<"Taps : " << to_str(fir.taps);
std::cout<<"\nTRANSFORM IN THE LOOP \n";
std::vector<double> x_array = {0,1,2,3,4,5,6,0,0,0,0,0,0,13};
for (auto x:x_array){
auto p = fir(x);
std::cout<<p<<" ";
}
std::cout<<"\n";
fir.reset();
std::cout<<"\nTRANSFORM WITH FUNCTOR FOR SCALAR\n";
std::vector<double> y_array( x_array.size(), 0);
std::transform(x_array.begin(), x_array.end(), y_array.begin(), fir);
std::cout << to_str(y_array);
fir.reset();
std::cout<<"\nAPPLY FUNCTOR FOR CONTTAINER \n";
auto y_2 = fir(x_array);
std::cout << to_str(y_2);
fir.reset();
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T16:38:30.673",
"Id": "493587",
"Score": "2",
"body": "Welcome to the Code Review site. For future reference the title should give some indication of what the code does. It is best to give a brief description of what you are quoting as well. You should read [How do I ask a good question](https://codereview.stackexchange.com/help/how-to-ask) for more tips on asking questions. Nice job overall."
}
] |
[
{
"body": "<pre><code> for ( c =coeff.begin(), t =taps.begin(); \n c!=coeff.end(), t !=taps.end();\n ++c , ++t ){\n psum += (*c) * (*t);\n }\n</code></pre>\n<p>I'm guessing the comma in the for loop condition should be an <code>&&</code>. It might be cleaner to use an index in this loop instead (especially if the two arrays are always the same size).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T17:19:49.993",
"Id": "250873",
"ParentId": "250871",
"Score": "1"
}
},
{
"body": "<ul>\n<li><p><strong><code>class FIR</code></strong> has nothing private. Should it be <code>struct</code>?</p>\n</li>\n<li><p>The line</p>\n<pre><code> std::list< T > taps; // Array of is are shifting each tick\n</code></pre>\n<p>is somewhat contradictory. It <code>taps</code> a list or an array?</p>\n</li>\n<li><p>I don't see how <code>order</code> is used. Does it need to be a class member at all?</p>\n</li>\n<li><p><strong><code>operator()(T x)</code></strong> is very confusing. I would argue that it shall not be an operator at all; if you really want this to be an operator, consider <code>operator<<</code>. A metaphor of <em>shifting into a filter</em> is much more understandable than <em>calling a filter</em>.</p>\n</li>\n<li><p><em>// Can we do better here?</em> <a href=\"https://en.cppreference.com/w/cpp/algorithm/inner_product\" rel=\"nofollow noreferrer\">Yes</a>.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T00:50:46.600",
"Id": "250886",
"ParentId": "250871",
"Score": "3"
}
},
{
"body": "<h1>Use member initializer lists in constructors where possible</h1>\n<p>Using <a href=\"https://en.cppreference.com/w/cpp/language/constructor\" rel=\"nofollow noreferrer\">member initializer lists</a> can be more optimal and avoid issues when an error is thrown in a constructor. Use it where possible. For example:</p>\n<pre><code>FIR(const std::vector<T> &v): coeff(v), taps(coeff.size()), order(coeff.size()) {}\n</code></pre>\n<p>Make sure you initialize the members in the same order as you declared them.</p>\n<h1>Use <code>const</code> references when appropriate</h1>\n<p>Passing a vector by value means a complete copy has to be created. This wastes CPU time and memory. Use a <code>const</code> reference in that case, as I've done above.</p>\n<h1>Avoid storing redundant information</h1>\n<p>There is no need to store <code>order</code>, you can already get the same value by using <code>coeff.size()</code>.</p>\n<h1>Make member variables <code>const</code> if they should never change</h1>\n<p>Since the coefficients never change after creating an instance of <code>FIR</code>, you can make <code>coeff</code> <code>const</code>.</p>\n<h1>Make functions that don't change any member variables <code>const</code></h1>\n<p>Not only variables, but member functions themselves can be marked <code>const</code>. Do this when they don't change any member variables. This helps the compiler generate more optimal code, and will allow it to generate error messages if you accidentily do modify a member variable. For example:</p>\n<pre><code>auto sum_product() const {\n ...\n}\n</code></pre>\n<h1>Use a <code>std::queue</code> for <code>taps</code></h1>\n<p>A <code>std::list</code> has <span class=\"math-container\">\\$\\mathcal{O}(1)\\$</span> insertion and removal at both ends, but the problem is that every element needs a separate heap allocation, pointers need to be kept up to date, and when looping over the elements in a list, they are not nicely layed out in memory. There is a better container for this: <a href=\"https://en.cppreference.com/w/cpp/container/deque\" rel=\"nofollow noreferrer\"><code>std::deque</code></a>. However, since you use it as a queue, use the <a href=\"https://en.cppreference.com/w/cpp/container/queue\" rel=\"nofollow noreferrer\"><code>std::queue</code></a> "container adapter" instead, so it is clear what the function of <code>taps</code> is.</p>\n<p>If performance is really crucial, perhaps using a <code>std::vector</code> would be best, and use it as a <a href=\"https://en.wikipedia.org/wiki/Circular_buffer\" rel=\"nofollow noreferrer\">circular buffer</a>. But don't do that unless you really need it, because it will complicate your code.</p>\n<h1>Use STL algorithms where appropriate</h1>\n<p>The STL not only provides handy containers, but also <a href=\"https://en.cppreference.com/w/cpp/algorithm\" rel=\"nofollow noreferrer\">algorithms</a> that you can use, so you don't have to write them out yourself. For example, <code>sum_product()</code> can be replaced with a call to <a href=\"https://en.cppreference.com/w/cpp/algorithm/inner_product\" rel=\"nofollow noreferrer\"><code>std::inner_product()</code></a>:</p>\n<pre><code>auto operator()(T x) {\n append(x);\n return std::inner_product(coeff.begin(), coeff.end(), taps.begin());\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T11:36:37.480",
"Id": "250904",
"ParentId": "250871",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "250904",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T16:18:30.013",
"Id": "250871",
"Score": "5",
"Tags": [
"c++",
"c++11",
"c++17"
],
"Title": "A FIR filter using Modern C++ features"
}
|
250871
|
<p>I am working on a Document Writer that writes documentation for software deliveries. It all works in its current state but I am needing to refactor a C# method. The app reaches to TFS and pulls down a work item and writes it in Word.</p>
<p>This method deals with writing the headings for sections and subsections of the document. You can see lambda usage at the beginning that gathers the info to be written and at the end the original setup before refactoring to its current state is commented out in the end. The method reads an AreaPath listed as <code>root\space1\space2\...</code> and splits at the <code>\</code> to get the length. Then on the document it is written as "3.0 Root...3.1 Space 1...3.2 Space 2...".</p>
<pre><code>private void InsertReqSection()
{
//connectToServerManual();
System.Data.DataTable AreaPathsList = GetAllAreaPaths(project.ProjectName);
InsertText("Functional Requirements", WdBuiltinStyle.wdStyleHeading1);
if (project.AllLinksRequirements.Count > 0)
{
List<Requirement> sortedList = project.AllLinksRequirements.OrderBy(o => o.Category).ThenBy(o => o.CharId).ToList();
List<Requirement> areaPathOrderedList = new List<Requirement>();
List<string> sectionHeadingList = new List<string>();
string currentArea = string.Empty;
string nextArea = string.Empty;
Table table = null;
for (int i = 0; i < AreaPathsList.Rows.Count; i++)
{
foreach (Requirement req in sortedList)
{
if (req.AreaPath == AreaPathsList.Rows[i]["Path"].ToString())
{
areaPathOrderedList.Add(req);
}
}
}
foreach(Requirement req in areaPathOrderedList)
{
nextArea = req.AreaPath;
string[] areaNames = nextArea.Split('\\');
if (nextArea != currentArea)
{
int areaPathLength = areaNames.Length;
if (!sectionHeadingList.Contains(areaNames[1]))
{
sectionHeadingList.Clear();
sectionHeadingList.Add(areaNames[1]);
WriteUsingHeadingStyle2(areaNames[1]);
}
if (areaPathLength >= 3 && !sectionHeadingList.Contains(areaNames[2]))
{
sectionHeadingList.Add(areaNames[2]);
WriteUsingHeadingStyle3(areaNames[2]);
}
switch (areaPathLength)
{
case 4:
sectionHeadingList.Add(areaNames[3]);
WriteUsingHeadingStyle4(areaNames[areaNames.Length - 1]);
break;
case 5:
sectionHeadingList.Add(areaNames[4]);
WriteUsingHeadingStyle5(areaNames[areaNames.Length - 1]);
break;
case 6:
if (!sectionHeadingList.Contains(areaNames[5]))
WriteUsingHeadingStyle5(areaNames[areaNames.Length - 2]);
WriteUsingHeadingStyle6(areaNames[areaNames.Length - 1]);
break;
default:
break;
}
// if (areaNames.Length > 4)
// {
// if (areaNames.Length == 6)
// {
// WriteUsingHeadingStyle5(areaNames[areaNames.Length - 2]);
// WriteUsingHeadingStyle6(areaNames[areaNames.Length - 1]);
// }
// else if (areaNames.Length == 5)
// WriteUsingHeadingStyle5(areaNames[areaNames.Length - 1]);
// }
// else if (areaNames.Length == 4)
// WriteUsingHeadingStyle4(areaNames[areaNames.Length - 1]);
currentArea = nextArea;
table = InsertAndFormatReqTable();
}
AddReqRow(table, req);
}
}
else
{
InsertText("There are no requirements listed in the Project.", WdBuiltinStyle.wdStyleNormal);
}
}
</code></pre>
|
[] |
[
{
"body": "<h2><code>var</code> when appropriate</h2>\n<p>These lines:</p>\n<pre><code> List<Requirement> areaPathOrderedList = new List<Requirement>();\n List<string> sectionHeadingList = new List<string>();\n</code></pre>\n<p>have an obvious type, so you can replace them with <code>var</code>. For your other variables, keep them as-is since their type is not obvious on inspection.</p>\n<h2>C-style loops</h2>\n<pre><code> for (int i = 0; i < AreaPathsList.Rows.Count; i++)\n</code></pre>\n<p>should be replaced with a <code>foreach</code>, since you do not use the index.</p>\n<h2>Parsing</h2>\n<p>Looking at how you use fixed indices into the <code>areaNames</code> array, it's likely that <code>req.AreaPath</code> is a string that needs to be parsed out into its own class with meaningful field names rather than numerical indices into a split string. Given your current code I have no idea what those fields would be, but this is what traditional OOP would push you toward. It would be more legible and maintainable.</p>\n<h2>Early-return</h2>\n<p>This is a matter of style, but I find this:</p>\n<pre><code> if (project.AllLinksRequirements.Count > 0)\n {\n // most of the method\n }\n else\n {\n InsertText("There are no requirements listed in the Project.", WdBuiltinStyle.wdStyleNormal);\n }\n</code></pre>\n<p>to be more legible as</p>\n<pre><code>if (project.AllLinksRequirements.Count < 1)\n{\n InsertText("There are no requirements listed in the Project.", WdBuiltinStyle.wdStyleNormal);\n return;\n}\n\n// The rest of the method\n</code></pre>\n<p>It allows you a good deal of de-indentation, as well as dealing with the simpler case first.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T19:48:16.197",
"Id": "493607",
"Score": "0",
"body": "Thank you. These are all great suggestions. My question is for your suggestion of C-style loops, is my index of `[i]` not being used within `AreaPathsList.Rows[i][\"Path\"].ToString()`? When I change to a `foreach` it becomes an undefined variable and I lose the ability to keep track of where in the original sorted list I am at."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T19:52:11.333",
"Id": "493610",
"Score": "0",
"body": "When you replace `AreaPathsList.Rows[i]` with your loop variable, all of your references to `i` will go away."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T19:15:25.157",
"Id": "250879",
"ParentId": "250877",
"Score": "2"
}
},
{
"body": "<p>Quick remarks:</p>\n<ul>\n<li><p>Do not call things "xxxxList". The type might change and thus the name might become invalid, but more importantly we don't call a collection of items an "xxxxList" in real life, we simply use the plural: <code>areas</code>, <code>requirements</code>, etc.</p>\n</li>\n<li><p>Use descriptive names: <code>sortedList</code> tells me next to nothing about the contents of that collection.</p>\n</li>\n<li><p>Be consistent: you use both "sorted" and "ordered", which suggests these are different concepts to you. Which means the next developer needs to figure out what distinction you make and why. (Then again, such terms really shouldn't be part of a name anyway.)</p>\n</li>\n<li><p>Why does <code>GetAllAreaPaths</code> return a <code>DataTable</code>? Why not return a collection of a custom class?</p>\n</li>\n<li><p>Things like <code>areaNames[1]</code> are non-descriptive. Store these values in a properly named variable.</p>\n</li>\n<li><p>I see methods like <code>WriteUsingHeadingStyle2</code>, <code>WriteUsingHeadingStyle3</code>, etc. Why not have a <code>Write</code> method that has the <code>HeadingStyle</code> as the second parameter?</p>\n</li>\n<li><p>Do not pointlessly abbreviate, e.g. <code>AddReqRow</code>. Your code will not execute faster because you abbreviated <code>Requested</code> to <code>Req</code>. Or is it <code>Required</code>?</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T07:51:18.427",
"Id": "250894",
"ParentId": "250877",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T18:56:45.247",
"Id": "250877",
"Score": "2",
"Tags": [
"c#"
],
"Title": "Refactoring Document Writer headings"
}
|
250877
|
<p>I wrote this java Class to solve a standard 9x9 sudoku board.
It uses backtracking to solve each field of the board.</p>
<p>I am really interested in feedback for the "isValid" and "isBlockValid" Methods, because they are redundant.</p>
<p>Here is my code on <a href="https://github.com/apocalyps0/SudokuSolver" rel="noreferrer">github</a>.</p>
<p>Also here is the code:</p>
<pre><code>public class SudokuSolver {
private boolean solve(int[][] board, int counter){
int col = (int) counter / board.length;
int row = counter % board.length;
if (col >= board.length){
printBoard(board);
return true;
}
if (board[row][col] == 0) {
for (int n = 1; n <= board.length; n++) {
if (isValid(n,row,col, board)){
board[row][col] = n;
if (solve(board,counter+1)){
return true;
}
}
board[row][col] = 0;
}
}else{
if (solve(board,counter+1)){
return true;
}
}
return false;
}
public void startSolving(int[][] board){
if(!solve(board, 0)){
System.out.println("no solution");
}
}
private boolean isValid(int n, int row, int col, int[][] board){
int i;
int j;
for (i = 0; i < board.length; i++) {
if(board[row][i] == n){
return false;
}
}
for (i = 0; i < board.length; i++) {
if(board[i][col] == n){
return false;
}
}
//check if block is valid - do not know any other way for solving this
// check block 1
if (row >= 0 && col >= 0 && row <= 2 && col <= 2){
if(!isBlockValid(n, row, col, board, 0, 2, 0, 2)){
return false;
}
}
// check block 2
if (row >= 0 && col >= 3 && row <= 2 && col <= 5){
if(!isBlockValid(n, row, col, board, 0, 2, 3, 5)){
return false;
}
}
// check block 3
if (row >= 0 && col >= 6 && row <= 2 && col <= 8){
if(!isBlockValid(n, row, col, board, 0, 2, 6, 8)){
return false;
}
}
// check block 4
if (row >= 3 && col >= 0 && row <= 5 && col <= 2){
if(!isBlockValid(n, row, col, board, 3, 5, 0, 2)){
return false;
}
}
// check block 5
if (row >= 3 && col >= 3 && row <= 5 && col <= 5){
if(!isBlockValid(n, row, col, board, 3, 5, 3, 5)){
return false;
}
}
// check block 6
if (row >= 3 && col >= 6 && row <= 5 && col <= 8){
if(!isBlockValid(n, row, col, board, 3, 5, 6, 8)){
return false;
}
}
// check block 7
if (row >= 6 && col >= 0 && row <= 8 && col <= 2){
if(!isBlockValid(n, row, col, board, 6, 8, 0, 2)){
return false;
}
}
// check block 8
if (row >= 6 && col >= 3 && row <= 8 && col <= 5){
if(!isBlockValid(n, row, col, board, 6, 8, 3, 5)){
return false;
}
}
// check block 9
if (row >= 6 && col >= 6 && row <= 8 && col <= 8){
if(!isBlockValid(n, row, col, board, 6, 8, 6, 8)){
return false;
}
}
return true;
}
private boolean isBlockValid(int n, int row, int col, int[][] board, int starti, int stopi, int startj, int stopj){
for (int i = starti; i <= stopi; i++) {
for (int j = startj; j <= stopj; j++) {
if (board[i][j] == n) {
return false;
}
}
}
return true;
}
private void printBoard(int[][] board){
System.out.println();
for (int[] row : board){
System.out.print("|");
for (int col : row){
System.out.print(col);
System.out.print("|");
}
System.out.println();
}
System.out.println();
}
public static void main(String[] args) {
int[][] board =
{{2,0,5,0,0,0,0,0,0},
{3,0,8,6,0,0,9,0,0},
{0,0,0,1,0,0,4,0,0},
{0,0,0,0,5,0,0,1,0},
{0,0,0,0,9,0,0,2,0},
{8,7,0,0,2,0,0,0,0},
{0,0,0,0,8,9,0,0,3},
{0,0,6,0,0,3,0,0,5},
{5,0,4,0,0,0,0,0,1}};
SudokuSolver sudokuSolver = new SudokuSolver();
sudokuSolver.startSolving(board);
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T20:33:35.580",
"Id": "493617",
"Score": "0",
"body": "For the duplicate bit of isValid where you check each block. Consider, a block can be described by the top left position, given the top left position you can determine the squares to look at. So, consider writing something which can take (for example, there are other, perhaps better, ways) [[0, 0], [0, 3], [0, 6], [3, 0], ... ] and check the block described by each pair is a good block."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T20:36:15.970",
"Id": "493618",
"Score": "0",
"body": "It is worth saying, that you could have probably come to this conclusion yourself with an intermediate refactor. Where you did like [[0, 0, 2, 2], [0, 3, 2, 5], ...] (taking your bounds from each for loop) and then went through the array of quadruples and called isBlockValid. There's a good lesson here about how repeatedly refactoring will lead you to cleaner and cleaner solutions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T23:56:13.150",
"Id": "493636",
"Score": "0",
"body": "I understand what you mean by describing a block only by the top left position but I would still need all the if statements to determine in which block the field-to-prove is. Or am I missing something?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T00:01:29.777",
"Id": "493639",
"Score": "0",
"body": "The thing is, you can work out which block you need to check, and then just check that one. Let's just stick with your isBlockValid for now, have a function workItOut which takes the row and col and then returns the correct 4 numbers to pass into isBlockValid for that row, col. \n\nThen in your code, call workItOut, get the 4 numbers, call isBlockValid with those 4 numbers, if it's not true return false."
}
] |
[
{
"body": "<p>To remove duplication,</p>\n<pre><code> // check block 1\n if (row >= 0 && col >= 0 && row <= 2 && col <= 2){\n if(!isBlockValid(n, row, col, board, 0, 2, 0, 2)){\n return false;\n }\n }\n</code></pre>\n<p>you can rewrite these nine sections as this single block</p>\n<pre><code>final int blockRow = 3 * (row / 3);\nfinal int blockCol = 3 * (col / 3);\nreturn isBlockValid(n, row, col, board, blockRow, blockRow + 2, blockCol, blockCol + 2);\n</code></pre>\n<p>Note that it would probably be easier to just pass in <code>blockRow</code> and <code>blockCol</code> and do the + 2 in the <code>isBlockValid</code> method.</p>\n<p>I would also consider passing the board into the constructor so that you don't have to pass it around constantly.</p>\n<p>And of course, you don't use <code>row</code> or <code>col</code> in your <code>isBlockValid</code> method, so there is no reason to pass them. So something like</p>\n<pre><code>return isBlockValid(n,\n VERTICAL_SIZE * (row / VERTICAL_SIZE),\n HORIZONTAL_SIZE * (col / HORIZONTAL_SIZE));\n</code></pre>\n<p>and</p>\n<pre><code>private boolean isBlockValid(int n, int row, int col) {\n for (int bottom = row + VERTICAL_SIZE; row < bottom; row++) {\n for (int right = col + HORIZONTAL_SIZE; col < right; col++) {\n if (board[row][col] == n) {\n return false;\n }\n }\n }\n\n return true;\n}\n\npublic final int HORIZONTAL_SIZE = 3;\npublic final int VERTICAL_SIZE = 3;\n</code></pre>\n<p>This also gets rid of your magic numbers. Perhaps this too should be set in the constructor. But even constants are going to be easier to change later.</p>\n<p>An exclusive upper bound is more idiomatic and allows us to reuse the same constants.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T04:27:59.157",
"Id": "250891",
"ParentId": "250880",
"Score": "7"
}
},
{
"body": "<p><em>I realise that this isn't as much of a review as a rewrite, but I still think it's on topic as an answer on this site as sometimes the right answer to your problem is to take a completely different approach that avoids the problems in the original attempt by design rather than tweaks.</em></p>\n<p>I wrote a sudoku solver a long time ago. One of the things I did to reduce duplication and make processing efficient is to use an appropriate data structure.</p>\n<p>The board consists of cells that contain a list of candidate-sets and a nullable number. The candidate sets each contain the set of numbers allowed for coming/row/block. Something like this:</p>\n<pre><code>class Cell{\n List<Set<Integer>> candidates;\n Integer value=null;\n\n // During board setup, generate one set for each row, column and block\n // and initialize with 1...9\n // Pass appropriate list of row, column and block for each cell\n Cell(List<Set<Integer>> c){\n candidates = c;\n }\n\n void set(int v){\n for(var c : candidates) {\n c.remove(v);\n }\n value = v;\n }\n\n boolean isSet(){\n return value != null;\n }\n\n Set<Integer> allowed(){\n var ans = new HashSet<>(candidates.get(0));\n for(var c : candidates) {\n ans.retainAll(c);\n } \n return ans;\n }\n}\n</code></pre>\n<p>This allows fast computation of the allowed values you can try in the back tracking search (this essentially implements constraint propagation for first order constraints) and it does so in a general way over rows, columns and blocks making the code simpler.</p>\n<p>Note that the code here represents a change in approach. Instead of checking validity at every step, we prevent generating invalid states to begin with. You'll detect that you've reached a dead end in the solving prices when the allowed set of numbers for a cel that is empty is the empty set.</p>\n<p>Pseudocode for a solver could then be:</p>\n<pre><code>class Board{\n List<Cell> board;\n \n Board deepCopy(){...}\n\n List<Cell> getUnsolved(){\n return board.stream().filter(X -> !X.isSet()).collect(toList());\n }\n \n\n boolean isSolved(){ return getUnsolved().isEmpty (); }\n\n Board solve(){\n var b = deepCopy ();\n b.deterministicSolve();\n List<Cell> unsolved = b.getUnsolved();\n if (unsolved.isEmpty()){\n return b;\n }\n // Sorting makes solving faster by reducing the branching factor\n // close to the search root and allowing constraint propagation to\n // work more efficiently\n unsolved.sort(byLowestAllowedNumberOfValues);\n Cell c = unsolved.get(0); // pick most constrained cell to guess values for\n for(var v : c.allowed()){\n c.set(v);\n var ans = b.solve();\n if(ans.isSolved()){\n return ans;\n }\n }\n throw new Exception("no solution exists!");\n } \n\n void deterministicSolve (){\n boolean changed = true;\n while(changed){\n changed=false;\n for(var c : board){\n var allowed = c.allowed();\n if(allowed.size()==1){\n c.set(allowed.get(0));\n changed=true;\n }\n }\n }\n }\n}\n</code></pre>\n<p>Note that the pseudocode is generic, free repetition, and iteration over rows, columns and blocks, and free of magic numbers, you only need the magic constants when setting up the board.</p>\n<p>About the solving process: the deterministic part solves any cells for which there is only one possible value, I found that this was a necessary step as it severely reduces both the branching factor and tree depth of the search space, significantly improving run time.</p>\n<p>In the depth first search (DFS) part of the solve (<code>solve()</code> function) we take care to guide the tree exploration to select cells with few possible values first. This results in a narrower search tree and as solving the tightly constrained values first typically makes other cells tightly constrained this effect applies throughout the search tree. Essentially it reduces the search space and a small cost per search node. The use of the sets for the constraints in the cells efficiently allows computation of the allowed set of values which makes the above code cleaner and efficient.</p>\n<p>Sorry for the sloppiness in the naming and formatting of the code, I wrote this on a phone.</p>\n<p>Edit: note that there are other techniques that can be added to the deterministic solve function to make the runtime even faster. I just showed the lowest hanging fruit.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T09:51:40.003",
"Id": "250899",
"ParentId": "250880",
"Score": "4"
}
},
{
"body": "<p>One approach to unify all the various validity tests is to introduce what I'd call "groups":</p>\n<ul>\n<li>Each row is a group.</li>\n<li>Each column is a group.</li>\n<li>Each of the 3*3 blocks is a group.</li>\n</ul>\n<p>Each group consists of 9 cells, and can be represented by a list of 9 coordinates.</p>\n<p>You can create the 27 groups either by manually writing down the coordinate lists (tedious and error-prone), or (better) by generating them with a few loops in an initialization step.</p>\n<p>Then validating a number for a given coordinate means:</p>\n<ul>\n<li>Find all groups containing this coordinate (there should always be 3 hits).</li>\n<li>Check whether the number is already present at one of the group's coordinates.</li>\n</ul>\n<p>Rows, columns and blocks get treated the same, by the very same piece of code, as now they are just lists of coordinates.</p>\n<p>The indirection of going through corrdinates lists might cost you a tiny bit of performance, but I'm not even sure of that. If performance is an issue, use a profiler.</p>\n<p>EDIT</p>\n<p>I just recognized that this is basically part of EmilyL's approach, so look at her answer instead.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T10:39:41.163",
"Id": "250901",
"ParentId": "250880",
"Score": "2"
}
},
{
"body": "<p>In addition to your specific question on the <code>isValid()</code> methods, a few hints on code style, as this is the CodeReview site.</p>\n<p>Your <code>solve()</code> method is well done regarding its recursive calls, but it mixes computation and user interface (output) when it finally found the solution.</p>\n<p>In professional development, we separate these concerns as much as possible, e.g. to have one solver core, providing solutions to different user interfaces, e.g. console output, graphical user interface, or web service.</p>\n<p>Changing that in your code is easy. When you found the solution, just return true. All recursion layers above will simply pass this upwards, and the top-level caller (<code>startSolving()</code> in your case) will receive the information about success or failure, and in the success case, the board will contain the solution. So you can just move the\n<code>printBoard()</code> call out there, and then <code>solve()</code> is free of UI code and re-usable in other environments.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T12:09:39.980",
"Id": "250906",
"ParentId": "250880",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "250891",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T20:23:53.230",
"Id": "250880",
"Score": "6",
"Tags": [
"java",
"backtracking"
],
"Title": "Solving a sudoku with backtracking"
}
|
250880
|
<p>I just started to use WordPress to start building a website, but as I need to use the <code>get_header()</code> function to retrieve the <code><head></code> content and I have a very large project, I wanted to put a CSS file depending on the page that is being displayed. After a few tries I came up with a solution, but I think that I can do it in a better way and I need your help to optimize it.</p>
<p>Here is my PHP snippet that goes into the functions.php file:</p>
<pre><code>function website_files_per_page() {
$pagelist = get_pages();
$index = sizeof($pagelist);
while ($index --) {
$pagename = $pagelist[$index]->post_name;
if (is_page($pagename)){
$styleName = "website_".$pagename."_styles";
$styleDir = get_theme_file_uri("/style/".$pagename.".css");
wp_enqueue_style($styleName, $styleDir);
break;
}
}
}
add_action("wp_print_styles", "website_files_per_page");
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T21:31:28.683",
"Id": "493621",
"Score": "0",
"body": "Welcome to Code Review! I notice the [tag:performance] tag is used - is there a concern about execution time here being higher than desired?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T21:59:14.987",
"Id": "493626",
"Score": "0",
"body": "I'd like my code to be O(1) not O(n)"
}
] |
[
{
"body": "<h2>Simpler approach</h2>\n<p>I haven’t tested this but based on <a href=\"https://stackoverflow.com/a/9628266/1575353\">this SO answer</a> using <a href=\"https://codex.wordpress.org/Global_Variables#Inside_the_Loop_variables\" rel=\"nofollow noreferrer\"><code>global $post</code></a> and <code>$post->page_title</code> to set <code>$pagename</code> should allow you to remove the loop.</p>\n<pre><code>function website_files_per_page() {\n global $post;\n $pagename = $post->post_title;\n if ($pagename) {\n return; //no page name\n }\n $styleName = "website_".$pagename."_styles";\n $styleDir = get_theme_file_uri("/style/".$pagename.".css");\n wp_enqueue_style($styleName, $styleDir);\n}\nadd_action("wp_print_styles", "website_files_per_page");\n</code></pre>\n<p>That would allow the code to run in <span class=\"math-container\">\\$O(1)\\$</span> time instead of <span class=\"math-container\">\\$O(n)\\$</span>.</p>\n<h2>Let PHP handle the iteration</h2>\n<p>If the suggestion to use <code>$post</code> doesn’t work, you may be able to change the <code>while</code> loop to a <a href=\"https://php.net/foreach\" rel=\"nofollow noreferrer\"><code>foreach</code></a>. <a href=\"https://php.net/foreach\" rel=\"nofollow noreferrer\"><code>foreach</code></a> provides an easy way to iterate over arrays:</p>\n<pre><code>foreach ($pagelist as $post) {\n $pagename = $post->post_name;\n if (is_page($pagename)) {\n ...\n</code></pre>\n<p>With this approach there is no need to initialize and update a counter (e.g. `$index) to dereference elements in the array.</p>\n<p>If there was a need to access the index/counter variable the second syntax can be used for that:</p>\n<pre><code>foreach ($pagelist as $index => $post) {\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T23:11:13.177",
"Id": "501857",
"Score": "0",
"body": "This works pretty awesome and does what I wanted, reduce the time to O(1). Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-12T14:10:32.483",
"Id": "253382",
"ParentId": "250881",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "253382",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T21:14:39.700",
"Id": "250881",
"Score": "3",
"Tags": [
"performance",
"php",
"css",
"iteration",
"wordpress"
],
"Title": "I need a better way to add css per each page on wordpress"
}
|
250881
|
<p><strong>Story</strong></p>
<p>I was trying to solve a hard problem from Project Euler earlier today (continued from yesterday) and I wanted to graph some things up and play a little bit with fractions. To work with fractions, I decided to implement a little OOP-ish fraction class. I was hoping to brush up whatever little knowledge of C++ I have into trying and implementing a full blown templated project (as I don't practice software design very often and am relatively on the newer side of programming (1.8-ish years)). After fixing what seems like a million template errors (we all can agree on how terrible compilers are with reporting template errors), the following code is what I've arrived at in one day's work.</p>
<p><strong>Code</strong></p>
<pre class="lang-cpp prettyprint-override"><code>/**
Lost Arrow (Aryan V S)
Monday 2020-10-19
**/
#ifndef FRACTION_H_INCLUDED
#define FRACTION_H_INCLUDED
#include <algorithm>
#include <stdexcept>
#include <type_traits>
#include <utility>
/**
* The fraction class is meant to represent and allow usage of fractions from math.
* It is represented by a numerator and a denominator (private context).
* The interface provides you with simple operations:
* - Construction/Assignment
* - Comparison (equality/inequality, less/greater than, lesser/greater equal to, three-way (C++20 spaceship operator))
* - Arithmetic (addition/subtraction, multiplication/division)
* - Conversion (bool, decimal)
* - I/O Utility
* - Access/Modification
*/
template <typename T>
class fraction {
/**
* fraction <T> is implemented to work only with T = [integer types]
* using floating point or any other types in fractions doesn't make sense.
*/
static_assert(std::is_integral <T>::value, "fraction requires integral types");
public:
/**
* Constructors
*/
fraction ();
fraction (const T&, const T&);
fraction (T&&, T&&);
fraction (const fraction&);
fraction (fraction&&);
fraction (const std::pair <T, T>&);
fraction (std::pair <T, T>&&);
/**
* Assignment
*/
fraction <T>& operator = (const fraction&);
fraction <T>& operator = (fraction&&);
/**
* Access/Modification
*/
T nr () const;
T dr () const;
T& nr ();
T& dr ();
std::pair <T, T> value () const;
std::pair <T&, T&> value ();
/**
* Utility
*/
void print (std::ostream& = std::cout) const;
void read (std::istream& = std::cin);
template <typename S>
S decimal_value () const;
std::pair <T, T> operator () () const;
std::pair <T&, T&> operator () ();
operator bool() const;
/**
* Comparison
*/
int8_t spaceship_operator (const fraction <T>&) const;
template <typename S>
friend bool operator == (const fraction <S>&, const fraction <S>&);
template <typename S>
friend bool operator != (const fraction <S>&, const fraction <S>&);
template <typename S>
friend bool operator <= (const fraction <S>&, const fraction <S>&);
template <typename S>
friend bool operator >= (const fraction <S>&, const fraction <S>&);
template <typename S>
friend bool operator < (const fraction <S>&, const fraction <S>&);
template <typename S>
friend bool operator > (const fraction <S>&, const fraction <S>&);
/**
* Arithmetic
*/
fraction <T>& operator += (const fraction <T>&);
fraction <T>& operator -= (const fraction <T>&);
fraction <T>& operator *= (const fraction <T>&);
fraction <T>& operator /= (const fraction <T>&);
private:
mutable T m_nr, m_dr;
/**
* Utility
*/
void normalize () const;
};
/** ::normalize
* The normalize utility function converts a fraction into its mathematically equivalent
* "simplest" form.
* The functions throws a domain error if the denominator is ever set to 0.
*/
template <typename T>
inline void fraction <T>::normalize () const {
if (m_dr == 0)
throw std::domain_error("denominator must not be zero");
T gcd = std::gcd(nr(), dr());
m_nr /= gcd;
m_dr /= gcd;
}
/** ::spaceship_operator
* The spaceship operator provides similar functionality as the <=> operator introduced in C++20.
* If self < other : return value is -1
* If self == other : return value is 0
* If self > other : return value is 1
*/
template <typename T>
inline int8_t fraction <T>::spaceship_operator (const fraction <T>& other) const {
normalize();
other.normalize();
if ((*this)() == other())
return 0;
if (nr() * other.dr() < other.nr() * dr())
return -1;
return 1;
}
/**
* Constructors
*/
template <typename T>
fraction <T>::fraction ()
: m_nr (0)
, m_dr (1)
{ }
template <typename T>
fraction <T>::fraction (const T& nr, const T& dr)
: m_nr (nr)
, m_dr (dr)
{ normalize(); }
template <typename T>
fraction <T>::fraction (T&& nr, T&& dr)
: m_nr (std::move(nr))
, m_dr (std::move(dr))
{ normalize(); }
template <typename T>
fraction <T>::fraction (const fraction <T>& other)
: fraction (other.nr(), other.dr())
{ }
template <typename T>
fraction <T>::fraction (fraction <T>&& other)
: fraction (std::move(other.nr()), std::move(other.dr()))
{ }
template <typename T>
fraction <T>::fraction (const std::pair <T, T>& other)
: fraction (other.first, other.second)
{ }
template <typename T>
fraction <T>::fraction (std::pair <T, T>&& other)
: fraction (std::move(other.first), std::move(other.second))
{ }
/**
* Assignment
*/
template <typename T>
fraction <T>& fraction <T>::operator = (const fraction <T>& other) {
if (this != &other) {
nr() = other.nr();
dr() = other.dr();
}
return *this;
}
template <typename T>
fraction <T>& fraction <T>::operator = (fraction <T>&& other) {
if (this != &other) {
nr() = std::move(other.nr());
dr() = std::move(other.dr());
}
return *this;
}
/** ::nr
* An accessor function that returns a copy of the numerator value to the caller.
*/
template <typename T>
inline T fraction <T>::nr () const {
return m_nr;
}
/** ::dr
* An accessor function that returns a copy of the denominator value to the caller.
*/
template <typename T>
inline T fraction <T>::dr () const {
return m_dr;
}
/** ::nr
* An modification function that returns a reference of the numerator value to the caller.
*/
template <typename T>
inline T& fraction <T>::nr () {
return m_nr;
}
/** ::dr
* An modification function that returns a reference of the denominator value to the caller.
*/
template <typename T>
inline T& fraction <T>::dr () {
return m_dr;
}
/** ::print
* An utility function that prints to the standard output stream parameter in the form: nr/dr
*/
template <typename T>
inline void fraction <T>::print (std::ostream& stream) const {
normalize();
stream << nr() << "/" << dr();
}
/** ::read
* An utility function that reads from the standard input stream in the form: nr dr
*/
template <typename T>
inline void fraction <T>::read (std::istream& stream) {
stream >> nr() >> dr();
normalize();
}
/** ::decimal_value
* An utility function that converts a fraction to its mathematically equivalent floating point representation
* This function requires its template type as a floating point type.
*/
template <typename T>
template <typename S>
inline S fraction <T>::decimal_value () const {
static_assert(std::is_floating_point <S>::value, "decimal notation requires floating point type");
normalize();
return static_cast <S> (nr()) / static_cast <S> (dr());
}
/** ::value
* An utility function that returns a standard pair with the copy of the numerator and denominator to the caller.
*/
template <typename T>
inline std::pair <T, T> fraction <T>::value () const {
return std::pair <T, T> (nr(), dr());
}
/** ::value
* An utility function that returns a standard pair with a refernce to the numerator and denominator to the caller.
*/
template <typename T>
inline std::pair <T&, T&> fraction <T>::value () {
return std::pair <T&, T&> (nr(), dr());
}
/** ::operator ()
* Provides same functionality as ::value with copy.
*/
template <typename T>
inline std::pair <T, T> fraction <T>::operator () () const {
return value();
}
/** ::operator ()
* Provides same functionality as ::value with reference.
*/
template <typename T>
inline std::pair <T&, T&> fraction <T>::operator () () {
return std::pair <T&, T&> (nr(), dr());
}
/** ::bool()
* Converts a fraction to a boolean value which is false if the numerator is 0.
*/
template <typename T>
inline fraction <T>::operator bool() const {
return bool(nr());
}
/**
* Comparison (implemented with the spaceship_operator
*/
template <typename S>
inline bool operator == (const fraction <S>& left, const fraction <S>& right) {
return left.spaceship_operator(right) == 0;
}
template <typename S>
inline bool operator != (const fraction <S>& left, const fraction <S>& right) {
return left.spaceship_operator(right) != 0;
}
template <typename S>
inline bool operator <= (const fraction <S>& left, const fraction <S>& right) {
return left.spaceship_operator(right) <= 0;
}
template <typename S>
inline bool operator >= (const fraction <S>& left, const fraction <S>& right) {
return left.spaceship_operator(right) >= 0;
}
template <typename S>
inline bool operator < (const fraction <S>& left, const fraction <S>& right) {
return left.spaceship_operator(right) == -1;
}
template <typename S>
inline bool operator > (const fraction <S>& left, const fraction <S>& right) {
return left.spaceship_operator(right) == 1;
}
/**
* Arithmetic
*/
template <typename T>
fraction <T>& fraction <T>::operator += (const fraction <T>& other) {
normalize();
other.normalize();
T lcm = std::lcm(dr(), other.dr());
nr() = nr() * (lcm / dr()) + other.nr() * (lcm / other.dr());
dr() = lcm;
normalize();
return *this;
}
template <typename T>
fraction <T>& fraction <T>::operator -= (const fraction <T>& other) {
return *this += fraction <T> (-other.nr(), other.dr());
}
template <typename T>
fraction <T>& fraction <T>::operator *= (const fraction <T>& other) {
normalize();
other.normalize();
nr() *= other.nr();
dr() *= other.dr();
normalize();
return *this;
}
template <typename T>
fraction <T>& fraction <T>::operator /= (const fraction <T>& other) {
return *this *= fraction <T> (other.dr(), other.nr());
}
template <typename T>
fraction <T> operator + (fraction <T>& left, fraction <T>& right) {
fraction <T> result (left);
return result += right;
}
template <typename T>
fraction <T> operator - (fraction <T>& left, fraction <T>& right) {
fraction <T> result (left);
return result -= right;
}
template <typename T>
fraction <T> operator * (fraction <T>& left, fraction <T>& right) {
fraction <T> result (left);
return result *= right;
}
template <typename T>
fraction <T> operator / (fraction <T>& left, fraction <T>& right) {
fraction <T> result (left);
return result /= right;
}
#endif // FRACTION_H_INCLUDED
</code></pre>
<p><strong>Questions and other stuff</strong></p>
<p>According to modern programming standards in C++, how well is my code written? According to software engineering standards, what are the areas I need to improve in? Is my code efficient and well written? Are there any ways I could speed up some computations for efficiency? What improvements to the interface are possible? What could I clean up or refactor in my code? Other relevant insights and tips/discussion/reviews will be appreciated.</p>
<p>To make my implementation more efficient, I'm thinking that I have <code>normalize()</code> at a lot of places which runs in <code>O(log(a.b))</code> and I could add another private variable which checks if a fraction has been normalized or not. This could get rid of redundant runs on normalize. Any other suggestions will be warmly welcomed.</p>
<p>Please don't mind the terrible documentation. I would really do that part much better if my goal was to write a fraction implementation for the sake of writing a fraction implementation and not for solving some problem, and if I were to not have to finish it in one days work. Also, any comments on a good procedure to document stuff are welcome (I know this is subjective and different people have different answers to this but something like a short 101 will likely provide helpful info for future projects).</p>
<p>Thanks SE Community!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T22:02:33.730",
"Id": "493628",
"Score": "0",
"body": "Seems like I forgot implementing assignment completely... It's 03:30 AM where I live and this is the best thing I've got to do. Programming makes you do weird things."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T22:10:04.423",
"Id": "493629",
"Score": "0",
"body": "Another question: If I have a big integer arithmetic implementation and would like to use it as a template parameter in the above code, is there a possibility that I could do an integer type check on the big integer class with features from C++20? Something involving concepts maybe?"
}
] |
[
{
"body": "<h2>Overview</h2>\n<p>Prety good. Big points.</p>\n<ul>\n<li>Move Semantics should be <code>noexcept</code></li>\n<li>Overuse of <code>normalize()</code> is going to make the class ineffecient.<br />\nI would only normalize for printing personally.</li>\n<li>Don't use <code>nr()</code> when <code>m_nr</code> is just as valid.<br />\nYou are already tightly bound in all other member functions.</li>\n<li><code>read()</code> should not change the state of the object if it fails.</li>\n</ul>\n<p>Things You should probably do:</p>\n<ul>\n<li>I would add a <code>swap()</code></li>\n<li>Put one liners into the class definition.</li>\n<li>Put forward declarations of the arithmatic operations next to the class.<br />\nI should not need to read all the code to find them.</li>\n<li>print/read should be symetric</li>\n</ul>\n<h2>Code Review</h2>\n<p>Best practice would to put this in a namespace.</p>\n<hr />\n<p>This works:</p>\n<pre><code> /**\n * fraction <T> is implemented to work only with T = [integer types]\n * using floating point or any other types in fractions doesn't make sense.\n */\n static_assert(std::is_integral <T>::value, "fraction requires integral types");\n</code></pre>\n<p>But since you specified C++20 should you not be using <code>concepts</code> (require rather than static_assert). Not very familiar with the exact definitions yet so don't know how to do it myself.</p>\n<hr />\n<p>The move opertator should be <code>noexcept</code>:</p>\n<pre><code>fraction (fraction&&) noexcept;\nfraction <T>& operator = (fraction&&) noexcept;\n</code></pre>\n<p>When your object is used in a standard container this helps. Becuase the standard gurantees the "Strong Excetpion Gurantee" on some operations it must use the copy semantics when resizing; unless you guranted (with noexcept) that you can not throw an exception then it can use move semantics and speed up these operations.</p>\n<hr />\n<p>You have the normal assignment operators.</p>\n<pre><code> fraction (const T&, const T&);\n fraction (T&&, T&&);\n\n fraction <T>& operator = (const fraction&);\n fraction <T>& operator = (fraction&&);\n</code></pre>\n<p>But since this type is supposed to represent integers. It should be able to support just assigning integers to directly. I would allow the construction/assignment with a single integer (and use a 1 as bottom of the fraction).</p>\n<pre><code> fraction (const T& n, const T& d = 1);\n fraction (T&& n, T&& d = 1);\n\n fraction <T>& operator = (const fraction&);\n fraction <T>& operator = (fraction&&);\n\n // I would provide these explicitly\n // Otherwise the compiler will generate a conversion with a single\n // parameter constructor and then use the assignment above. This\n // may be slightly sub optimal.\n fraction <T>& operator = (const T&);\n fraction <T>& operator = (T&&);\n</code></pre>\n<hr />\n<p>Return these by const reference.</p>\n<pre><code> T nr () const;\n T dr () const;\n</code></pre>\n<p>You mention that T may be some "Big Integer" implementation not just a standard POD int. So you want to avoid a copy if you don't actually need it.</p>\n<pre><code> T const& nr () const;\n T const& dr () const;\n ^ not a fan of this space.\n</code></pre>\n<hr />\n<p>You give accesses to the internal state.</p>\n<pre><code> T& nr ();\n T& dr ();\n</code></pre>\n<p>This makes redundant your use of <code>normalize()</code> in the constructor. You no longer gurantee that the fraction is normalized.</p>\n<hr />\n<p>Not sure I like this.</p>\n<pre><code> std::pair <T&, T&> value ();\n</code></pre>\n<p>Not going to argue against it. But it seems like you are giving accesses to the internals without good reason.</p>\n<hr />\n<p>Like this:</p>\n<pre><code> void print (std::ostream& = std::cout) const;\n void read (std::istream& = std::cin);\n</code></pre>\n<p>Don't see the friend functions to help printing:</p>\n<pre><code> friend std::ostream& operator<<(std::ostream& st, fraction const& d)\n {\n d.print(str);\n return str;\n }\n friend std::istream& operator>>(std::istream& st, fraction& d)\n {\n d.read(str);\n return str;\n }\n</code></pre>\n<hr />\n<p>I would always make the bool operator <code>explicit</code>. This will prevent an accidental conversion to bool in contexts that you don't want it happening.</p>\n<pre><code> operator bool() const;\n</code></pre>\n<hr />\n<p>The reason to make these free standing functions (FSF) rather than members is to allow symetric auto conversion. i.e. If they are members only the rhs could be auto converted to a fraction. If these are non member then both the lhs or the rhs can by auto converted to fractions.</p>\n<pre><code> friend bool operator == (const fraction <S>&, const fraction <S>&);\n ... etc\n</code></pre>\n<p>Notrmally not a fan of auto conversion. But this use case it is a good idea. Unfortunately you don't provide the appropriate constructions to allow auto conversion from an integer type to a fraction (you need a single argument constructor).</p>\n<hr />\n<p>If you create these:</p>\n<pre><code> fraction<T>& operator += (const fraction <T>&);\n ... etc\n</code></pre>\n<p>Then why don't you implement:</p>\n<pre><code> fraction<T> operator + (fraction<T> const& lhs, fraction<T> const& rhs);\n ... etc\n</code></pre>\n<p>these are FSF for the same reason as these:</p>\n<pre><code>friend bool operator == (const fraction <S>&, const fraction <S>&);\n</code></pre>\n<hr />\n<p>This is not a good use of <code>mutable</code>.</p>\n<pre><code> mutable T m_nr, m_dr;\n</code></pre>\n<p>Mutable should be used on members that don't represent the state of the object. i.e. you are caching some printable value. i.e. It has a state that is expensive to compute so you keep it around but it could be easily re-computed from the members that actually represent the state of the obejct.</p>\n<hr />\n<p>No need to call <code>nr()</code> inside the class simply use <code>m_nr</code>.</p>\n<pre><code> T gcd = std::gcd(nr(), dr());\n</code></pre>\n<hr />\n<p>Is <code>normalize()</code> a rather expensive operation?</p>\n<pre><code>inline int8_t fraction <T>::spaceship_operator (const fraction <T>& other) const {\n</code></pre>\n<p>Thus calling it as part of a comparison seems overkill.</p>\n<pre><code> normalize();\n other.normalize();\n</code></pre>\n<p>Why not calcualte the value and do a comparison?</p>\n<pre><code> double lhsTest = 1.0 * m_nr/m_dr;\n double rhsTest = 1.0 * other.m_nr/other.m_dr;\n</code></pre>\n<p>In comparison to normalization this is relatively cheap? I think?</p>\n<hr />\n<p>I would not bother to normalize during construction.</p>\n<pre><code>fraction <T>::fraction (const T& nr, const T& dr)\n : m_nr (nr)\n , m_dr (dr)\n{ normalize(); }\n</code></pre>\n<p>You don't gurantee that the object will remain normalized (As you give access to the internal members. So why do this expensive operation each time. I would simply save normalization for printing.</p>\n<hr />\n<p>I prefer the standard <code>Copy and Swap Idiom</code> here.</p>\n<pre><code>template <typename T>\nfraction <T>& fraction <T>::operator = (const fraction <T>& other) {\n if (this != &other) {\n nr() = other.nr();\n dr() = other.dr();\n }\n return *this;\n}\n</code></pre>\n<p>The check for assignment to self is a test for something that basically never happens and is thus a pessimization in real code (obviously it still needs to work with assignment to self). But the copy and swap gets away from this by always doing the copy (which may seem like a pesimization but in real life is not as you don't get the branch prediction reset).</p>\n<hr />\n<p>Prefer the swap implementation of this:</p>\n<pre><code>template <typename T>\nfraction <T>& fraction <T>::operator = (fraction <T>&& other) {\n if (this != &other) {\n nr() = std::move(other.nr());\n dr() = std::move(other.dr());\n }\n return *this;\n}\n</code></pre>\n<p>Again. no need for a self assignment test.</p>\n<hr />\n<p>I would also add a swap() method and swap() friend function:</p>\n<pre><code> void fraction<T>::swap(fraction<T>& other) noexpcept\n {\n using std::swap;\n swap(m_nr, other.m_nr);\n swap(m_dr, ither.m_dr);\n }\n friend void swap(fraction<T>& lhs, fraction<T>& rhs)\n {\n lhs.swap(rhs);\n }\n</code></pre>\n<hr />\n<p>I don't like the external definition of functions that are this simple.</p>\n<pre><code>template <typename T>\ninline T fraction <T>::nr () const {\n return m_nr;\n}\n</code></pre>\n<p>One liner functions should be part of the class declaration.</p>\n<hr />\n<pre><code>inline void fraction <T>::print (std::ostream& stream) const {\n normalize();\n stream << nr() << "/" << dr();\n ^^^^ You are inside the class.\n You are already tightly coupled to the implementation.\n You should simply use m_nr.\n}\n</code></pre>\n<p>Here is "about" the only time I would normalize fraction. Printing is already relatively slow operation, so normalizing is not going to add a great cost relatively speaking.</p>\n<p>I would implement this function like this:</p>\n<pre><code>void fraction <T>::print (std::ostream& stream) const\n{\n fraction<T> temp(*this);\n temp.normalize(); // Now normalize can happen on a non cost object.\n\n stream << temp.m_nr << "/" << temp.m_dr;\n}\n</code></pre>\n<hr />\n<p>I would want the read operation to be symetric with the <code>print()</code> function. Thus I would expect it to read and discard the <code>/</code> operator.</p>\n<p>Also the read operation should only mutate the current object if the read succedes. So I would change it slightly.</p>\n<pre><code>void fraction<T>::read(std::istream& stream)\n{\n fraction<T> temp\n char div;\n if ((stream >> temp.m_nr >> div >> temp.m_dr) && div == '/') {\n // read worked and we have correct seporator.\n // so we can update the state of the object.\n temp.swap(*this);\n }\n else {\n // some failure. Make sure the stream is marked bad.\n stream.setstate(std::ios::badbit);\n }\n}\n</code></pre>\n<hr />\n<p>That seems like a non optimal comparison.</p>\n<pre><code>inline bool operator == (const fraction <S>& left, const fraction <S>& right) \n{\n return left.spaceship_operator(right) == 0;\n}\n</code></pre>\n<p>Quite expensive if it is not eual.</p>\n<hr />\n<p>You don't need to call normalize three times!! Call it once at the end of the operation (if you must). I would not bother (unless there is some overflow issue).</p>\n<p>PS. You missed the <code>inline</code> here.</p>\n<pre><code>template <typename T>\nfraction <T>& fraction <T>::operator += (const fraction <T>& other) {\n normalize();\n other.normalize();\n T lcm = std::lcm(dr(), other.dr());\n nr() = nr() * (lcm / dr()) + other.nr() * (lcm / other.dr());\n dr() = lcm;\n normalize();\n return *this;\n}\n</code></pre>\n<p>This can be simplified to:</p>\n<pre><code>fraction<T>& fraction<T>::operator+=(fraction <T> const& other)\n{\n if (m_dr == other.m_dr) {\n m_nr += other.m_nr;\n }\n else {\n m_nr = (other.m_nr * m_dr) + (m_nr * other.m_dr);\n m_dr = m_dr * other.m_dr;\n if (m_dr > SOME_BOUNDRY_CONDITION) {\n normalize();\n }\n }\n return *this;\n}\n// Notice the lhs is passed by value to get a copy.\n// So we don't need to do an explicit copy in the function;\nfraction<T> operator+(fraction<T> lhs, fraction<T> const& rhs) {return lhs += rhs;}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T10:09:53.497",
"Id": "493665",
"Score": "1",
"body": "Short review review: I think there's a note about `= default`ing the move and copy constructors as well as `operator=` missing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T10:16:53.437",
"Id": "493666",
"Score": "0",
"body": "I'm amazed at the level of detail you've provided Martin. Huge thanks for the effort and time you've taken! There are a lot of things you've mentioned. I'm going to be replying to some of them in these comments. Just to make sure that I don't end up commenting too much, I'll try to comment about things I'm not familiar with and the new things I'm seeing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T10:26:19.060",
"Id": "493667",
"Score": "0",
"body": "(1) Yes, I should be using concepts but because I don't have a g++ version which supports C++20 features, this is how it's gonna have to be for now. (2) I believe I've missed a lot of things as this was a one day build to get stuff done. It was a nice point of defaulting denominators to 1 in the constructors to represent integers. (3) I still have no idea how I could use Big Integer type a parameter as the static assertion prevents me from doing so. Maybe when I can use C++20, it'd be easier to intuitively understand what to do to make it work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T10:31:20.100",
"Id": "493668",
"Score": "0",
"body": "(4) I figured as much about the redundant calls to `normalize()`. Again, I was trying to solve a problem which is why I implemented this. I didn't want to deal with any sort of stupid overflow that might occur. However, in the worst cases, the calls don't really do anything. I'll work on fixing that. (5) The reason why I have `std::pair <T&, T&> value ();` is because I thought it might look cool to do stuff like `f.value() = some_pair`. I'm immature I guess. (6) I haven't add the friend functions for i/ostream into the header because the end user could want to print/read data in their own way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T10:37:05.503",
"Id": "493669",
"Score": "0",
"body": "...(6) If I did provide it, there'd be problems of ambiguity. Example: If I want to change the way a string is printed through cout, I'd have to define my own overload. Once I do so, the compiler shouts. So, I thought it best to be simply left out and provide `read()` and `print()` instead. (7) Instead of making bool() explicit, I added a templated overload for cast operations (and remembered to mark it explicit earlier this morning after noticing cout printing boolean values true and false), Now I can do stuff like `cout << (int) fraction <int> (5, 2);` too or directly type cast to doubles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T10:51:32.180",
"Id": "493674",
"Score": "0",
"body": "(8) Points on overloads for += and others are understandable. I'll work on the improvements. (9) I added the mutables simply as a work around to overflowing values which I encountered yesterday. This allowed me to do the `other.normalize()` when other was a const object. Bad design, yes. I'll work on it. (10) I would like to keep the nr's and dr's normalized at all times simply because I want to avoid overflow at all times, if possible. Maybe it's because I provide weird ways of access that makes it seem useless. (11) Points on design are well stated! I'll edit my question with revised code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T16:55:09.970",
"Id": "493714",
"Score": "1",
"body": "`I'll edit my question with revised code.`: Don't do that. Ask a new question with the new code. If you look at my submissions here I can go through 4/5 revisions in 4/5 different questions."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T09:36:32.510",
"Id": "250897",
"ParentId": "250882",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "250897",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T21:41:19.507",
"Id": "250882",
"Score": "4",
"Tags": [
"c++",
"object-oriented",
"c++17"
],
"Title": "Templated Fraction Class and programming design"
}
|
250882
|
<p>I've made a program which makes the folders a-z, and in each of those makes the folders a-z, and in each of... you get it. many, many folders. its quite slow at the moment, would there be any way to optimize?</p>
<pre><code>import os
from os import chdir,mkdir,rmdir
from os.path import isdir
from sys import exit
if os.name == "nt":
os.system("color")
DIRLIMIT = 4
LOGLIMIT = 2
CHAR_GREEN = "\u001b[32m"
CHAR_RESET = "\u001b[0m"
CHAR_WHITE = "\u001b[37m"
CHAR_CYAN = "\u001b[36m"
CHAR_MAGENTA = "\u001b[35;1m"
CHAR_YELLOW = "\u001b[33m"
PREFIX = "dir_"
CHARS_ALPHABET = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z", " "] #last character is empty whitespace
colors_dict = {
0: CHAR_RESET,
1: CHAR_GREEN,
2: CHAR_YELLOW,
3: CHAR_MAGENTA,
4: CHAR_CYAN,
5: CHAR_WHITE
}
def make_recursive():
usr = int(input("Input how many directores you want:\n> "))
print(f"Making '{usr}' directories with prefix '{PREFIX}'\n")
for curGoal in range(usr):
curGoal += 1
try:
mkdir(f"./{PREFIX}{curGoal}")
chdir(f"./{PREFIX}{curGoal}")
print(f"Made directory '{PREFIX}{curGoal}', navigated")
except (FileNotFoundError, OSError):
input(f"I can't go any further, MAX_PATH is still limited at 260 characters for this system. Please remove this limit, and run me again!\n\nPress the enter key to exit...")
return
except FileExistsError:
chdir(f"./{PREFIX}{curGoal}")
print(f"Already found directory '{PREFIX}{curGoal}', navigated")
input("\nDone!\n\nPress enter to exit...")
return
def rmtree(path : str, level : int = 0):
try:
start = autotab(level)
if start != None:
print(f"{start}Working on level {level}{CHAR_RESET}\t\t\t\t'{path}'")
os.rmdir(path)
except OSError:
for folder in os.listdir(path):
try:
rmtree(f"{path}/{folder}", level+1)
except NotADirectoryError:
os.remove(f"{path}/{folder}")
if os.path.exists(path):
rmtree(path)
def make_letters():
for char in CHARS_ALPHABET:
mkdir(f"./{char}")
def start_makealphabet():
try:
mkdir("./Alphabet")
chdir("./Alphabet")
except FileExistsError:
input("Alphabet already exists!\n\nPress the enter key to delete it...")
rmtree("./Alphabet")
input("\nAlphabet deleted!\n\nPress the enter key to exit...")
return
make_alphabet()
input(f"\n\n\n\n{CHAR_MAGENTA}Generation done!\n\n{CHAR_RESET}Press the enter key to exit...")
exit()
def autotab(level):
if level == 0 or level > LOGLIMIT:
return None
try:
returnString = colors_dict[level]
except KeyError:
returnString = ""
while level != 1:
level -= 1
returnString += "\t"
return returnString
def make_alphabet(level=1, curpath=""):
for char in CHARS_ALPHABET:
mkdir(f"./{char}")
start = autotab(level)
if start != None:
print(f"{start}Working on level {level}{char}{CHAR_RESET}")
chdir(f"./{char}")
if level < DIRLIMIT:
make_alphabet(level+1, f"{curpath}{char}")
else:
with open(f"{curpath}{char}", "w"):
pass
chdir("..")
if __name__ == "__main__":
try:
start_makealphabet()
except KeyboardInterrupt:
input("Program stopped.\n\nPress the enter key to exit...")
exit()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T23:51:50.573",
"Id": "493634",
"Score": "0",
"body": "Nope, just a thing that I made for fun"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T23:56:30.610",
"Id": "493637",
"Score": "0",
"body": "I'm sure you have your reasons... Anyway let me just consider make_alphabet, you are pretty much io bound, so things will be faster if you remove the print lines, and if you avoid changing dir, and make the directories and files immediately.\n\nConsider something like itertools.product, then you can avoid the recursion in make_alphabet, and make the directories directly, and avoid changing dir, will be a good deal faster. To allow the intermediate dirs to be made, use os.makedirs instead of os.mkdir.\n\nI have tried these changes myself locally and the performance difference is considerable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T00:03:21.553",
"Id": "493640",
"Score": "0",
"body": "@hjpotter92 sorry, i started the thread using my phone so i had troubles with the intentation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T00:03:26.603",
"Id": "493641",
"Score": "0",
"body": "@Countingstuff that sounds pretty good, i'll research a bit and modify my program to use your suggestions"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T00:04:01.517",
"Id": "493642",
"Score": "0",
"body": "and please do not keep changing the code itself. you've already done so 3 times https://codereview.stackexchange.com/posts/250883/revisions"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T00:04:42.767",
"Id": "493643",
"Score": "0",
"body": "yes, i had troubles with some indentation and missing code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T03:13:19.303",
"Id": "495313",
"Score": "0",
"body": "When asking a performance question, you should start by trying to learn what piece is slow yourself. Comment out lines, measure time in each section, etc. Once you know, ask again. Or if you can't find out that's fine too, just let us know what you already tried."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T23:03:55.440",
"Id": "250883",
"Score": "1",
"Tags": [
"python",
"performance",
"python-3.x",
"file-system"
],
"Title": "Generate many, many folders fast"
}
|
250883
|
<p>Here is a project that I have been working on for the past few days.</p>
<p>I have used the <code>SFML</code> library in C++ to make a flappy bird game of my own. I made this as a step towards learning GUI in C++. <br><br></p>
<hr />
<p>The program is <strong>Object-Oriented</strong> as I believe this made it a little easier to maintain. Although this isn't my first time learning SFML, I am pretty rusty since I never tried to make something serious with it.</p>
<hr />
<h1>Game.h</h1>
<pre class="lang-cpp prettyprint-override"><code>#pragma once
#include <SFML/Graphics.hpp>
#include "Bird.h"
#include "Obstacle.h"
class Game
{
public:
Game(const char*);
~Game();
int score;
void mainloop();
private:
sf::RenderWindow window;
Bird bird;
Obstacle obstacle;
sf::Texture background_texture;
sf::Sprite background;
void handle_events(const sf::Event&);
inline void draw_objects();
inline void update_object_positions();
inline bool detect_loss();
};
inline bool Game::detect_loss()
{
const auto& bird_bounds = bird.body.getGlobalBounds();
if (bird_bounds.intersects(obstacle.top_obstacle.getGlobalBounds()))
return true;
if (bird_bounds.intersects(obstacle.bottom_obstacle.getGlobalBounds()))
return true;
return false;
}
inline void Game::update_object_positions()
{
bird.update_bird();
obstacle.update_obstacle();
if (obstacle.bottom_obstacle.getPosition().x < -89)
{
++score;
obstacle.new_rand_obstacle();
}
}
inline void Game::draw_objects()
{
window.draw(background);
window.draw(bird.body);
window.draw(obstacle.bottom_obstacle);
window.draw(obstacle.top_obstacle);
}
</code></pre>
<h1>Game.cpp</h1>
<pre class="lang-cpp prettyprint-override"><code>#include "Game.h"
#include <iostream>
Game::~Game()
{
std::cout << "Well played ! Score : " << score << '\n';
}
Game::Game(const char* title)
: score{ 0 }
{
window.create(sf::VideoMode(800, 800), title);
if (!background_texture.loadFromFile("images//background.png"))
std::cout << "Failed to load background image\n";
background.setTexture(background_texture);
}
void Game::handle_events(const sf::Event& event)
{
switch (event.type)
{
case sf::Event::Closed:
window.close();
break;
case sf::Event::KeyPressed:
if (event.key.code == sf::Keyboard::Space || event.key.code == sf::Keyboard::Up)
bird.fly();
if (event.key.code == sf::Keyboard::N)
obstacle.new_rand_obstacle();
break;
}
}
void Game::mainloop()
{
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
handle_events(event);
}
if (detect_loss())
break;
update_object_positions();
window.clear();
draw_objects();
window.display();
}
}
</code></pre>
<h1>Bird.h</h1>
<pre class="lang-cpp prettyprint-override"><code>#pragma once
#include <SFML/Graphics.hpp>
class Bird
{
public:
sf::Texture texture_wing_up;
sf::Texture texture_wing_down;
sf::Sprite body;
sf::Vector2f acceleration;
sf::Vector2f velocity;
Bird();
void fall();
void fly();
void reset();
void update_bird();
private:
int start_fall;
};
</code></pre>
<h1>Bird.cpp</h1>
<pre class="lang-cpp prettyprint-override"><code>#include "Bird.h"
#include <iostream>
namespace
{
const sf::Vector2f fly_acc(0, -0.01f);
const sf::Vector2f fall_acc(0, 0.001f);
const float fly_rot{ -30.5f };
const float fall_rot{ 0.06f }; // offset is applied to current rotation
const sf::Vector2f middle(35,29);
const sf::Vector2f initial_bird_pos(320, 300);
const float max_fall_vel = 0.4f;
const float max_fly_vel = -0.5f;
}
void Bird::fly()
{
acceleration = ::fly_acc;
start_fall = static_cast<int>(body.getPosition().y-7);
body.setRotation(::fly_rot);
body.setTexture(texture_wing_down);
}
void Bird::fall()
{
acceleration = ::fall_acc;
body.rotate(::fall_rot);
body.setTexture(texture_wing_up);
}
void Bird::reset()
{
acceleration = { 0,0 };
velocity = { 0,0 };
body.setPosition(320, 300);
body.setRotation(0);
start_fall = 0;
}
void Bird::update_bird()
{
velocity += acceleration;
if (velocity.y > ::max_fall_vel) velocity.y = ::max_fall_vel;
if (velocity.y < ::max_fly_vel) velocity.y = ::max_fly_vel;
body.move(velocity);
const auto& position = body.getPosition().y;
if (position < start_fall) fall();
}
Bird::Bird()
{
if (!texture_wing_up.loadFromFile("images//bird_wing_up.png"))
throw std::runtime_error("Failed to load images//bird_wing_up.png\n");
if (!texture_wing_down.loadFromFile("images//bird_wing_down.png"))
throw std::runtime_error("Failed to load images//bird_wing_down.png");
body.setTexture(texture_wing_up);
body.setPosition(initial_bird_pos);
acceleration = { 0,0 };
velocity = { 0,0 };
body.setOrigin(middle); // Imporant as it also sets the point where the bird rotates at
start_fall = 0;
}
</code></pre>
<h1>Obstacle.h</h1>
<pre class="lang-cpp prettyprint-override"><code>#pragma once
#include <SFML/Graphics.hpp>
class Obstacle
{
public:
sf::Texture texture;
sf::Sprite bottom_obstacle;
sf::Sprite top_obstacle;
sf::Vector2f velocity;
Obstacle();
void update_obstacle();
void new_rand_obstacle();
};
</code></pre>
<h1>Obstacle.cpp</h1>
<pre class="lang-cpp prettyprint-override"><code>#include "Obstacle.h"
#include <stdlib.h>
#include <iostream>
Obstacle::Obstacle()
{
velocity = { -0.15f,0 };
if (!texture.loadFromFile("images//obstacle.png"))
throw std::runtime_error("Failed to load images//obstacle.png\n");
bottom_obstacle.setTexture(texture);
bottom_obstacle.setPosition(720, 300);
top_obstacle = bottom_obstacle;
top_obstacle.rotate(180);
const auto& bottom_position = bottom_obstacle.getPosition();
top_obstacle.setPosition(bottom_position.x+89, bottom_position.y - 250);
srand((unsigned)time(0));
}
void Obstacle::update_obstacle()
{
bottom_obstacle.move(velocity);
auto bottom_position = bottom_obstacle.getPosition();
top_obstacle.setPosition(bottom_position.x+89, bottom_position.y - 250);
}
void Obstacle::new_rand_obstacle()
{
const auto new_pos = rand() % 600 + 200;
bottom_obstacle.setPosition(800, (float)new_pos);
const auto& bottom_position = bottom_obstacle.getPosition();
top_obstacle.setPosition(bottom_position.x+89, bottom_position.y - 250);
}
</code></pre>
<h1>main.cpp</h1>
<pre class="lang-cpp prettyprint-override"><code>#include "Game.h"
int main()
{
Game* game = new Game("Flappy Bird");
game->mainloop();
delete game;
game = nullptr;
return 0;
}
</code></pre>
<h3>The physics for the bird</h3>
<ul>
<li><p>The bird's physics was the part I took time to code, not because it was tough but I tried to perfect how the bird <code>fall()</code> and <code>fly()</code>. I used <code>acceleration</code> that would modify <code>velocity</code>. The values given to <code>acceleration</code> are quite small, but each frame it adds up so the overall movement of the bird looks really good. Every time<code> fly()</code> is called, it sets a point above the bird at which the bird will start to <strong>de-celerate</strong>. Hence <code>start_fall()</code> .I am happy with how the bird flew at last </p>
</li>
<li><p>There are two images, one with the bird's wings flapped and one normal. When <code>fly()</code> is called I switch to the flapped wings, and when it starts falling I switch back to the normal ones, this also adds to the effect and gives a better look.</p>
</li>
<li><p>The bird also rotates according to its velocity.</p>
</li>
</ul>
<p>The obstacles are pretty straight forward.</p>
<ul>
<li><p>One obstacle at the bottom has a constant velocity and is placed randomly on the <code>y-axis</code> every new generation.</p>
</li>
<li><p>Top obstacle is rotated <code>180 °</code> and aligned with the bottom obstacle.</p>
</li>
</ul>
<h2>What I expect from a review</h2>
<ul>
<li><p>General coding aspects</p>
</li>
<li><p>Things like acceleration, origin, positions are all constant, and <code>bird.cpp</code> has many of them. At first, I decided to just use the plan floating-constants, but then the magic numbers didn't look very nice.<br> Hence, I decided to keep them in an anonymous namespace as they are only used in <code>bird.cpp</code>. Is this a better way to do this? Also, what way do <strong>you</strong> usually prefer to store stuff like this?</p>
</li>
</ul>
<p><a href="https://i.stack.imgur.com/vK9hd.png" rel="noreferrer"><img src="https://i.stack.imgur.com/vK9hd.png" alt="Bird" /></a>
<a href="https://i.stack.imgur.com/VkrNn.png" rel="noreferrer"><img src="https://i.stack.imgur.com/VkrNn.png" alt="Bird2" /></a></p>
<p><a href="https://i.stack.imgur.com/V5OLX.png" rel="noreferrer"><img src="https://i.stack.imgur.com/V5OLX.png" alt="Game" /></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T10:56:09.000",
"Id": "493676",
"Score": "2",
"body": "What do you expect that the reviewer looks at? General coding, specific aspects?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T11:25:41.513",
"Id": "493679",
"Score": "1",
"body": "Yes anything and everything"
}
] |
[
{
"body": "<h1>Prefer member variables to be <code>private</code> if possible</h1>\n<p>There are a lot of member variables that are <code>public</code> that are not used outside the class itself. For example, <code>Game::score</code>, <code>Bird::texture_wing_up</code>, and many more. These should all be <code>private</code>, as this prevents other classes from accidentily accessing these member variabels.</p>\n<h1>Avoid premature inlining of functions</h1>\n<p>Why are <code>detect_loss()</code>, <code>update_object_positions()</code> and <code>draw_objects()</code> declared as <code>inline</code> functions in <code>Game.h</code>? I do not see any reason why these would be performance critical. Declare them as regular member functions, and define them in <code>Game.cpp</code>. Note that the compiler itself can still decide to inline those functions when they are called from <code>mainloop()</code>.</p>\n<h1>Who is responsible for what</h1>\n<p>Your game is quite simple, and <code>Game::draw_objects()</code> looks perfectly reasonable. But what it actually does is having <code>class Game</code> reaching into <code>class Bird</code> and <code>class Obstacle</code>, and accessing their member variabels <code>body</code> and <code>bottom</code>/<code>top_obstacle</code>. This means that there is now quite a tight coupling between those classes. But consider now that drawing the bird would be much more complex than just drawing a single <code>sf::Sprite</code>. Maybe you have many separate sprites, for example one for the wings, one for the body, one for the head and so on, that all animate independently. Do you want <code>class Game</code> to be responsible for drawing a <code>Bird</code> in that case?</p>\n<p>There are several ways to address this issue. You could simply add a member function that does all the drawing in <code>class Bird</code>:</p>\n<pre><code>void Game::draw_objects() {\n ...\n bird.draw(window);\n ...\n}\n\nvoid Bird::draw(sf::RenderTarget &target) {\n target.draw(body);\n}\n</code></pre>\n<p>I used the fact that <code>sf::Window</code> derives from <code>sf::RenderTarget</code>, so <code>Bird::draw()</code> is now more generic than if you would pass a reference to an <code>sf::Window</code>. Alternatively, with SFML, you could make <code>Bird</code> become an <code>sf::Drawable</code>, like so:</p>\n<pre><code>void Game::draw_objects() {\n ...\n window.draw(bird);\n ...\n}\n\nclass Bird: public sf::Drawable {\n ...\n Bird::draw(sf::RenderTarget &target, sf::RenderStates states) final;\n ...\n};\n\nvoid Bird::draw(sf::RenderTarget &target, sf::RenderStates states) {\n target.draw(body);\n}\n</code></pre>\n<p>With either technique, you can make the <code>sf::Sprite</code> variabels <code>private</code>, and while it doesn't look like much of an improvement for <code>Bird</code>, it already becomes more interesting for <code>Obstacle</code>, where in <code>Game::draw_objects()</code> you should only have to call <code>window.draw(obstacle)</code> to have the <code>Obstacle</code> itself draw both its bottom and top parts.</p>\n<p>(For games with much more objects you might want to look into using an <a href=\"https://en.wikipedia.org/wiki/Entity_component_system\" rel=\"nofollow noreferrer\">Entity Component System</a> like <a href=\"https://github.com/skypjack/entt\" rel=\"nofollow noreferrer\">EnTT</a>, where one of the components would be the drawable part of entities like the bird and the obstacle, but that is obviously complete overkill for this game.)</p>\n<h1>Have <code>Game::handle_events()</code> implement the <code>while</code>-loop</h1>\n<p>Despite the name, <code>Game::handle_events()</code> only handles a single event, the <code>while</code>-loop that ensures all queued events are handled is in <code>Game::mainloop()</code>. Consider moving the <code>while</code>-loop to <code>handle_events()</code>.</p>\n<h1>Create a function <code>render()</code> to further simplify <code>mainloop()</code></h1>\n<p>Create one high-level function to do the rendering. This keeps <code>mainloop()</code> nice and clean:</p>\n<pre><code>void Game::render() {\n window.clear();\n draw_objects();\n window.display();\n}\n\nvoid Game::mainloop() {\n while (running)\n {\n handle_events();\n update_object_positions();\n render();\n }\n}\n</code></pre>\n<p>Create a member variable <code>running</code> that can be set to false in <code>handle_events()</code> if the window is closed, or by <code>update_object_positions()</code> if a collision between the bird and the obstacle is detected.</p>\n<h1>Make global constants <code>constexpr</code></h1>\n<p>It's very good that you avoided magic constants in your code, and gave them clear names. The anonymous namespace does the same as <code>static</code>, and ensures they don't have external linkage. But even better is to make them <code>constexpr</code> instead of <code>const</code>. This makes it clear to the compiler that this is not meant to be used as a variable (of which an address can be taken for example), but really just as a literal constant.</p>\n<h1>There still are magic constants left</h1>\n<p>There are still lots of magic constants in your code. For example, the window size, the initial position of the obstacle, and so on.</p>\n<h1>Call <code>reset()</code> from the constructor</h1>\n<p>You have some unnecessary code duplication, since you are initializing member variables manually in the constructor of <code>Bird</code> and <code>Obstacle</code>, that you also set from <code>Bird::reset()</code> and <code>Obstacle::new_rand_obstacle()</code>. Consider calling the latter two functions from the constructors of those classes.</p>\n<h1>Use C++'s random number generator functions</h1>\n<p>C++ has much better random number generator facilities than C. Use then instead of <code>rand()</code>. For example, you can use <a href=\"https://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution\" rel=\"nofollow noreferrer\"><code>std::uniform_int_distribution</code></a> in <code>Obstacle</code>.</p>\n<h1>Use <code>std::min</code> and <code>std::max</code></h1>\n<p>For example:</p>\n<pre><code>void Bird::update_bird()\n{\n\n velocity += acceleration;\n velocity.y = std::min(std::max(velocity.y, max_fly_vel), max_fall_vel);\n ...\n}\n</code></pre>\n<p>Or even better, with C++17 you can write:</p>\n<pre><code> velocity.y = std::clamp(velocity.y, max_fly_vel, max_fall_vel);\n</code></pre>\n<h1>Avoid allocating objects on the heap for no good reason</h1>\n<p>There is no need to use <code>new</code> in <code>main()</code>, you can just write:</p>\n<pre><code>int main()\n{\n Game game("Flappy Bird");\n game.mainloop();\n}\n</code></pre>\n<p>If you do want or need to avoid allocating an object on the stack, then you should still avoid using <code>new</code> and <code>delete</code> directly, but instead use something like <a href=\"https://en.cppreference.com/w/cpp/memory/unique_ptr\" rel=\"nofollow noreferrer\"><code>std::unique_ptr</code></a> to manage the lifetime for you automatically. like so:</p>\n<pre><code>int main()\n{\n auto game = std::make_unique<Game>("Flappy Bird");\n game->mainloop();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T03:23:52.943",
"Id": "493769",
"Score": "0",
"body": "Amazing insights! I even told this on the other review since It was pointed out there too, I have read that I shouldn't allocate large objects on the stack, and even visual studio suggests me to move `Game` into the heap if I initialize it on the stack. Is this wrong?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T03:38:36.580",
"Id": "493771",
"Score": "1",
"body": "Also, `std::clamp` didn't seem to work, the bird flew straight up never came down, I think you have switched `max_fall_vel` and `max_fly_vel`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T06:35:59.083",
"Id": "493782",
"Score": "0",
"body": "Ah, I indeed had the velocities the wrong way around. As for `Game` on the stack: it's not large at all, and even if it was in the order of kilobytes, I still wouldn't worry about it if it's just a single object. However, the moment you start declaring an array of objects on the stack you should be careful, as it's easy to use a lot of memory that way, and indeed the stack is a limited resource. But on most desktop operating systems it's in the order of megabytes for the main thread."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T06:42:46.427",
"Id": "493784",
"Score": "0",
"body": "Alright, I understand that, so for this case, it shouldn't be an issue to have `Game` on the stack right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T06:59:26.477",
"Id": "493787",
"Score": "1",
"body": "Correct, in this case it's fine."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T19:49:33.580",
"Id": "250925",
"ParentId": "250892",
"Score": "5"
}
},
{
"body": "<p>I'm not an expert in SFML, so I can't really give any advice about that. Though, let me look at the code as is.</p>\n<p>Let's start with <code>Game.h</code>:</p>\n<ul>\n<li>Your Game is taking a <code>const char *</code> as argument, I would recommend <code>std::string_view</code> if you would be compiling with C++17. It has a lot of features of <code>std::string</code> and it behaves as <code>const char *</code></li>\n<li>I like how you encapsulate several of your members behind relevant functions, though, why is <code>score</code> public?</li>\n<li>I can understand the need for a few functions to be inline. However, why would you implement those functions in the same header if they are only callable from within your other methods (which are all implemented in the cpp). It would increase compile times (especially on large projects) and it puts the private details in the public file.</li>\n<li>In one of the functions you compare x with <code>-89</code>, this is a bit strange to me as a reader, what's this number? What does it represent. Putting it in a constant would help a lot in understanding why every value from -inf to (and including) -90 would be accepted.</li>\n</ul>\n<p><code>Game.cpp</code>:</p>\n<ul>\n<li>Again you have some magic constants, in this case: <code>"images//background.png"</code>. Here it makes sense to put this in a constant, that way, you later on could use a code generator to create these constants based on the actual pictures (or even embed them) and you get compilation failures if they go missing.</li>\n<li><code>Failed to load ...</code> sounds like an error, yet, you stream this to <code>std::cout</code> instead of <code>std::cerr</code>. As a result, the console can't collor this differently.</li>\n<li>Looking at the same message, your user is gonna be puzzled, how should they solve this? It could help if you mention to them where you expected the image to be so they can put a new picture there.</li>\n</ul>\n<p><code>Bird.h</code>:</p>\n<ul>\n<li><code>start_fall</code> is not initialized, by writing <code>int start_fall{0};</code> you can say this needs to be zero. That way, you can't forget about it in the cpp.</li>\n</ul>\n<p><code>Bird.cpp</code>:</p>\n<ul>\n<li>Let's look at layout, in <code>update_bird</code> you put the <code>if</code> and the code on 1 line, in the Ctor, you put it on 2.</li>\n<li>In the same <code>update_bird</code> function, you seem to be correcting velocity.y, I would write something like: <code>velocity.y = std::clamp(velocity.y, ::max_fly_vel, ::max_fall_vel);</code> Much easier to read what's going on, less chance to write something wrong.</li>\n<li>In the Ctor, you throw exceptions, yet I don't see any mention of <code>noexcept</code> or in this case <code>noexcept(false)</code> to inform your users when to expect exceptions.</li>\n</ul>\n<p><code>Obstacle.cpp</code>:</p>\n<ul>\n<li>In C++, we use <code><cstdlib></code> instead of the C headers <code><stdlib.h></code></li>\n<li><code>srand((unsigned)time(0));</code> hurts my eyes, I'm not even gonna explain it, it's best you watch <a href=\"https://www.youtube.com/watch?v=6DPkyvkMkk8\" rel=\"nofollow noreferrer\">CppCon 2016: Walter E. Brown “What C++ Programmers Need to Know about Header <random>"</a></li>\n</ul>\n<p><code>main.cpp</code>:</p>\n<ul>\n<li>What's the point of allocating a game if you can put it on the stack? I've once explained this in more detail, see <a href=\"https://stackoverflow.com/a/53898150/2466431\">stackoverflow</a></li>\n</ul>\n<p>So in general:</p>\n<ul>\n<li>Really good code with a few remarks</li>\n<li>It's obvious that you ain't familiar with the details of C++1 or more recent, using those things could help making this code easier to read</li>\n<li>I didn't really mention anything about structure, let me fix that: This looks like really nice OO!</li>\n</ul>\n<p>And to answer your question about the constants: I usually use <code>constexpr</code> constants. Whether it's in unnamed namespace, constants in a separate header or static constants in the class depends on the use case.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T03:20:38.067",
"Id": "493768",
"Score": "0",
"body": "Brilliant review, I have to clarify a few things though. I have read that I shouldn't allocate large objects on the stack, and even visual studio suggests me to move `Game` into the heap if I initialise it on the stack. Is this wrong?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T03:57:42.230",
"Id": "493772",
"Score": "0",
"body": "Also, declaring any `sf::Vector2f` variable `constexpr` throws an error instantly saying that the object isn't constant, is this related to how the constructor is designed in class `Vector2f`?'"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T06:35:37.737",
"Id": "493781",
"Score": "2",
"body": "Yes, you are right, though what's a big object? I only see 5 members of which I expect most of them to do allocations to store their data (they have the big data in it). Best to do a sizeof(Game) and check. Normally you should be having 1MB of stack with visual studio compiler and you can change this if needed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T06:38:21.607",
"Id": "493783",
"Score": "1",
"body": "Constexpr has its limitations, c++20 resolves a few of them again making std::vector and std::string constexpr. Instead use `inline static const` for ease of use. That said, when constexpr is possible, use that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T06:45:09.720",
"Id": "493786",
"Score": "0",
"body": "Yes I did do `sizeof()`, but I assumed that since `Game` also uses `Bird` and `Obstacle` which also use some extra variables, it would be big, but since you've explained it now, I think I will be okay if I continue to use the stack"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T19:56:14.147",
"Id": "250927",
"ParentId": "250892",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "250925",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T05:42:50.003",
"Id": "250892",
"Score": "12",
"Tags": [
"c++",
"object-oriented",
"game",
"physics",
"sfml"
],
"Title": "A Flappy bird Game"
}
|
250892
|
<p>I have a react native native app and I am fetching the state of the toggle buttons from an API and then putting them into redux state. I do not like the way I have implemented it cause it seems very messy and was wondering if anyone would have any suggestions on how to refactor the code.</p>
<p>Below is screen that calls my redux state for each toggle switch.</p>
<pre><code>const SiteSettingsDashboard = (props) => {
const dispatch = useDispatch();
const alarmNotificationsToggle = useSelector(
(state) => state.registration.alarmNotifications
);
const armingNotificationToggle = useSelector(
(state) => state.registration.armingNotifications
);
const faultsNotificationToggle = useSelector(
(state) => state.registration.faultsNotifications
);
const engineerNotificationToggle = useSelector(
(state) => state.registration.engineerNotifications
);
const techZoneNotificationToggle = useSelector(
(state) => state.registration.techZoneNotifications
);
const eventTimerNotificationToggle = useSelector(
(state) => state.registration.eventTimerNotifications
);
const noCommsNotificationToggle = useSelector(
(state) => state.registration.noCommsNotifications
);
const ToggleSwitchInput = (value) => {
dispatch(registrationActions.toggleNotificationInput(value));
};
return (
<View>
<View style={{ flexDirection: "row" }}>
<Text>{IMLocalized("Arming")}</Text>
<Switch
style={styles.right}
trackColor={{ false: "#FF0000", true: "#008000" }}
thumbColor={armingNotificationToggle ? "#008000" : "#FF0000"}
ios_backgroundColor="#3e3e3e"
onValueChange={() => ToggleSwitchInput("arming")}
value={armingNotificationToggle}
/>
</View>
<Card.Divider />
<View style={{ flexDirection: "row" }}>
<Text>{IMLocalized("Faults")}</Text>
<Switch
style={styles.right}
trackColor={{ false: "#FF0000", true: "#008000" }}
thumbColor={faultsNotificationToggle ? "#008000" : "#FF0000"}
ios_backgroundColor="#3e3e3e"
onValueChange={() => ToggleSwitchInput("faults")}
value={faultsNotificationToggle}
/>
</View>
<Card.Divider />
<View style={{ flexDirection: "row" }}>
<Text>{IMLocalized("Engineer")}</Text>
<Switch
style={styles.right}
trackColor={{ false: "#FF0000", true: "#008000" }}
thumbColor={engineerNotificationToggle ? "#008000" : "#FF0000"}
ios_backgroundColor="#3e3e3e"
onValueChange={() => ToggleSwitchInput("engineer")}
value={engineerNotificationToggle}
/>
</View>
<Card.Divider />
<View style={{ flexDirection: "row" }}>
<Text>{IMLocalized("TechZone")}</Text>
<Switch
style={styles.right}
trackColor={{ false: "#FF0000", true: "#008000" }}
thumbColor={techZoneNotificationToggle ? "#008000" : "#FF0000"}
ios_backgroundColor="#3e3e3e"
onValueChange={() => ToggleSwitchInput("techZone")}
value={techZoneNotificationToggle}
/>
</View>
<Card.Divider />
<View style={{ flexDirection: "row" }}>
<Text>{IMLocalized("EventTimers")}</Text>
<Switch
style={styles.right}
trackColor={{ false: "#FF0000", true: "#008000" }}
thumbColor={eventTimerNotificationToggle ? "#008000" : "#FF0000"}
ios_backgroundColor="#3e3e3e"
onValueChange={() => ToggleSwitchInput("eventTimer")}
value={eventTimerNotificationToggle}
/>
</View>
<Card.Divider />
<View style={{ flexDirection: "row" }}>
<Text>{IMLocalized("NoComms")}</Text>
<Switch
style={styles.right}
trackColor={{ false: "#FF0000", true: "#008000" }}
thumbColor={noCommsNotificationToggle ? "#008000" : "#FF0000"}
ios_backgroundColor="#3e3e3e"
onValueChange={() => ToggleSwitchInput("noComms")}
value={noCommsNotificationToggle}
/>
</View>
<Card.Divider />
</Card>
</View>
);
};
const styles = StyleSheet.create({
errorText: {
color: "red",
},
right: {
flex: 1,
},
});
export default SiteSettingsDashboard;
</code></pre>
<p>I have the state of each of the buttons declared in redux.</p>
<pre><code>export const types = Object.freeze({
ToggleAlarmNotification: "TOGGLE_ALARM_NOTIFICATION",
ToggleArmingNotification: "TOGGLE_ARMING_NOTIFICATION",
ToggleFaultsNotification: "TOGGLE_FAULTS_NOTIFICATION",
ToggleEngineerNotification: "TOGGLE_Engineer_NOTIFICATION",
ToggleTechZoneNotification: "TOGGLE_TECH_ZONE_NOTIFICATION",
ToggleEventTimerNotification: "TOGGLE_EVENT_TIMER_NOTIFICATION",
ToggleNoCommsNotification: "TOGGLE_NO_COMMS_NOTIFICATION",
});
const initialState = {
isRequestingLogoImage: false,
alarmNotifications: false,
armingNotifications: false,
faultsNotifications: false,
engineerNotifications: false,
techZoneNotifications: false,
eventTimerNotifications: false,
noCommsNotifications: false,
};
</code></pre>
<p>And here is my reducer file. I do this for all of the toggle buttons.</p>
<pre><code>case types.ToggleNoCommsNotification:
return {
...state,
noCommsNotifications: !state.noCommsNotifications,
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T09:53:47.617",
"Id": "493908",
"Score": "1",
"body": "I can look at this more closely later, but the way that you would avoid all of this special-casing is to have the the notification type ('alarm', 'faults', etc.) be a variable. It seems that you've done this with `ToggleSwitchInput`, but not with your action types or your selectors. You don't need to have a separate action type constant for every toggle. You can use the payload to pass the toggle name."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T09:56:16.627",
"Id": "493909",
"Score": "1",
"body": "Plus all of your `Card` components are essentially the same! I can get this code down to half the size if not less. But I need to go to bed first."
}
] |
[
{
"body": "<p>The general idea here is that we have seven different toggles and we don't want to write the same code seven times in every place. We want to define functions that act on a general notification and pass in the name of the notification as an argument.</p>\n<h3>Actions</h3>\n<p>We can define one action type <code>"TOGGLE_NOTIFICATION"</code> and use the <code>action.payload</code> property to pass through the name of the notification that we are toggling. An action creator will create the right action from just the name.</p>\n<pre><code>export const TOGGLE_NOTIFICATION = "TOGGLE_NOTIFICATION";\n\nexport const toggleNotification = (name) => ({\n type: TOGGLE_NOTIFICATION,\n payload: {\n name\n }\n});\n</code></pre>\n<h3>State</h3>\n<p>Right now the toggles are top-level properties alongside <code>isRequestingLogoImage</code>, but I think it's better to give them their own branch. One advantage of separating them is is that we could use <code>Object.keys()</code> in a selector to get all of the canonical notification names.</p>\n<pre><code>const initialNotifications = {\n alarm: false,\n arming: false,\n faults: false,\n engineer: false,\n techZone: false,\n eventTimer: false,\n noComms: false\n}\n</code></pre>\n<p>We don't actually need a combined initial state, but it would be this:</p>\n<pre><code>const initialState = {\n isRequestingLogoImage: false,\n notifications: initialNotifications,\n};\n</code></pre>\n<h3>Reducer</h3>\n<p>We only have to handle one action now instead of seven! The <code>action.payload.name</code> property is the key which we are updating and we set it to the opposite of the existing value.</p>\n<pre><code>const notifications = (state = initialNotifications, action) => {\n switch (action.type) {\n case TOGGLE_NOTIFICATION: {\n return {\n ...state,\n [action.payload.name]: !state[action.payload.name]\n };\n }\n default:\n return state;\n }\n};\n</code></pre>\n<p>That reducer updates the <code>notifications</code> property only. We combine this branch with the other reducers in your app using the redux <code>combineReducers</code> function.</p>\n<pre><code>// dummy placeholder\nconst isRequestingLogoImage = (state = false, action ) => state;\n\nconst rootReducer = combineReducers({\n isRequestingLogoImage,\n notifications\n});\n\nexport default rootReducer;\n</code></pre>\n<h3>Selectors</h3>\n<p>We can get the current value for each toggle by defining an <code>isEnabled</code> selector as a double arrow function that takes the notification name as the first argument and the state as the second. The double function means that instead of calling <code>useSelector(state => isEnabled(state, name))</code> we can just call <code>useSelector(isEnabled(name))</code>.</p>\n<p>As mentioned before, we can also select all of the notification types in order to loop through them.</p>\n<pre><code>export const isEnabled = (name) => (state) => state.notifications[name];\n\nexport const getNotificationTypes = (state) => Object.keys(state.notifications);\n</code></pre>\n<h3>Components</h3>\n<p>We want to create a generalized <code>ToggleSwitch</code> component which we can use for all notification types rather than writing the same style properties seven different times. This component takes the name/key of the notification as a prop and also accepts an optional label prop so that you can pass in the title-cased version of the name.</p>\n<p>We use redux hooks to get the current on/off value and to dispatch the <code>onValueChange</code> callback.</p>\n<pre><code>const ToggleSwitch = ({name, label}: ToggleSwitchProps) => {\n const value = useSelector(isEnabled(name));\n const dispatch = useDispatch();\n\n return (\n <View style={{ flexDirection: "row" }}>\n <Text>{IMLocalized(label || name)}</Text>\n <Switch\n style={styles.right}\n trackColor={{ false: "#FF0000", true: "#008000" }}\n thumbColor={value ? "#008000" : "#FF0000"}\n ios_backgroundColor="#3e3e3e"\n onValueChange={() => dispatch(toggleNotification(name))}\n value={value}\n />\n </View>\n )\n}\n</code></pre>\n<p>Our <code>SiteSettingsDashboard</code> is now just a bunch of <code>ToggleSwitch</code> JSX declarations. You can manually write them out if you want to control the order and the label text. This is still much simpler than before because we only have one component with two properties instead of a whole View/Text/Switch block.</p>\n<p>But as your current titles are just the notification names in PascalCase, we can loop through and use lodash string functions to create the label.</p>\n<pre><code>const SiteSettingsDashboard = () => {\n const notifications = useSelector(getNotificationTypes);\n\n return (\n <View>\n {notifications.map((name) => (\n <ToggleSwitch\n key={name}\n name={name}\n label={upperFirst(camelCase(name))}\n />\n ))}\n </View>\n );\n};\n</code></pre>\n<p><a href=\"https://codesandbox.io/s/codereview-250893-nw09c\" rel=\"noreferrer\">Complete CodeSandbox Link</a> (with type annotations because I think in typescript)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T08:27:51.090",
"Id": "494010",
"Score": "0",
"body": "Thanks Linda. I tried writing something similar myself but I had some difficulty doing it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T20:32:23.017",
"Id": "251039",
"ParentId": "250893",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "251039",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T07:49:21.973",
"Id": "250893",
"Score": "2",
"Tags": [
"redux",
"react-native"
],
"Title": "Managing redux state of mutiple switch components"
}
|
250893
|
<p>This is the follow-up question for <a href="https://codereview.stackexchange.com/q/250790/231235">A Summation Function For Various Type Arbitrary Nested Iterable Implementation in C++</a>. Besides the summation case, I am trying to implement a <code>Max</code> function which can find the maximum value in various type (comparable) arbitrary nested iterable things as the further step. The recursive technique is also used here in order to iterate all elements. Some concepts as the constraints for template are as below.</p>
<pre><code>template<typename T>
concept Summable = requires(T x) { x + x; };
template<typename T>
concept Iterable = requires(T x)
{
x.begin(); // must have `x.begin()`
x.end(); // and `x.end()`
};
</code></pre>
<p>The key implement part about this <code>Max</code> function.</p>
<pre><code>template<typename T> requires Summable<T>
static T Max(T inputNumber); // Deal with the base case like "Max(static_cast<int>(1))"
template<class T> requires Iterable<T>
static auto Max(const T& numbers); // Deal with the iterable case like "Max(std::vector<long double>{ 1, 1, 1 })"
template<class T> requires Summable<T>
static inline T Max(T inputNumber)
{
return inputNumber;
}
template<class T> requires Iterable<T>
static inline auto Max(const T& numbers)
{
typedef typename std::iterator_traits<typename T::iterator>::value_type
value_type;
decltype(Max(std::declval<value_type &&>())) maxValue{};
maxValue = static_cast<decltype(maxValue)>(Max(numbers.at(0)));
for (auto& element : numbers)
{
if (maxValue < Max(element))
{
maxValue = Max(element);
}
}
return maxValue;
}
</code></pre>
<p>The <code>std::vector</code> test case to this <code>Max</code> function.</p>
<pre><code>std::vector<int> v{ 1, 2, 3, -1, -2, -3 };
int largest_element = *std::max_element(v.begin(), v.end());
std::cout << largest_element << std::endl;
std::cout << Max(v) << std::endl;
</code></pre>
<p>The value of <code>largest_element</code> and the result of <code>Max(v)</code> are the same.</p>
<p>The <code>std::array</code> test case to this <code>Max</code> function.</p>
<pre><code>std::array<long double, 10> testArray;
for (size_t i = 0; i < 10; i++)
{
testArray[i] = i;
}
std::cout << Max(testArray) << std::endl;
</code></pre>
<p>The more complex (<code>std::vector<std::vector<long double>></code>) case:</p>
<pre><code>std::vector<long double> testVector1;
testVector1.push_back(1);
testVector1.push_back(20);
testVector1.push_back(-100);
std::vector<long double> testVector2;
testVector2.push_back(10);
testVector2.push_back(90);
testVector2.push_back(-30);
std::vector<std::vector<long double>> testVector3;
testVector3.push_back(testVector1);
testVector3.push_back(testVector2);
std::cout << Max(testVector3) << std::endl;
</code></pre>
<p>All suggestions are welcome.</p>
<p>The summary information:</p>
<ul>
<li><p>Which question it is a follow-up to?
<a href="https://codereview.stackexchange.com/q/250790/231235">A Summation Function For Various Type Arbitrary Nested Iterable Implementation in C++</a></p>
</li>
<li><p>What changes has been made in the code since last question?</p>
<p>The previous question focus on the summation operation and the main idea in this question is trying to achieve the maximum operation.</p>
</li>
<li><p>Why a new review is being asked for?</p>
<p>In my opinion about this code, there are some problem existed. Although this <code>Max</code> function seems works well, there is a little weird to the usage of <code>Summable</code> concept here. Is it a good idea to replace this <code>Summable</code> into a new concept <code>Comparable</code>? If so, Is there any better idea or suggestion about the design of <code>Comparable</code>? I have ever comes up an idea to the concept <code>Comparable</code> like below.</p>
<pre><code>template<typename T>
concept Comparable = requires(T x) { x > x; };
</code></pre>
<p>However, the operator ">" <a href="https://en.cppreference.com/w/cpp/container/vector/operator_cmp" rel="nofollow noreferrer">has been defined in <code>std::vector</code> until C++20</a>. This operator <code>></code> compares the contents lexicographically. This causes the error "ambiguous call to overloaded function".</p>
<p>Moreover, is it a good idea to simplify the initial value assignment <code>maxValue = static_cast<decltype(maxValue)>(Max(numbers.at(0)));</code> into <code>maxValue = Max(numbers.at(0))</code> (remove the static_cast syntax)?</p>
</li>
</ul>
|
[] |
[
{
"body": "<h1>Using the right concept</h1>\n<p>Indeed, <code>Summable</code> is the wrong concept to use if you want to check if the value type is such that you can calculate the maximum of two values. Have a look at the documentation of <a href=\"https://en.cppreference.com/w/cpp/algorithm/max\" rel=\"nofollow noreferrer\"><code>std::max()</code></a>. In particular, it requires that the type is <a href=\"https://en.cppreference.com/w/cpp/named_req/LessThanComparable\" rel=\"nofollow noreferrer\">LessThanComparable</a>. So you could create a concept to test that. There is already a concept <a href=\"https://en.cppreference.com/w/cpp/concepts/totally_ordered\" rel=\"nofollow noreferrer\"><code>std::totally_ordered</code></a>, which is a bit more strict than necessary.</p>\n<h1>Simplify <code>Max()</code></h1>\n<p>You do an elaborate dance to get the right type for <code>maxValue</code>, but why not just use <code>auto</code>? Also, use <code>std::max()</code> to calculate the maximum for you:</p>\n<pre><code>template<class T> requires Iterable<T>\nstatic inline auto Max(const T& numbers)\n{\n auto maxValue = Max(numbers.at(0));\n\n for (auto& element : numbers)\n {\n maxValue = std::max(maxValue, Max(element));\n }\n\n return maxValue;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T11:57:36.830",
"Id": "250905",
"ParentId": "250895",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "250905",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T08:49:35.707",
"Id": "250895",
"Score": "4",
"Tags": [
"c++",
"recursion",
"c++20"
],
"Title": "A Maximum Function For Various Type Arbitrary Nested Iterable Implementation in C++"
}
|
250895
|
<p>I am trying to create this API endpoint that will accept JSON payload and will calculate quote based on provided factors and their ratings.</p>
<p>I have Entities that contain information about:</p>
<ul>
<li><code>age</code></li>
<li><code>postcode</code></li>
<li><code>ABI code</code><br />
ratings.</li>
</ul>
<p>These <code>AgeRating</code>, <code>PostcodeRating</code> and <code>AbiRating</code> entities implement <code>RatingFactorInterface</code> to force implementation of <code>getRatingFactor()</code> method.</p>
<p><code>QuoteController</code> seems to be violating <em>Single Responsibility</em> and <em>Open/Close</em> design principles as the factors like <code>age</code>, <code>postcode</code> can change - extra factor can be added or one of the factors might not be used.</p>
<p>I was thinking maybe it would be possible for rating factors to be specified in the dependency injection container, but can't seem find a good example how this would work especially with factors that depend on other services like <code>AbiCodeRating</code> which also depends on ABI code which is returned by using third party API which accepts car registration number.</p>
<h3>Question</h3>
<p>How do I refactor the controller and services so I'm not violating Single Responsibility and Open / Close design principles?</p>
<h3>POST JSON Payload example</h3>
<pre><code>{
"age": 20,
"postcode": "PE3 8AF",
"regNo": "PJ63 LXR"
}
</code></pre>
<h3>QuoteController</h3>
<pre><code><?php
namespace App\Controller;
use App\Repository\AbiCodeRatingRepository;
use App\Repository\AgeRatingRepository;
use App\Repository\PostcodeRatingRepository;
use App\Service\AbiCodeLookup;
use App\Service\QuoteCalculator;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
/**
* Class QuoteController
* @package App\Controller
*/
class QuoteController extends AbstractController
{
/**
* @Route("/", name="quote")
*
* @param Request $request
* @param AbiCodeRatingRepository $abiCodeRatingRepository
* @param AgeRatingRepository $ageRatingRepository
* @param PostcodeRatingRepository $postcodeRatingRepository
* @return JsonResponse
*/
public function index(Request $request, AbiCodeRatingRepository $abiCodeRatingRepository, AgeRatingRepository $ageRatingRepository, PostcodeRatingRepository $postcodeRatingRepository)
{
try{
$request = $this->transformJsonBody($request);
/**
* Quoting engine could be used with a different set of rating factors!
* Meaning age, postcode and regNo maybe not be required, some other rating factors might be introduced
* How to make controller to accept rating factors dynamically?
*/
if (!$request || !$request->get('age') || !$request->request->get('postcode') || !$request->get('regNo')){
throw new \Exception();
}
/**
* call to a third party API to look up the vehicle registration number and return an ABI code
* this is only required if AbiRating is used with the quoting engine
*/
$abiCode = AbiCodeLookup::getAbiCode($request->get('regNo'));
/**
* $abiCode is only required if postcodeRating is used by quoting engine
*/
$ratingFactors[] = $abiCodeRatingRepository->findOneBy(["abiCode"=>$abiCode]);
$ratingFactors[] = $ageRatingRepository->findOneBy(["age"=>$request->get("age")]);
/**
* $area is only required if postcodeRating is used by quoting engine
*/
$area = substr($request->get("postcode"),0,3);
$ratingFactors[] = $postcodeRatingRepository->findByPostcodeArea($area);
$premiumTotal = QuoteCalculator::calculate($ratingFactors);
$data = [
'status' => 200,
'success' => "Quote created successfully",
'quote' => $premiumTotal
];
return new JsonResponse($data,200);
}catch (\Exception $e){
$data = [
'status' => 422,
'errors' => "Data is not valid",
];
return new JsonResponse($data,422);
}
}
/**
* @param Request $request
* @return Request
*/
protected function transformJsonBody(Request $request)
{
$data = json_decode($request->getContent(), true);
if ($data === null) {
return $request;
}
$request->request->replace($data);
return $request;
}
}
</code></pre>
<h3>AbiCodeRating</h3>
<pre><code><?php
namespace App\Entity;
use App\Repository\AbiCodeRatingRepository;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass=AbiCodeRatingRepository::class)
*/
class AbiCodeRating implements RatingFactorInterface
{
/**
* @ORM\Id
* @ORM\Column(type="string", length=10)
*/
private $abiCode;
/**
* @ORM\Column(type="decimal", precision=10, scale=2, nullable=true)
*/
private $ratingFactor;
public function getAbiCode(): ?string
{
return $this->abiCode;
}
public function setAbiCode(string $abiCode): self
{
$this->abiCode = $abiCode;
return $this;
}
public function getRatingFactor(): ?float
{
return $this->ratingFactor;
}
public function setRatingFactor(?float $ratingFactor): self
{
$this->ratingFactor = $ratingFactor;
return $this;
}
}
</code></pre>
<h3>AgeRating</h3>
<pre><code><?php
namespace App\Entity;
use App\Repository\AgeRatingRepository;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass=AgeRatingRepository::class)
*/
class AgeRating implements RatingFactorInterface
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
*/
private $age;
/**
* @ORM\Column(type="decimal", precision=10, scale=2, nullable=true)
*/
private $ratingFactor;
public function getAge(): ?int
{
return $this->age;
}
public function setAge(int $age): self
{
$this->age = $age;
return $this;
}
public function getRatingFactor(): ?float
{
return $this->ratingFactor;
}
public function setRatingFactor(?float $ratingFactor): self
{
$this->ratingFactor = $ratingFactor;
return $this;
}
}
</code></pre>
<h3>PostcodeRating</h3>
<pre><code><?php
namespace App\Entity;
use App\Repository\PostcodeRatingRepository;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass=PostcodeRatingRepository::class)
*/
class PostcodeRating implements RatingFactorInterface
{
/**
* @ORM\Id
* @ORM\Column(type="string", length=4)
*/
private $postcodeArea;
/**
* @ORM\Column(type="decimal", precision=10, scale=2, nullable=true)
*/
private $ratingFactor;
public function getPostcodeArea(): ?string
{
return $this->postcodeArea;
}
public function setPostcodeArea(string $postcodeArea): self
{
$this->postcodeArea = $postcodeArea;
return $this;
}
public function getRatingFactor(): ?float
{
return $this->ratingFactor;
}
public function setRatingFactor(?float $ratingFactor): self
{
$this->ratingFactor = $ratingFactor;
return $this;
}
}
</code></pre>
<h3>RatingFactorInterface</h3>
<pre><code><?php
namespace App\Entity;
interface RatingFactorInterface
{
/**
* @return float|null
*/
public function getRatingFactor(): ?float;
}
</code></pre>
<h3>AbiCodeRatingRepository</h3>
<pre><code><?php
namespace App\Repository;
use App\Entity\AbiCodeRating;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @method AbiCodeRating|null find($id, $lockMode = null, $lockVersion = null)
* @method AbiCodeRating|null findOneBy(array $criteria, array $orderBy = null)
* @method AbiCodeRating[] findAll()
* @method AbiCodeRating[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class AbiCodeRatingRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, AbiCodeRating::class);
}
}
</code></pre>
<h3>AgeRatingRepository</h3>
<pre><code><?php
namespace App\Repository;
use App\Entity\AgeRating;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @method AgeRating|null find($id, $lockMode = null, $lockVersion = null)
* @method AgeRating|null findOneBy(array $criteria, array $orderBy = null)
* @method AgeRating[] findAll()
* @method AgeRating[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class AgeRatingRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, AgeRating::class);
}
}
</code></pre>
<h3>PostcodeRatingRepository</h3>
<pre><code><?php
namespace App\Repository;
use App\Entity\PostcodeRating;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @method PostcodeRating|null find($id, $lockMode = null, $lockVersion = null)
* @method PostcodeRating|null findOneBy(array $criteria, array $orderBy = null)
* @method PostcodeRating[] findAll()
* @method PostcodeRating[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class PostcodeRatingRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, PostcodeRating::class);
}
/**
* @return PostcodeRating Returns PostcodeRating objects based on area
*/
public function findByPostcodeArea($area): ?PostcodeRating
{
return $this->findOneBy(["postcodeArea"=>$area]);
}
}
</code></pre>
<h3>AbiCodeLookup</h3>
<pre><code><?php
namespace App\Service;
class AbiCodeLookup
{
public static function getAbiCode(string $regNumber){
/**
* create a request to third party api which would return abi code
* How to configure this service to be used only with regNo factor
*/
return "22529902";
}
}
</code></pre>
<h3>QuoteCalculator</h3>
<pre><code><?php
namespace App\Service;
use App\Entity\RatingFactorInterface;
/**
* Class QuoteCalculator
*/
class QuoteCalculator
{
/**
* @param array $ratingFactors
* @return float
*/
public static function calculate(array $ratingFactors): float
{
$premiumTotal = 500;
foreach ($ratingFactors as $ratingFactor){
$premiumTotal = $premiumTotal * ($ratingFactor instanceof RatingFactorInterface ? $ratingFactor->getRatingFactor() : 1);
}
return $premiumTotal ;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>First I think that is important to redefine the <strong>SRP</strong> principle for better understanding. Robert C. Martin defines responsibility as <strong>a reason to change</strong>, so a class should've <em>just one</em> reason to change.</p>\n<p>In my humble opinion a <em>controller</em> should only care about receiving the request then hand that input over to the service or services that handle the logic and create a response. That would be <strong>its reason to change</strong>.</p>\n<p>In your code, the controller coordinates the logic. It knows which repositories to call, which criteria to apply, which services to execute, the order to do it... So, at least, it has a <em>second</em> reason for changing.</p>\n<p>What should it do then? Well, the controller should handle the request, then transform it to some kind of data structure (like a dummy object, ie: DTO) using a transformer, or similar. When you have that, you handle that data to a service that <em>knows</em> the flow of the use case you want to execute (this service is the one with all the dependencies like repositories, or the calculator service.. or even more complex services with their own dependencies).</p>\n<p>I don't like the static calls either, most of the time they just <em>hide</em> dependencies and violate <strong>DI</strong>, being just structured code in a class oriented disguise.</p>\n<p>When you look at your controller it's not clear which dependencies it has, even if you were to move your code to the service layer, with all those static calls the dependencies would still be hidden and you would've to look at everyline to see which services it's using.</p>\n<pre><code><?php\n\nclass QuoteUseCase {\n \n public function __construct($AbiCodeLookup, $abiCodeRatingRepository, ageRatingRepository...){\n \n }\n \n public function handle(RatingFactor $ratingFactors){\n //here would be your logic\n }\n}\n</code></pre>\n<p>If you look at this pseudocode, you can easily see which dependencies it has (codeLookUp, codeRatingRepo, ageRatingRepo...) and you can see as well which are the arguments it need to perform the <em>use case</em> (ratingFactors). This RatingFactor would perform the role of the dummy object I was talking about earlier.</p>\n<p>You may be wondering, why would you need to do all this, in the end I just moved some code from one class to another. Well, think about the following scenario:</p>\n<p>Imagine tomorrow you have to perform the exact same use case but from the command line instead of a request. What would you do? Would you duplicate all your code?</p>\n<p>If you have that extra service layer that contains the use case logic you could just make a call from a Symfony Command, a PHP Script or whatever and that would be it: you create the same dummy object from command line parameters this time, you get the service with all its dependencies, you hand the DTO to the handle method and that's it.</p>\n<p>PS: It's all about trade-offs, maybe in your example there's no real need to do that kind of separation. It's just <strong>as bad</strong> to refactor and to apply, the so called, principles (that end adding complexity) than to never apply them at all.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T12:27:36.993",
"Id": "493684",
"Score": "0",
"body": "Thanks for the quick reply, so if i lets say have one service dependency in the QuoteController -> public function index(Request $request, QuoteCalculator $quoteCalculator) - QuoteCalculator also depends on array of objects that implement getRatingFactor() - is there a way to create $ratingFactors array based on configuration in config/services.yaml something like below:"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T12:27:40.587",
"Id": "493685",
"Score": "0",
"body": "`code` parameters:\n rating_factors:\n - App\\Service\\AbiCodeRatingUseCase\n - App\\Service\\AgeRatingUseCase\n - App\\Service\\PostcodeRatingUseCase\nservices: \n app.quote_calculator:\n class: App\\Service\\QuoteCalculator\n arguments:\n $ratingFactors: \"%rating_factors%\" `code`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T12:39:44.190",
"Id": "493688",
"Score": "0",
"body": "is there a way in service configuration to set \"array\" argument like $ratingFactors[] in my case which would define which use cases are required in a particular scenario? i don't seem to find on symfony docs about array arguments as dependency although there seems to be array parameters https://symfony.com/doc/2.1/components/dependency_injection/parameters.html#array-parameters"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T06:58:25.587",
"Id": "493901",
"Score": "0",
"body": "I don't think I understand your question. RatingFactors come from the Request, don't they? You can use a Transformer class, some ParamConverters, or something similar to handle the request and get the object. QuoteCalculator is, on the other hand, configured at \"compilation\" time (when Symfony builds the cache and wires everything). With the \"RatingFactors\" class I was just making an example, it would be the DTO that has the values that came in the JSON (maybe with an initial validation of types, and stuff like that)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T11:32:19.040",
"Id": "250903",
"ParentId": "250896",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T09:05:47.627",
"Id": "250896",
"Score": "4",
"Tags": [
"design-patterns",
"symfony4"
],
"Title": "How to refactor Symfony 5 controller to comply with SOLID design principles"
}
|
250896
|
<p>I have a small blog backend in Rust with Rocket and Diesel on Postgres. It reads and writes to and from the database fine, but to get to where it is I used a lot of <code>clone()</code> calls on strings. I feel like it could be written more efficiently with lifetimes, but my grasp of lifetimes in Rust is quite tenuous and I get a lot of compiler complaints.</p>
<p>The blog is divided into collections called 'atlases' with sub pages in each atlas. Each page has properties including ancestors, content blocks, and user IDs and roles. Each request comes with a cookie containing a session ID. To get a page the program receives a POST request to an endpoint containing an atlas ID and a page ID. It uses the cookie to authenticate the request, then queries the database through a Diesel schema to get the content blocks, ancestors, and other bits and bobs belonging to the page, and returns them as JSON data.</p>
<p>The <code>main.rs</code> file is generally standard Rocket boilerplate. The relevant bits for the POST handler to get a page from an atlas:</p>
<pre><code>mod atlas;
#[macro_use]
extern crate rocket;
#[macro_use]
extern crate rocket_contrib;
#[macro_use]
extern crate diesel;
use response::{ResponseJson, ResponsePublicMedia, ResponseStaticFile, STATIC_FILES};
use rocket::http::CookieJar;
use rocket::Data;
pub mod schema;
#[database("postgres_conn")]
pub struct Db(diesel::PgConnection);
... // various endpoints and handlers
#[post("/endpoint/atlas.page.get/<atlas_id>/<page_id>")]
async fn tel_atlas_page_get(
conn: Db,
cookies: &CookieJar<'_>,
atlas_id: String,
page_id: String,
) -> ResponseJson {
atlas::page_get(conn, cookies, atlas_id, page_id).await
}
...
#[launch]
fn rocket() -> rocket::Rocket {
rocket::ignite()
.mount(
"/",
routes![
...
tel_atlas_page_get,
...
],
)
.attach(Db::fairing())
}
</code></pre>
<p>The handler internals file:</p>
<pre><code>use crate::atlas;
use crate::response::ResponseJson;
use crate::users::auth;
use crate::utilities::ERR;
use crate::Db;
use rocket::http::CookieJar;
use rocket_contrib::databases::diesel::prelude::*;
pub async fn page_get(
conn: Db,
cookies: &CookieJar<'_>,
atlas_id: String,
page_id: String,
) -> ResponseJson {
// Page data
let a_clone_page = atlas_id.clone();
let p_clone_page = page_id.clone();
let page = match conn.run(|c| get_page(c, a_clone_page, p_clone_page)).await {
Some(p) => p,
None => return ResponseJson::message("page.404", ""),
};
// User ID
let user_id = match cookies.get("token") {
Some(cookie) => match auth::check(cookie).await {
Some((_email, user_id, _name, _token)) => Some(user_id),
None => None,
},
None => None,
};
// Atlas role
let a_clone_role = atlas_id.clone();
let role = match user_id.clone() {
Some(u) => conn.run(|c| get_atlas_role(c, u, a_clone_role)).await,
None => "none".to_owned(),
};
// Page users
let a_clone_users = atlas_id.clone();
let p_clone_users = page_id.clone();
let users = match user_id.clone() {
Some(u) => {
conn.run(|c| get_users(c, u, a_clone_users, p_clone_users))
.await
}
None => Vec::new(),
};
if page.public || role != "none" || (user_id.is_some() && !users.is_empty()) {
// Page ancestors
let a_clone_ancestors = atlas_id.clone();
let p_clone_ancestors = page_id.clone();
let ancestors = conn
.run(|c| get_ancestors(c, a_clone_ancestors, p_clone_ancestors))
.await;
// Page children
let a_clone_children = atlas_id.clone();
let p_clone_children = page_id.clone();
let children = conn
.run(|c| get_children(c, a_clone_children, p_clone_children))
.await;
// Page blocks
let timestamp_clone = page.timestamp.clone();
let blocks = conn
.run(|c| get_blocks(c, atlas_id, page_id, timestamp_clone))
.await;
// JSON encode
let page_encoded = match serde_json::to_string(&page) {
Ok(e) => e,
Err(_) => return ResponseJson::error(ERR.generic),
};
let users_encoded = match serde_json::to_string(&users) {
Ok(e) => e,
Err(_) => return ResponseJson::error(ERR.generic),
};
let ancestors_encoded = match serde_json::to_string(&ancestors) {
Ok(e) => e,
Err(_) => return ResponseJson::error(ERR.generic),
};
let children_encoded = match serde_json::to_string(&children) {
Ok(e) => e,
Err(_) => return ResponseJson::error(ERR.generic),
};
let blocks_encoded = match serde_json::to_string(&blocks) {
Ok(e) => e,
Err(_) => return ResponseJson::error(ERR.generic),
};
ResponseJson::message(
"atlas.page",
&format!(
"{{\"page\":{},\"atlas_role\":\"{}\",\"users\":{},\"ancestors\":{},\"blocks\":{},\"children\":{}}}",
page_encoded, role, users_encoded, ancestors_encoded, blocks_encoded, children_encoded
),
)
} else {
ResponseJson::message("auth.forbidden", "")
}
}
fn get_page(
conn: &mut diesel::PgConnection,
atlas_id: String,
page_id: String,
) -> Option<atlas::Page> {
use crate::schema::atlas_pages;
if &page_id == "maps" || &page_id == "locations" {
match atlas_pages::table
.select((
atlas_pages::page_id,
atlas_pages::atlas_id,
atlas_pages::title,
atlas_pages::image,
atlas_pages::public,
atlas_pages::parent,
atlas_pages::timestamp,
))
.filter(atlas_pages::atlas_id.eq(&atlas_id))
.filter(atlas_pages::page_id.eq("index"))
.first::<atlas::Page>(conn)
{
Ok(a) => Some(atlas::Page {
page_id,
atlas_id,
title: a.title,
image: a.image,
public: a.public,
parent: "index".to_owned(),
timestamp: a.timestamp,
}),
Err(_) => None,
}
} else {
match atlas_pages::table
.select((
atlas_pages::page_id,
atlas_pages::atlas_id,
atlas_pages::title,
atlas_pages::image,
atlas_pages::public,
atlas_pages::parent,
atlas_pages::timestamp,
))
.filter(atlas_pages::atlas_id.eq(&atlas_id))
.filter(atlas_pages::page_id.eq(&page_id))
.first::<atlas::Page>(conn)
{
Ok(a) => Some(a),
Err(_) => None,
}
}
}
fn get_users(
conn: &mut diesel::PgConnection,
user_id: String,
atlas_id: String,
page_id: String,
) -> Vec<atlas::AtlasUser> {
use crate::schema::page_users;
let user = match page_users::table
.select((page_users::user_id, page_users::user_type))
.filter(page_users::user_id.eq(&user_id))
.filter(page_users::atlas_id.eq(&atlas_id))
.filter(page_users::page_id.eq(&page_id))
.first::<atlas::AtlasUser>(conn)
{
Ok(a) => a,
Err(_) => return Vec::new(),
};
if user.user_type == "owner" {
match page_users::table
.select((page_users::user_id, page_users::user_type))
.filter(page_users::atlas_id.eq(&atlas_id))
.filter(page_users::page_id.eq(&page_id))
.load::<atlas::AtlasUser>(conn)
{
Ok(a) => a,
Err(_) => Vec::new(),
}
} else {
vec![user]
}
}
fn get_atlas_role(conn: &mut diesel::PgConnection, user_id: String, atlas_id: String) -> String {
use crate::schema::page_users;
match page_users::table
.select((page_users::user_id, page_users::user_type))
.filter(page_users::user_id.eq(&user_id))
.filter(page_users::atlas_id.eq(&atlas_id))
.filter(page_users::page_id.eq("index"))
.first::<atlas::AtlasUser>(conn)
{
Ok(a) => a.user_type,
Err(_) => "none".to_owned(),
}
}
fn get_ancestors(
conn: &mut diesel::PgConnection,
atlas_id: String,
page_id: String,
) -> Vec<atlas::Ancestors> {
use crate::schema::page_ancestors;
match page_ancestors::table
.select((
page_ancestors::page_id,
page_ancestors::atlas_id,
page_ancestors::title,
page_ancestors::index,
page_ancestors::ancestor,
))
.filter(page_ancestors::atlas_id.eq(&atlas_id))
.filter(page_ancestors::page_id.eq(&page_id))
.order(page_ancestors::index.asc())
.load::<atlas::Ancestors>(conn)
{
Ok(a) => a,
Err(_) => Vec::new(),
}
}
fn get_children(
conn: &mut diesel::PgConnection,
atlas_id: String,
page_id: String,
) -> Vec<atlas::Page> {
use crate::schema::atlas_pages;
match atlas_pages::table
.select((
atlas_pages::page_id,
atlas_pages::atlas_id,
atlas_pages::title,
atlas_pages::image,
atlas_pages::public,
atlas_pages::parent,
atlas_pages::timestamp,
))
.filter(atlas_pages::atlas_id.eq(&atlas_id))
.filter(atlas_pages::parent.eq(&page_id))
.order(atlas_pages::title.desc())
.load::<atlas::Page>(conn)
{
Ok(a) => a,
Err(_) => Vec::new(),
}
}
fn get_blocks(
conn: &mut diesel::PgConnection,
atlas_id: String,
page_id: String,
timestamp: String,
) -> Vec<atlas::Block> {
use crate::schema::page_blocks;
match page_blocks::table
.select((
page_blocks::page_id,
page_blocks::atlas_id,
page_blocks::index,
page_blocks::label,
page_blocks::block,
page_blocks::text,
page_blocks::data,
page_blocks::timestamp,
))
.filter(page_blocks::atlas_id.eq(atlas_id))
.filter(page_blocks::page_id.eq(page_id))
.filter(page_blocks::timestamp.eq(timestamp))
.order(page_blocks::index.asc())
.load::<atlas::Block>(conn)
{
Ok(a) => a,
Err(_) => Vec::new(),
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T10:06:24.957",
"Id": "250900",
"Score": "2",
"Tags": [
"rust"
],
"Title": "Rust blog backend in Rocket and Diesel, lots of clones"
}
|
250900
|
<h3>Hypothesis</h3>
<p>There is a paid parking lot, with the following rates: $1 for the first hour and $0.5 for every subsequent hour. The parking capacity is of 10 spaces.</p>
<h3>Required</h3>
<p>Make an activity management system for the Parking with the following characteristics:</p>
<ul>
<li>Any parking interval is rounded up, to the nearest hour.</li>
<li>When a new car enters the parking lot, the parking system takes in the registration number of the
car.</li>
<li>When a car leaves the parking, the system issues a summary, depending on the duration of the stay. What information do you consider essential as part of the summary?</li>
<li>Any customer can see the list of cars parked in the parking lot at a given time.</li>
</ul>
<h3>Technical requirements</h3>
<ul>
<li>The implementation will be done using JavaScript, all data being stored in memory, with no need for permanent storage.</li>
<li>Write clean code.</li>
<li>Create a simple GUI that allows entering and reading data from the computer; display the data on the same page.</li>
</ul>
<h3>Solution</h3>
<p>I used Bootstrap 4 for aesthetics. The script itself uses only JavaScript. jQuery is included for the corect functioning of Bootstrap.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let cars = [];
const addCarButton = document.querySelector('#carButton');
const minLicenseeLength = 7;
const payPerHour = 0.5;
const payFirstHour = 1;
const totalPlaces = 10;
const formatDate = (date) => {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12;
minutes = minutes < 10 ? '0' + minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return date.getDate() + "/" + (date.getMonth() + 1) + "/" + date.getFullYear() + " " + strTime;
}
const secondsToHours = (d) => {
d = Number(d);
let h = Math.ceil(d / 3600);
return h;
}
const renterTable = () => {
let results = '';
for (var i = 0; i < cars.length; i++) {
let licensee = cars[i].licensee;
let arrival = formatDate(cars[i].arrival);
let leave = cars[i].leave === '-' ? '-' : formatDate(cars[i].leave);
results += `<tr>
<td>${licensee}</td>
<td>${arrival}</td>
<td>${leave}</td>
<td>${showStatus(cars[i])}</td>
<td class="text-right">${makeBill(cars[i])}</td>
<td class="text-right">
<button data-row="${i}" onclick="showSummary(event)" data-toggle="modal" data-target="#myModal" class="btn btn-sm btn-success">Summary</button>
</td>
</tr>`;
}
document.querySelector("#parking tbody").innerHTML = results;
}
const showStatus = (car) => {
return car.isParked ? "Parked" : "Has left";
}
const changeStatus = (event) => {
cars[event.target.dataset.row].isParked = false;
}
const setLeaveTime = (event) => {
cars[event.target.dataset.row].leave = new Date(Date.now());
}
const countAvailablePlaces = (event) => {
document.querySelector('#placesCount').innerHTML = totalPlaces - cars.length;
}
const setClassForBadge = () => {
let badgeClassName = cars.length == totalPlaces ? 'badge badge-danger' : 'badge badge-success';
document.querySelector('#placesCount').setAttribute('class', badgeClassName);
}
const calculateHoursBilled = (car) => {
let arrivedAt = new Date(car.arrival).getTime();
let leftAt = new Date(car.leave).getTime();
return secondsToHours((leftAt - arrivedAt) / 1000); //duration in seconds
}
const makeBill = (car) => {
let hoursBilled = calculateHoursBilled(car);
let billValue = car.isParked ? "-" : "$" + (payFirstHour + (hoursBilled - 1) * payPerHour);
return billValue;
}
const printSummary = (event) => {
let car = cars[event.target.dataset.row];
let sumarryTable = `<table class="table table-bordered m-0">
<tr>
<td class="font-weight-bold">Registration number</td>
<td>${car.licensee}</td>
</tr>
<tr>
<td class="font-weight-bold">Arrival</td>
<td>${formatDate(car.arrival)}</td>
</tr>
<tr>
<td class="font-weight-bold">Departure</td>
<td>${formatDate(car.leave)}</td>
</tr>
<tr>
<td class="font-weight-bold">Billable hours</td>
<td>${calculateHoursBilled(car)}</td>
</tr>
<tr>
<td class="font-weight-bold">Bill value</td>
<td>${makeBill(car)}</td>
</tr></table>`;
document.querySelector('#modalBody').innerHTML = sumarryTable;
}
const showSummary = (event) => {
changeStatus(event);
setLeaveTime(event);
renterTable();
printSummary(event);
//Free the parking place, 3 seconds after the summary is released
setTimeout(function() {
freeSpot(event);
}, 3000);
}
const addCar = () => {
let newLicensee = document.querySelector("#carValue").value;
let newCar = {
licensee: newLicensee,
arrival: new Date(),
leave: '-',
isParked: true
}
// Add new car to the cars array
document.querySelector('#message').style.display = 'none';
if (newLicensee.length >= minLicenseeLength && cars.length < totalPlaces) {
cars.unshift(newCar);
} else {
if (newLicensee.length < minLicenseeLength) {
document.querySelector('#message').style.display = 'block';
}
}
if (cars.length == totalPlaces) {
document.querySelector('#carButton').setAttribute('disabled', true);
}
setClassForBadge();
//Update places count
countAvailablePlaces(event);
// Empty text box
document.querySelector("#carValue").value = '';
// Render the table
renterTable();
}
const freeSpot = (event) => {
cars.splice(event.target.dataset.row, 1);
setClassForBadge();
if (cars.length == totalPlaces) {
document.querySelector('#carButton').setAttribute('disabled');
} else {
document.querySelector('#carButton').removeAttribute('disabled');
}
// Render Table again after delete
renterTable();
//Update places count
countAvailablePlaces(event);
}
// Add new car to the array
addCarButton.addEventListener('click', addCar);
// Render Table
renterTable();
//Show places count at page load
countAvailablePlaces(event);</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>#addForm {
position: relative;
}
#message {
display: none;
position: relative;
font-size: 10px;
position: absolute;
}
#placesCount {
font-size: 90%;
}
#parking th,
#parking td {
white-space: nowrap;
font-size: 14px;
}
#myModal .font-weight-bold {
font-weight: 500 !important;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<div class="container">
<div class="card my-3">
<div class="card-header px-3 d-flex">
<h5 class="m-0">Parking management</h5>
<div class="ml-auto">
<span id="placesCount" class="badge badge-success"></span> available places
</div>
</div>
<div class="card-body p-0">
<div class="input-group p-2" id="addForm">
<input type="text" class="form-control" id="carValue" placeholder="Registration number">
<div class="input-group-append">
<button id="carButton" class="btn btn-sm btn-success">Park car</button>
</div>
<p id="message" class="text-danger m-0">Registration number invalid</p>
</div>
<div class="table-responsive">
<table id="parking" class="table table-striped m-0">
<thead>
<tr>
<th>Registration no</th>
<th>Arrival</th>
<th>Departure</th>
<th>Status</th>
<th class="text-right">Bill</th>
<th class="text-right">Actions</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
</div>
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h6 class="modal-title">Sumar Parcare</h6>
<button type="button" class="close" data-dismiss="modal">&times;</button>
</div>
<div id="modalBody" class="modal-body"></div>
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
<p>Do you see any problems with this application, including from a <strong>security</strong> stand-point?</p>
<p>Thanks!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T14:31:08.610",
"Id": "493697",
"Score": "1",
"body": "A method like `countAvailablePlaces` is doing two things: the maths and the rendering of the result. These concerns could be separated."
}
] |
[
{
"body": "<p><strong>Prefer <code>const</code></strong> over <code>let</code> and <code>var</code>. When you declare a variable with <code>let</code>, you're indicating to any reader of the code that the variable may be reassigned at any time. When the reassignment isn't actually necessary for the code to work, this results in undesirable cognitive overhead - it may be a constant worry in the back of one's mind "This variable name may be reassigned at any time, so what it's referring to now may not be what it was originally assigned to.* See <a href=\"https://softwareengineering.stackexchange.com/questions/278652/how-much-should-i-be-using-let-vs-const-in-es6\">https://softwareengineering.stackexchange.com/questions/278652/how-much-should-i-be-using-let-vs-const-in-es6</a></p>\n<p>Best to avoid <code>var</code> entirely, it has too many problems to be worth using nowadays - most importantly, it has unintuitive function scope instead of block scope.</p>\n<p><strong>String padding</strong> When you want to pad the start of a string with some leading characters to make the string a particular length (eg, here, <code>9</code> and <code>10</code> to <code>09</code> and <code>10</code> respectively), the most appropriate method to use is <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart\" rel=\"nofollow noreferrer\"><code>padStart</code></a></p>\n<p><strong>Template literals</strong> are great when you need to interpolate multiple variables into a string - they're often preferable to the style of <code>' + someVar + '</code>.</p>\n<p>Taking the above 3 tips into consideration, the <code>formatDate</code> function can be refactored to:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const formatDate = (date) => {\n const hoursMilitary = date.getHours();\n const minutesToDisplay = String(date.getMinutes()).padStart('0', 2);\n const ampm = hoursMilitary >= 12 ? 'PM' : 'AM';\n const hoursToDisplay = (hoursMilitary % 12) || 12;\n const strTime = `${hoursToDisplay}:${minutesToDisplay} ${ampm}`;\n return `${date.getDate()}/${date.getMonth() + 1}/${date.getFullYear()} ${strTime}`;\n}\n</code></pre>\n<p><strong>secondsToHours</strong> can be made much more concise, and without reassignment of the parameter:</p>\n<pre><code>const secondsToHours = d => Math.ceil(d / 3600);\n</code></pre>\n<p><code>/</code> will coerce non-numbers to numbers; you don't need to call <code>Number</code> on <code>d</code> first.</p>\n<p><strong><code>renterTable</code></strong> Lots of improvements can be made here. First, the function name isn't entirely intuitive - what does something called <code>renterTable</code> (noun) do? Is it a variable that contains an HTMLTableElement? Does it create a table and return it? No, it re-renders the table in the DOM given the data in the <code>cars</code> array. Consider calling it <code>renderTable</code> or <code>renderRenterTable</code> (verb) instead.</p>\n<p><strong>Constructing HTML by concatenating user input is unsafe</strong> You have:</p>\n<pre><code> results += `<tr>\n <td>${licensee}</td>\n <td>${arrival}</td>\n <td>${leave}</td>\n <td>${showStatus(cars[i])}</td>\n <td class="text-right">${makeBill(cars[i])}</td>\n <td class="text-right">\n <button data-row="${i}" onclick="showSummary(event)" data-toggle="modal" data-target="#myModal" class="btn btn-sm btn-success">Summary</button>\n </td>\n </tr>`;\n}\ndocument.querySelector("#parking tbody").innerHTML = results;\n</code></pre>\n<p>This will allow for arbitrary code execution. Imagine if someone said:</p>\n<blockquote>\n<p>Try plugging in the following license plate when registering a car, you won't believe what happens next!</p>\n<pre><code><img src onerror='alert("evil")'>\n</code></pre>\n</blockquote>\n<p>where the <code>alert("evil")</code> can be replaced with anything the phisher wants. Then some not-too-intelligent users might fall for it and get their login info / account funds / etc compromized.</p>\n<p>This can be fixed by making sure the <code>licensee</code> contains only valid characters first, eg, turn:</p>\n<pre><code>let newLicensee = document.querySelector("#carValue").value;\nif (!/^[a-z\\d]+$/.test(newLicensee)) {\n // display error message to user: license invalid\n return;\n}\n</code></pre>\n<p>But that's still only a patch job. If the script gets developed in the future, I'd be afraid of accidentally <em>not</em> sanitizing an input before inserting it into the DOM. When user input is involved, I'd prefer to avoid string interpolation entirely with HTML, and instead insert the <code>textContent</code> into the element after the element is put into the document, eg:</p>\n<pre><code>const tr = document.querySelector("#parking tbody").appendChild(document.createElement('tr'));\ntr.innerHTML = `\n <td></td>\n <td></td>\n <td></td>\n ...\n`;\ntr.children[0].textContent = licensee;\ntr.children[1].textContent = arrival;\ntr.children[2].textContent = leave;\n// ...\n</code></pre>\n<p><strong>Or, even better</strong>, for larger projects, consider using a framework that allows for the concise interpolation of input into the DOM, like React:</p>\n<pre><code>const CarRow = (carInfo) => (\n <tr>\n <td>{carInfo.licensee}</td>\n <td>{carInfo.arrival}</td>\n <td>{carInfo.leave}</td>\n ...\n</code></pre>\n<p>All of the above also applies to the <code>sumarryTable</code>, which has the same sort of concatenated-HTML vulnurability</p>\n<p><strong>Spelling</strong> Spelling matters in programming - properly spelled variable names help prevent bugs. Call it <code>summaryTable</code> instead. Also, the word "licensee" refers to the person who holds a license, but your variable refers to the license plate string. Consider calling it <code>licenseID</code> instead of <code>licensee</code>; it'll be less confusing.</p>\n<p><strong>Avoid <code>innerHTML</code></strong> For similar reasons to the above, only use <code>innerHTML</code> when you need to insert HTML markup. If you just want to insert <em>text</em> into an element, use <code>textContent</code>; it'll be safer, faster, and won't have problems with characters that have a special meaning in HTML. This:</p>\n<pre><code>document.querySelector('#placesCount').innerHTML = totalPlaces - cars.length;\n</code></pre>\n<p>can be</p>\n<pre><code>document.querySelector('#placesCount').textContent = totalPlaces - cars.length;\n</code></pre>\n<p>(Could also save the reference to <code>#placesCount</code> instead of re-selecting it each time the function is called)</p>\n<p><strong>Avoid inline handlers</strong> Inside the row markup, you have:</p>\n<pre><code><button data-row="${i}" onclick="showSummary(event)" data-toggle="modal" data-target="#myModal" class="btn btn-sm btn-success">Summary</button>\n</code></pre>\n<p>Inline handlers have <a href=\"https://stackoverflow.com/a/59539045\">too many problems</a> to be worth using in modern code. They require global pollution and have a crazy scope chain, among other issues. Attach the event listener properly using JavaScript instead. Either attach the listener to each button when the button gets inserted into the DOM, or, possibly a better option, use event delegation. See comments below too:</p>\n<pre><code>table.addEventListener('click', (event) => {\n if (!event.target.matches('button')) {\n return;\n }\n // I renamed this from "row" to "rowIndex" to make the variable name more precise;\n // it's not an actual row, it's only an index\n const { rowIndex } = event.target.dataset;\n // Now that the rowIndex has been extracted, grab the car,\n // then pass the car along instead of extracting it inside each function:\n const car = cars[rowIndex];\n changeStatus(car);\n setLeaveTime(car);\n \n renderRenterTable();\n printSummary(car);\n\n //Free the parking place, 3 seconds after the summary is released\n setTimeout(function() {\n freeSpot(rowIndex);\n }, 3000);\n});\n</code></pre>\n<p><strong>Prefer dot notation</strong> when possible, it's more concise and easier to read - you have</p>\n<pre><code>document.querySelector('#placesCount').setAttribute('class', badgeClassName);\n// ...\nif (cars.length == totalPlaces) {\n document.querySelector('#carButton').setAttribute('disabled');\n} else {\n document.querySelector('#carButton').removeAttribute('disabled');\n}\n</code></pre>\n<p>These can be changed to:</p>\n<pre><code>document.querySelector('#placesCount').className = badgeClassName;\n// ...\ndocument.querySelector('#carButton').disabled = cars.length === totalPlaces;\n</code></pre>\n<p>(remember to always use <code>===</code> <a href=\"https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons\">instead of</a> <code>==</code>; <code>==</code> has weird rules that readers of a script should not have to understand in order to grasp the logic being implemented)</p>\n<p><strong>Modern syntax</strong> Modern syntax and modern methods are being used in the source code, which is good - it makes for clean, concise, readable code. For production code, use <a href=\"https://babeljs.io/\" rel=\"nofollow noreferrer\">Babel</a> and polyfills to automatically transpile the source down to ES5 so that obsolete browsers like IE can run the code too.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T19:03:22.957",
"Id": "493722",
"Score": "0",
"body": "The application supposes the existence of a system that reads vehicle registration plates, so I think there is no need for validation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T19:17:30.887",
"Id": "493723",
"Score": "3",
"body": "Your question specifically asked about security, and did not say that the input was trustworthy. Even if the license happens to be trustworthy here, the general approach of concatenating HTML is still not a good idea, as detailed in the answer - when developing the script further, it's easy to make a mistake and open your users up to arbitrary code execution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-26T23:38:54.203",
"Id": "494406",
"Score": "0",
"body": "Please give an answer to **[this question](https://codereview.stackexchange.com/q/251164/178805)** too. Thanks!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T17:50:25.960",
"Id": "250919",
"ParentId": "250902",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "250919",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T11:01:19.133",
"Id": "250902",
"Score": "5",
"Tags": [
"javascript",
"twitter-bootstrap"
],
"Title": "Parking Lot Management System in JavaScript"
}
|
250902
|
<p>I have some directories with artifacts in them, and I want to clean them up by deleting them. The requirements are:</p>
<ul>
<li>Keep the 3 most recent directories</li>
<li>Keep only one snapshot folder</li>
<li>Keep only one rc folder</li>
<li>Delete everything else</li>
<li>The print commands should be written to a log file for posterity</li>
</ul>
<p>This code is in the root of a Linux Server and it will be run every morning.</p>
<p>Lib import
In this case we only have basic libraries, so we do not need to raise the environment first</p>
<pre><code>import os, sys, glob
import datetime
import re
import shutil
import subprocess
from xml.etree import ElementTree
from xml.etree.ElementTree import Element, SubElement, Comment
from xml.dom import minidom
</code></pre>
<p>Environment</p>
<pre><code>env = 'cd environment/bin/activate'
</code></pre>
<p>PATHs</p>
<pre><code>mypath = '/home/directories' #test
path_log = '/home/directories/delete-versions.log' #test
</code></pre>
<p>Gobal VAR</p>
<pre><code>percent = 50
versions = 3
snapshots = 1
rcs = 1
</code></pre>
<p>Security exclude directories</p>
<pre><code>exclude = ['a', 'b', 'c', 'd']
</code></pre>
<p>PREP</p>
<pre><code>def start_var():
now = datetime.datetime.now()
return now
def raise_environment(env):
try:
subprocess.run(env, shell=True)
print('Environment raised')
except:
print('Error: Environment not found. Please, run again manualy')
def info_log(path_log, message):
with open(path_log,'a') as f:
f.write(f'\n{message}\n')
###############################
######### Check space #########
###############################
def bash_commands(command):
ocup = str(subprocess.check_output(command, shell=True))
ocup = int(str(re.findall('\d+', ocup)).replace("['", "").replace("']", ""))
return ocup
###############################
######### Acquisition #########
###############################
def getting_routes(mypath, exclude):
# Getting the list of the directories I am going to iter
roots = routes = []
# Let outside the exclude routes
roots = os.listdir(mypath)
roots = [mypath + '/' + x for x in roots if x not in exclude]
# Looking for directories with more than one version and with xx.xx.xx
# When I found a version directory, i get the up route
for root in roots:
for (dirpath, _, _) in os.walk(root):
find = re.findall('\d+\.\d+\.\d+', dirpath)
if len(find) >= 1:
directory = str(re.findall('^(.+)\/[^\/]+$', dirpath)).replace("['", "").replace("']", "")
if directory not in routes:
routes.append(directory)
print(f'Routes ready')
info_log(path_log, 'Routes ready')
return(routes)
############################
######### Wrangling #########
############################
def delete(path, delete_time):
if len(delete_time) > 0:
for item in delete_time:
#shutil.rmtree(path + '/' + item, ignore_errors=True)
#I want to know if I delete or not the directories, so I do not use ignore_erros and I create a try/except
try:
shutil.rmtree(path + '/' + item)
message08 = ' Deleting: '+ path + '/' + item
print(f'\n{message08}\n')
info_log(path_log, message08)
except:
message09 = item + ' read only. We do not delete'
print(f'\n{message09}\n')
info_log(path_log, message08)
def prettify(elem):
#Return a pretty-printed XML string for the Element.
rough_string = ElementTree.tostring(elem, 'utf-8')
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent=" ") # For each element
def create_modify_xmls(path, all, keep_directories, keep_snapshots):
now = str(datetime.datetime.now())
top = Element('metadata')
child1 = SubElement(top, 'Id')
child1.text = '.'.join(path.replace(mypath + '/', '').split('/')[:-1])
child2 = SubElement(top, 'Id02')
child2.text = path.split('/')[-1]
child3 = SubElement(top, 'versioning')
current_group = SubElement(child3, 'versions')
lastupdated = SubElement(child3, 'lasUpdated')
lastupdated.text = now
# metadata-local
for a in all:
version = SubElement(current_group, 'version')
version.text = a
xml = str(prettify(top))
with open(path + '/-local.xml','w') as f:
f.write(xml)
# metadata-releases
for k in keep_directories:
version = SubElement(current_group, 'version')
version.text = k
xml = str(prettify(top))
with open(path + '/-releases.xml','w') as f:
f.write(xml)
for s in keep_snapshots:
version = SubElement(current_group, 'version')
version.text = s
xml = str(prettify(top))
with open(path + '/-snapshots.xml','w') as f:
f.write(xml)
############################
######### Analysis #########
############################
def find_directories_snapshots_rcs(routes, snapshots, rcs, versions):
for path in routes:# List of routes to find
files = os.listdir(path) #List with all inside path
snapshots = keep_snapshorts = delete_snapshots = []
rcs = keep_rcs = delete_rcs = xmls = []
all_directories = keep_directories = delete_directories = []
message03 = '----------------------------------------------------\nGo to:'+ path +'\n----------------------------------------------------'
print(f'\n{message03}\n')
info_log(path_log, message03)
for f in files: # For each element
is_directory = os.path.isdir(path + '/' + f)
if is_directory == True:
all_directories.append(f)
all_directories.sort(reverse=True)
message04 = ' All directories: '+ str(all_directories)
print(f'\n{message04}\n')
info_log(path_log, message04)
# We are going to find here snapshot, redhat and RCs
# Everything else is going to be treated as the same
snapshots = [w for w in all_directories if 'SNAPSHOT' in w]
snapshots.sort(reverse=True)
if len(snapshots) > 0:
keep_snapshots = snapshots[:snapshots]
delete_snapshots = snapshots[snapshots:]
message05 = ' All snapshots:'+ str(snapshots) +'\n Snapshots to keep: ' + str(keep_snapshots) + '\
\n Snapshots to delete: ' + str(delete_snapshots)
print(f'\n{message05}\n')
info_log(path_log, message05)
# Now RCs
rcs = [w for w in all_directories if 'RC' in w]
rcs.sort(reverse=True)
if len(rcs) > 0:
keep_rcs = rcs[:rcs]
delete_rcs = rcs[rcs:]
message06 = ' All RCs:'+ str(rcs) + '\n RCs to keep: ' + str(keep_rcs) + '\n RCs to delete: '+ str(delete_rcs)
print(f'\n{message06}\n')
info_log(path_log, message06)
# Now redhats
# We want to delete all redhats
redhats = [w for w in all_directories if 'redhat' in w]
# Preparamos
all_directories = [x for x in all_directories if x not in snapshots]
all_directories = [x for x in all_directories if x not in rcs]
all_directories = [x for x in all_directories if x not in redhats]
keep_directories = all_directories[:versions]
delete_directories = all_directories[versions:] + redhats
delete_time = delete_snapshots + delete_rcs + delete_directories
all = keep_directories + keep_rcs + keep_snapshots
all.sort()
message07 = ' Directories:'+ str(all_directories) +'\n Directories to keep: '+ str(keep_directories) +'\n Directories to delete: '+ str(delete_directories)
print(f'\n{message07}\n')
info_log(path_log, message07)
# Now is when delete for real
delete(path, delete_time)
# Create XML
create_modify_xmls(path, all, keep_directories, keep_snapshots)
def duration(start):
end = datetime.datetime.now()
duration = end - start
message10 = 'Duracion del proceso: '+ str(duration)
print(f'\n{message10}\n')
info_log(path_log, message10)
#################################################################################################
if __name__ == '__main__':
raise_environment(paradigma_env)
start = start_var()
message01 = '--------------------------------- Ejecution ' + str(start)+' ------------------'
info_log(path_log, message01)
command01 = "df -k | grep root | awk '{print $5}'"
ocup01 = bash_commands(command01)
if ocup01 < percent:
# If the ocupation of the server ies less tahan the percent we did, out and log
message02 = 'Ocu is ' + str(ocup01) + '%, less than '+ str(percent) +'%.\
\nOut'
print(f'\n{message02}\n')
info_log(path_log, message02)
else:
# It the ocupation is high or equal to percent, start
message03 = 'Ocup is '+ str(ocup01) +'%, higher or equal to '+ str(percent) +'%.\nStart delete process'
print(f'\n{message03}\n')
info_log(path_log, message03)
routes = getting_routes(mypath, exclude)
find_directories_snapshots_rcs(routes, snapshots, rcs, versions)
duration(start)
</code></pre>
|
[] |
[
{
"body": "<p>Stream of consciousness review from top-to-bottom.</p>\n<ul>\n<li>You should make sure you're adhering to <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> and general styling guides. I like to use <a href=\"https://black.readthedocs.io/en/latest/\" rel=\"nofollow noreferrer\">Black</a> to format my code</li>\n<li><code>start_var</code> just obfuscates <code>datetime.datetime.now()</code> and doesn't need to exist. <code>duration</code> is similar. I honestly would rather see this wrapped up in your info logger class (see below) - have it log start/end time on <code>__enter__</code> and <code>__exit__</code>.</li>\n<li>I don't see the point of <code>raise_environment</code> - you could just do <code>os.chdir(path)</code></li>\n</ul>\n<h3><code>info_log</code></h3>\n<p>I don't like that this repeatedly opens a file everytime you need it, and now everything needs to know/assume the <code>path_log</code> variable everywhere. Instead, I would prefer that you construct a logger object and pass that around. This also lets you avoid the messy duplication of printing and logging.</p>\n<p>I would do something like this (untested):</p>\n<pre><code>import sys\nclass InfoLogger:\n\n def __init__(self, log_file, print_loc=sys.stdout):\n self.log_file = log_file\n self.print_here = print_loc\n\n def __enter__(self):\n self.open_file = open(self.log_file, 'a')\n\n def __exit__(self):\n self.open_file.close()\n\n def log_message(message):\n to_write = f"\\n{message}\\n"\n self.open_file.write(to_write)\n self.print_here.write(to_write)\n</code></pre>\n<p>This lets you do something like this:</p>\n<pre><code>with InfoLogger(path_log) as logger:\n getting_routes(base_path, exclude_list, logger)\n # etc\n</code></pre>\n<p>If you don't do this, please at least factor your print statements into this as well to avoid duplication of formatting.</p>\n<h3><code>getting_routes</code></h3>\n<p>Throughout this function, you use low-level <code>os</code> APIs, or you do direct string operations. In Python 3.4+, you can use <a href=\"https://docs.python.org/3/library/pathlib.html#module-pathlib\" rel=\"nofollow noreferrer\"><code>pathlib</code></a> instead.</p>\n<p>A few additional notes:</p>\n<ul>\n<li><code>re.findall('\\d+\\.\\d+\\.\\d+')</code> is pretty magic, and doesn't actually get used (we don't care about the versions, we just want to check if they exist). I would probably wrap this in a helper function</li>\n<li><code>directory = str(re.findall('^(.+)\\/[^\\/]+$', dirpath)).replace("['", "").replace("']", "")</code> is not what you want - you want <code>re.findall('pattern').join(",")</code> (I don't know why - this line doesn't make sense to me, which is a good indicator that you need a helper function, to split it onto multiple lines, and maybe some comments)</li>\n<li><code>if directory not in routes</code> can get very expensive for long lists. Consider using a <a href=\"https://docs.python.org/3/library/stdtypes.html#set\" rel=\"nofollow noreferrer\"><code>set</code></a> instead</li>\n</ul>\n<p>I ended up with something like this:</p>\n<pre><code>def getting_routes(mypath, exclude):\n routes = set()\n get_routes_recursive(mypath, exclude, routes)\n return routes\n\ndef get_routes_recursive(base_path, exclude_list, routes):\n for path in base_path.iterdir():\n if path.name in exclude_list:\n continue\n if path.is_dir():\n if is_versioned_path(path.name):\n add_all_children(path, exclude_list, routes)\n else:\n get_routes_recursive(path, exclude_list, routes)\n\ndef add_all_children(base_path, exclude_list, routes):\n routes.update(\n path\n for path in base_path.glob("**\\*")\n if path.name not in exclude_list\n ) \n\ndef is_versioned_path(path):\n return re.findall(r"\\d+\\.\\d+\\.\\d+", path.name) \n</code></pre>\n<h3><code>delete</code></h3>\n<p>You should not use length to identify non-empty lists (this applies elsewhere) - instead, you can just do <code>if my_list</code>. Even better, if the only thing you want to do is loop, then just loop - it won't do anything if empty.</p>\n<p>When you handle exceptions, you should never use a bare <code>except:</code> - always catch the specific list of exceptions you want to do something with.</p>\n<p>Additionally, for safety, you should avoid just concatenating paths. Instead, you can use the <a href=\"https://docs.python.org/3/library/pathlib.html#operators\" rel=\"nofollow noreferrer\">slash operator</a>: <code>shutil.rmtree(path / item)</code> (this assumes you're using <code>pathlib</code>.</p>\n<p>I didn't notice it until here, but you don't need a unique <code>messageX</code> variable for each message (I don't think you need them at all - see <code>InfoLogger</code> above). Just use <code>message</code> (or whatever) each time.</p>\n<h3><code>create_modify_xmls</code></h3>\n<p>This line is very suspect:</p>\n<pre><code>child1.text = '.'.join(path.replace(mypath + '/', '').split('/')[:-1])\n</code></pre>\n<p>I don't know exactly what you're trying to do - I <em>think</em> you're trying to remove your root path, and then get the path without the final component? There are a number of <a href=\"https://docs.python.org/3/library/pathlib.html#accessing-individual-parts\" rel=\"nofollow noreferrer\">APIs</a> that I think will work better for this. Specifically, you would do something like this (just guessing):</p>\n<pre><code>mypath = Path("/home/directories")\nchildpath = Path(<something>)\nif childpath.is_relative_to(mypath):\n mypath_parents_length = len(mypath.parents)\n child1.text = ".".join(\n parent.name\n for i, parent in enumerate(childpath.parents)\n if i >= mypath_parents_length\n )\nelse:\n child1.text = ".".join(childpath.parents.name)\n</code></pre>\n<p>Similarly, <code>child2.text = path.split('/')[-1]</code> should become <code>child2.text = path.name</code></p>\n<h3><code>find_directories_snapshots_rcs</code></h3>\n<p>Again, this will be cleaner with <code>pathlib</code> instead of <code>os</code>.</p>\n<p>There's a lot of code here, and I'm hitting review fatigue, so I won't touch on everything:</p>\n<p>This pattern (<code>some_list = list[:list]</code>) doesn't work - you can't slice using a list, unless there is something I'm missing about how you've defined this.</p>\n<p>I suspect that you'll be better off not using list comprehensions and just looping over <code>all_directories</code> once to accumulate your other lists.</p>\n<p>Avoid using the names of builtins (<code>all</code>) as variable names</p>\n<h3>Final thoughts</h3>\n<p>I don't think you need to use subprocess (<code>"df -k | grep root | awk '{print $5}'"</code>); I think you can just use <a href=\"https://docs.python.org/3/library/os.html#os.statvfs\" rel=\"nofollow noreferrer\"><code>os.statvfs</code></a> (I'm on a Windows machine, so I can't test).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T15:37:06.480",
"Id": "250912",
"ParentId": "250909",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "250912",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T13:58:50.613",
"Id": "250909",
"Score": "3",
"Tags": [
"beginner",
"python-3.x",
"file-system"
],
"Title": "Clean up directory and file artifacts"
}
|
250909
|
<p>I was recently set Task 2 as seen below and I realise someone answer the question on this site <a href="https://codereview.stackexchange.com/questions/210517/two-player-dice-game-for-nea-task-computer-science-updated">here</a> but I wanted a fresh opinion</p>
<p>TASK 2:</p>
<ol>
<li>Allows two players to enter their details, which are then authenticated to ensure that they are authorised players.</li>
<li>Allows each player to roll two 6-sided dice.</li>
<li>Calculates and outputs the points for each round and each player’s total score.</li>
<li>Allows the players to play 5 rounds.</li>
<li>If both players have the same score after 5 rounds, allows each player to roll 1 die each until someone wins.</li>
<li>Outputs who has won at the end of the 5 rounds.</li>
<li>Stores the winner’s score, and their name, in an external file.</li>
<li>Displays the score and player name of the top 5 winning scores from the external file.</li>
</ol>
<pre><code>try: File = open("Users.txt","r")
except FileNotFoundError:
raise SystemExit("User file not found")
File = open("Users.txt", "r")
def Login(Username, Player):
File.seek(0)
for Line in File:
ValidUsername = Line.split(",")[0]
ValidPassword = Line.split(",")[1].replace("\n", "")
if Username == ValidUsername:
Password = input("Password: ")
if Password == ValidPassword:
print("Player",Player,"logged in")
print("")
return True
else: print("Invalid Details")
return False
try:
while True:
print("Player 1 Login")
Username1 = input("Username: ")
if Login(Username1, 1): break
print("")
while True:
print("Player 2 Login")
Username2 = input("Username: ")
if Username1 == Username2:
print("Double login detected")
elif Login(Username2, 2): break
print("")
except KeyboardInterrupt:
raise SystemExit("Exiting...")
finally:
File.close()
import random
Player1Score = 0
Player2Score = 0
def Roll():
Dice1 = random.randint(1, 6)
Dice2 = random.randint(1, 6)
print("You rolled a",Dice1,"and a",Dice2)
Change = Dice1 + Dice2
Change += 10 if (Dice1 + Dice2) % 2 == 0 else -5
if Change < 0: Change = 0
if Dice1 == Dice2:
Dice3 = random.randint(1, 6)
print("Your third roll is a",Dice3)
Change += Dice3
print("")
return Change
for X in range(5):
print("Play:",X + 1,"starting")
input("Player 1, press enter to roll: ")
Player1Score += Roll()
input("Player 2, press enter to roll: ")
Player2Score += Roll()
print("Player 1 now has a score of",Player1Score)
print("Player 2 now has a score of",Player2Score)
print("")
if Player1Score > Player2Score: Winner = 1
if Player1Score < Player2Score: Winner = 2
if Player1Score == Player2Score:
print("You both got the same score")
def SameScore():
input("Press enter to roll dice: ")
print("")
Dice1 = random.randint(1, 6)
Dice2 = random.randint(1, 6)
print("Player 1 rolled:",Dice1)
print("Player 2 rolled:",Dice2)
if Dice1 == Dice2: return False
if Dice1 > Dice2: return 1
if Dice1 < Dice2: return 2
Winner = False
while not Winner:
Winner = SameScore()
if Winner == 1:
Winner = Username1 + ": " + str(Player1Score)
print(Username1,"won with",Player1Score,"points")
print(Username2,"lost with",Player2Score,"points")
if Winner == 2:
Winner = Username2 + ": " + str(Player2Score)
print(Username2,"won with",Player2Score,"points")
print(Username1,"lost with",Player1Score,"points")
WinnerScore = int(Winner.split(": ")[1])
FileWritten = False
try:
File = open("Scores.txt", "r")
Data = File.readlines();File.close()
for X in range(len(Data)):
if WinnerScore > int(Data[X].split(": ")[1]):
Data.insert(X, Winner + "\n")
if len(Data) > 5: Data.pop(5)
FileWritten = True; break
if len(Data) < 5:
if not FileWritten: Data.append(Winner + "\n")
File = open("Scores.txt","w")
for X in Data:
File.write(X.replace("\n","") + "\n")
except FileNotFoundError:
File = open("Scores.txt","w")
File.write(Winner + "\n")
File.close()
print("")
File = open("Scores.txt","r")
print("Highscores:")
for Line in File:
if Line != "": print(Line.replace("\n", ""))
File.close()
</code></pre>
<p>Any thoughts/optimisations would be greatly appreciated</p>
|
[] |
[
{
"body": "<p>There's a lot in your code that can be refactored but let's start from the beginning with some Python styleguides (also called <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>)</p>\n<h2>Imports</h2>\n<p>It's recommended to write all the imports at the top of your file.</p>\n<h2>Naming</h2>\n<p>In Python, the name of functions and variables should be <em>snake_case</em>d. That is, instead of <code>def Roll()</code> you should have <code>def roll()</code>, instead of <code>Player1Score</code> you should have <code>player1_score</code> and so on. You got the idea. Read more about it <a href=\"https://www.python.org/dev/peps/pep-0008/#naming-conventions\" rel=\"nofollow noreferrer\">here</a></p>\n<h2>Say NO to `;` in Python!</h2>\n<p>Don't use <code>;</code> in Python. It's not needed, and it makes me remember the hard times I was using C / C++. You don't want me to be sad, do you? :( </p>\n<h2>General</h2>\n<p>It's usually good practice to try to avoid inline blocks of code. It's hard to follow and it doesn't have any benefits. This:</p>\n<pre><code>if Player1Score > Player2Score: Winner = 1\n</code></pre>\n<p>Should be written as:</p>\n<pre><code>if Player1Score > Player2Score: \n Winner = 1\n</code></pre>\n<p>That said, your code so far, taking the above advice into consideration, would look like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import random\n\n\ntry:\n file = open("Users.txt", "r")\nexcept FileNotFoundError:\n raise SystemExit("User file not found")\nfile = open("Users.txt", "r")\n\n\ndef same_score():\n input("Press enter to roll dice: ")\n print("")\n dice_1 = random.randint(1, 6)\n dice_2 = random.randint(1, 6)\n print("player 1 rolled:", dice_1)\n print("player 2 rolled:", dice_2)\n if dice_1 == dice_2:\n return False\n if dice_1 > dice_2:\n return 1\n if dice_1 < dice_2:\n return 2\n\n\ndef login(username, player):\n file.seek(0)\n for line in file:\n valid_username = line.split(",")[0]\n valid_password = line.split(",")[1].replace("\\n", "")\n if username == valid_username:\n password = input("password: ")\n if password == valid_password:\n print("player", player, "logged in")\n print("")\n return True\n else:\n print("Invalid Details")\n return False\n\n\ndef roll():\n dice1 = random.randint(1, 6)\n dice2 = random.randint(1, 6)\n\n print("You rolled a", dice1, "and a", dice2)\n\n change = dice1 + dice2\n change += 10 if (dice1 + dice2) % 2 == 0 else -5\n\n if change < 0:\n change = 0\n\n if dice1 == dice2:\n dice3 = random.randint(1, 6)\n print("Your third roll is a",dice3)\n change += dice3\n\n print("")\n return change\n\n\ntry:\n while True:\n print("player 1 login")\n username1 = input("username: ")\n if login(username1, 1):\n break\n print("")\n\n while True:\n print("player 2 login")\n username2 = input("username: ")\n if username1 == username2:\n print("Double login detected")\n elif login(username2, 2):\n break\n print("")\nexcept KeyboardInterrupt:\n raise SystemExit("Exiting...")\nfinally:\n file.close()\n\nplayer1_score = 0\nplayer2_score = 0\n\nfor x in range(5):\n print("Play:", x + 1, "starting")\n input("player 1, press enter to roll: ")\n player1_score += roll()\n\n input("player 2, press enter to roll: ")\n player2_score += roll()\n\n print("player 1 now has a score of", player1_score)\n print("player 2 now has a score of", player2_score)\n print("")\n\nif player1_score > player2_score:\n winner = 1\n\nif player1_score < player2_score:\n winner = 2\n\nif player1_score == player2_score:\n print("You both got the same score")\n winner = False\n while not winner:\n winner = same_score()\n\nif winner == 1:\n winner = username1 + ": " + str(player1_score)\n print(username1, "won with", player1_score, "points")\n print(username2, "lost with", player2_score, "points")\n\nif winner == 2:\n winner = username2 + ": " + str(player2_score)\n print(username2, "won with", player2_score, "points")\n print(username1, "lost with", player1_score, "points")\n\nwinner_score = int(winner.split(": ")[1])\nfile_written = False\ntry:\n file = open("Scores.txt", "r")\n data = file.readlines()\n file.close()\n for x in range(len(data)):\n if winner_score > int(data[x].split(": ")[1]):\n data.insert(x, winner + "\\n")\n if len(data) > 5:\n data.pop(5)\n file_written = True\n break\n\n if len(data) < 5:\n if not file_written:\n data.append(winner + "\\n")\n\n file = open("Scores.txt", "w")\n for x in data:\n file.write(x.replace("\\n", "") + "\\n")\nexcept FileNotFoundError:\n file = open("Scores.txt", "w")\n file.write(winner + "\\n")\nfile.close()\nprint("")\n\nfile = open("Scores.txt", "r")\nprint("Highscores:")\nfor line in file:\n if line != "":\n print(line.replace("\\n", ""))\nfile.close()\n</code></pre>\n<p>Now, this is a bit better. Let's discuss the actual implementation now.</p>\n<p>Here:</p>\n<pre class=\"lang-py prettyprint-override\"><code>try:\n file = open("Users.txt", "r")\nexcept FileNotFoundError:\n raise SystemExit("User file not found")\nfile = open("Users.txt", "r")\n</code></pre>\n<p>You're trying to open a file, and if it doesn't exist you raise and exception. There's nothing necessarily wrong with this, but notice how you open the file two times if there's no exception raised. If you want to check if a file exists or not, you could use the <code>os</code> module to confirm if a filepath exists and create a function which does that. Also, make the filepath a constant and put it at the top of your script:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import os\n\n\nUSERS_FILEPATH = '/path/to/Users.txt'\n\n\ndef check_file(filepath):\n """Verify if a filepath exists.\n \n Return True if a filepath exists. Otherwise raise an exception.\n \n Arguments:\n filepath (str): Path to a file\n \n Returns:\n True or raise an exception\n """\n if not os.path.exists(filepath):\n raise OSError('User filepath {} not found.'.format(filepath))\n return True\n</code></pre>\n<p>In order to call the function you can do:</p>\n<pre class=\"lang-py prettyprint-override\"><code>if check_path(USERS_FILEPATH):\n # do things here\n</code></pre>\n<p>There are a couple of new things here. First, notice how I added a docstring to this function and how easy it is to tell what it actually does. Second, notice how easy it is to use this function on any other files that your game might make use of. Third, look at how the string is formatted when I raise an exception. You can read more about Python's strings formatting <a href=\"https://www.learnpython.org/en/String_Formatting\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p>//have to go for now</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T17:09:10.357",
"Id": "493829",
"Score": "0",
"body": "If the \"Users.txt\" file is in the same directory (and will always be), is it important to specify the file path?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T07:37:22.600",
"Id": "250946",
"ParentId": "250911",
"Score": "4"
}
},
{
"body": "<p>Welcome to Code Review!</p>\n<h2>PEP-8</h2>\n<p>In python, it is common (and recommended) to follow the PEP-8 style guide for writing clean, maintainable and consistent code.</p>\n<p>Functions and variables should be named in a <code>lower_snake_case</code>, classes as <code>UpperCamelCase</code>, and constants as <code>UPPER_SNAKE_CASE</code>.</p>\n<h2>f-strings</h2>\n<p>Newly introduced in python 3 is the f-string; so instead of having <code>print("string", variable, "string")</code> you can do:</p>\n<pre><code>print(f"string {variable} string")\n</code></pre>\n<p>for the same effect.</p>\n<h2>Functions</h2>\n<p>Split your code into individual smaller functions, doing singular tasks. A few examples would be, fetching user/password from <code>users.txt</code>, validating user details, reading user credentials and so on.</p>\n<h2><code>if __name__</code> block</h2>\n<p>For scripts, it is a good practice to put your executable feature inside the <code>if __name__ == "__main__"</code> clause.</p>\n<h2>Control flow</h2>\n<p>You try to open users file twice (same is true for scores file). This is followed by a function definition, followed by code to get users to login. Then you have your first import statement followed by yet another function definition and later code again.</p>\n<p>Try grouping blocks together. In python (and almost all programming languages), imports are the very first thing (after shebang). Then global constants, functions/classes definitions and then the script code itself.</p>\n<h2><code>with</code> statements</h2>\n<p>Instead of you managing opened file descriptors and later controlling the closure of those, python has <code>with</code> statement that wraps this for you:</p>\n<pre><code>with open(your_file, mode) as f:\n something = f.read()\n # f.write(something)\n</code></pre>\n<p>this auto closes (and keeps in-scope) the file descriptor.</p>\n<h2>Associated attributes</h2>\n<p>You have player element, which has associated properties like username, player_id, score. This can be put into a class, instead of maintaining 10 different variables for each player.</p>\n<h2>Inbuilt methods</h2>\n<p>At a lot of places in your code, you are doing a <code>.replace("\\n", "")</code>. This is not really needed, as string objects in python have a <code>.strip()</code> method, which cleans up all whitespaces (and newlines).</p>\n<p>Similarly, you try to capture a <code>FileNotFoundError</code> only to raise another error for the same reason. Let the error specifically defined for the job do that. No need to capture if you want the program to fail in case of missing file anyway.</p>\n<hr />\n<h3>Rewrite</h3>\n<pre><code>from operator import itemgetter\nimport random\n\nUSERS_FILE: str = "Users.txt"\nSCORES_FILE: str = "Scores.txt"\nNUM_PLAYERS: int = 2\nNUM_ROUNDS: int = 5\n\n\ndef roll_die() -> int:\n return random.randint(1, 6)\n\n\nclass Player:\n def __init__(self, _id: int, name: str):\n self._id = _id\n self.name = name\n self.score = 0\n\n def add_score(self, value: int):\n self.score += value\n if self.score < 0:\n self.score = 0\n\n def turn(self):\n input(f"{self.name}'s turn. Press enter to roll.")\n dice_1 = roll_die()\n dice_2 = roll_die()\n print(f"{self.name} rolled {dice_1} and {dice_2}.")\n change = dice_1 + dice_2\n change += 10 if change % 2 == 0 else -5\n if change < 0:\n change = 0\n if dice_1 == dice_2:\n dice_3 = roll_die()\n print(f"Third roll is {dice_3}")\n change += dice_3\n self.add_score(change)\n\n def __str__(self) -> str:\n return f"Player({self.name}): {self.score}"\n\n\ndef fetch_users() -> dict:\n users = {}\n with open(USERS_FILE, "r") as f:\n users = dict([line.strip().split(",") for line in f])\n return users\n\n\ndef authenticate(users: dict, name: str, password: str) -> bool:\n return users.get(name) == password\n\n\ndef show_highscores() -> None:\n with open(SCORES_FILE, "r") as f:\n print(f.read())\n\n\ndef fetch_highscores() -> list:\n scores = []\n with open(SCORES_FILE, "r") as f:\n for line in f:\n name, score = line.strip().split(": ")\n score = int(score)\n scores.append((name, score))\n return scores\n\n\ndef write_score(player: Player, limit: int = 5):\n current_highscores = fetch_highscores()\n current_highscores.append((player.name, player.score))\n sorted_scores = sorted(current_highscores, key=itemgetter(1), reverse=True)\n with open(SCORES_FILE, "w") as f:\n for name, score in sorted_scores[:limit]:\n f.write(f"{name}: {score}\\n")\n\n\ndef get_player(_id: int, users: dict) -> Player:\n print(f"Players {_id} login")\n while True:\n name = input("username: ")\n password = input("password: ")\n if authenticate(users, name, password):\n return Player(_id, name)\n print("Invalid details. Try again!")\n\n\ndef get_winning_player(players: list) -> Player:\n def filter_winning_players(player_dices: list, value: int):\n filtered = []\n for player, dice in player_dices:\n print(f"{player.name} rolled {dice}.")\n if dice == value:\n filtered.append(player)\n return filtered\n max_score = max([player.score for player in players])\n winners = [player for player in players if player.score == max_score]\n if len(winners) == 1:\n return winners[0]\n print(f"{len(winners)} players have the same score. Trying to determine single winning player.")\n while True:\n input("Press enter to roll dice: ")\n dices = [roll_die() for _ in range(len(winners))]\n max_dice = max(dices)\n winners = filter_winning_players(zip(winners, dices), max_dice)\n if len(winners) == 1:\n return winners[0]\n\n\ndef game():\n users = fetch_users()\n players = [get_player(count + 1, users) for count in range(NUM_PLAYERS)]\n for round in range(1, NUM_ROUNDS + 1):\n for player in players:\n player.turn()\n print(f"Player scores at end of round {round}:")\n for player in players:\n print(str(player))\n winner = get_winning_player(players)\n print(f"Winner is {winner}.")\n write_score(winner)\n print("Highscores: ")\n show_highscores()\n\n\nif __name__ == "__main__":\n game()\n</code></pre>\n<hr />\n<h3>NOTE</h3>\n<p>The rewrite allows for multiple players, along with option to set multiple rounds (<code>NUM_PLAYERS</code> and <code>NUM_ROUNDS</code>).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T17:32:20.740",
"Id": "493831",
"Score": "0",
"body": "I might be being dumb here but is there any reason to create a one line definition? (The roll_dice() since it would be just as ok to assign the variable a random number instead of creating a def?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T00:33:42.497",
"Id": "493883",
"Score": "0",
"body": "@Evorage so that when you require a change that instead of 6 sided dice, it should be 20-sided, the changes would be at just one place instead of updating 30 different places."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T08:21:04.910",
"Id": "250947",
"ParentId": "250911",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "250947",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T15:23:59.867",
"Id": "250911",
"Score": "5",
"Tags": [
"python",
"programming-challenge",
"game",
"dice"
],
"Title": "NEA Computing Task 2 Dice Game"
}
|
250911
|
<p>I recently came across the need to allow consumers to prevent further execution of methods and I utilized an event driven system that allows the consumer to specify if the execution should cancel. I've tested it in a multi-threaded environment and everything is working as expected so as a simple solution it works as intended with no issues. However, I can't help but wonder where there are improvements that could be made as I've never dealt with event cancellations before.</p>
<h2>Event Arguments Definition</h2>
<pre><code>public class CustomEventArgs {
public bool Cancel { get; set; } = false;
}
</code></pre>
<p>I'm not sure that a default value for the <code>Cancel</code> property is a good idea here.</p>
<h2>Object Definition</h2>
<pre><code>public class MyCustomObject {
public void Count(int countTo) {
if (ShouldCount()) {
for (int i = 0; i < countTo;)
Console.WriteLine(++i);
} else
Console.WriteLine("Counting process was cancelled by the consumer.");
Console.WriteLine("The counting process has completed.");
}
public event EventHandler<CustomEventArgs> OnStarting;
private bool ShouldCount()
{
Console.WriteLine("The counting process is starting.");
CustomEventArgs args = new CustomEventArgs();
OnStarting?.Invoke(this, args);
return !args.Cancel;
}
}
</code></pre>
<p>I believe that <code>return !args.Cancel</code> is a little confusing to read as negative logic. Perhaps it should be <code>return args.Cancel</code> and the method should be renamed to something like <code>ShouldCancelCounting</code> and check for <code>if (!ShouldCancelCounting())</code> instead of <code>if (ShouldCount())</code>?</p>
<h2>Consumption</h2>
<pre><code>private static bool CancelEvent = false;
private static void RunTest() {
CancelEvent = false;
MyCustomObject obj = new MyCustomObject();
obj.OnStarting += CountStarting;
obj.Count(100);
CancelEvent = true;
MyCustomObject obj = new MyCustomObject();
obj.OnStarting += CountStarting;
obj.Count(100);
}
private static void CountStarting(object sender, CustomEventArgs e) {
e.Cancel = CancelEvent;
}
</code></pre>
<p>What are some areas that are harder to follow with this implementation? Is there anything confusing about it in any way? Is there any official Microsoft documentation on implementing event cancellations? What are some potential gotchas with my implementation?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T16:44:34.887",
"Id": "493711",
"Score": "2",
"body": "As you are a self-confessed rookie with cancellation, perhaps should rely upon what's already in the .NET Framework rather than rolling your own custom solution. See https://docs.microsoft.com/en-us/dotnet/standard/threading/cancellation-in-managed-threads,"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T16:45:55.580",
"Id": "493712",
"Score": "0",
"body": "Does this cide work as intended? Did you test it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T17:23:23.487",
"Id": "493717",
"Score": "1",
"body": "@RickDavin thank you for the reading material; I'm reading over it now. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T17:24:20.747",
"Id": "493718",
"Score": "0",
"body": "@Heslacher this code does in fact work as I intended it to. I tested it with nested multi-threading for added complexity."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T16:01:18.480",
"Id": "250913",
"Score": "1",
"Tags": [
"c#",
"event-handling"
],
"Title": "Basic Event Cancellation"
}
|
250913
|
<p>I've been playing around with the coroutines implementation in gcc 10.2.0 (Debian build) based on the sparse documentation at <a href="https://en.cppreference.com/w/cpp/language/coroutines" rel="nofollow noreferrer">https://en.cppreference.com/w/cpp/language/coroutines</a> . The target, for now, was to see how to use the functionality to enable creation of Python-style generator functions.</p>
<p>So here's what I have so far. I've tested valgrind cleanness of the code; and in addition to the included test cases demonstrating cancelling a pending generator coroutine, I've also tested the paths of normal exit of the coroutine and of unhandled exception propagating to the caller.</p>
<p>Note that with current gcc, you still need to add the <code>-fcoroutines</code> flag to compile this.</p>
<p>Main goal here is to get feedback on the parts specific to the coroutines functionality (and not so much the probably incomplete iterator implementation, where I just put in enough to satisfy the ranges library requirements).</p>
<p>(And yes, in projects using this code, as opposed to this quick experiment, I'd probably split the generic parts up into separate headers.)</p>
<pre><code>#include <coroutine>
#include <exception>
#include <iostream>
#include <ranges>
#include <tuple>
#include <utility>
// Class inspired by unique_ptr, whose main purpose is to have a destructor
// which calls destroy on the contained handle. Note that in order for this
// to work, there should be a suspend point in the promise type's
// final_suspend() hook; otherwise, on completion of the coroutine, this
// will be left with a dangling handle.
template <typename promise_type>
class unique_coroutine_handle {
private:
std::coroutine_handle<promise_type> m_handle;
public:
explicit unique_coroutine_handle(promise_type& promise)
{
m_handle = std::coroutine_handle<promise_type>::from_promise(promise);
}
explicit unique_coroutine_handle(std::coroutine_handle<promise_type> i_handle)
: m_handle(std::move(i_handle))
{
}
unique_coroutine_handle(const unique_coroutine_handle&) = delete;
unique_coroutine_handle(unique_coroutine_handle&& other)
: m_handle(std::move(other.m_handle))
{
other.m_handle = nullptr;
}
unique_coroutine_handle& operator=(const unique_coroutine_handle&) = delete;
unique_coroutine_handle& operator=(unique_coroutine_handle&& other)
{
if (m_handle)
m_handle.destroy();
m_handle = std::move(other.m_handle);
other.m_handle = nullptr;
}
~unique_coroutine_handle()
{
if (m_handle)
m_handle.destroy();
}
const std::coroutine_handle<promise_type>& get() const { return m_handle; }
};
template <typename T>
class generator {
public:
class promise_type {
public:
std::suspend_never initial_suspend() { return {}; };
// Note that in addition to the requirement imposed by the need not
// to leave the generator with a dangling unique_coroutine_handle,
// the suspend here is also important to ensure the promise object
// is not destroyed before iteration on the generator gets a chance
// to check for res==nullptr to see the terminating condition.
std::suspend_always final_suspend() { return {}; }
std::suspend_always yield_value(const T& val)
{
res = &val;
return {};
}
void return_void() {
res = nullptr;
}
void unhandled_exception()
{
eptr = std::current_exception();
res = nullptr;
}
generator get_return_object()
{
return { *this };
}
private:
const T* res;
std::exception_ptr eptr;
friend class ::generator<T>;
friend class ::generator<T>::iterator;
};
private:
promise_type& promise;
unique_coroutine_handle<promise_type> handle;
generator(promise_type& i_promise)
: promise { i_promise }
, handle { i_promise }
{
}
public:
generator() = default;
generator(generator&&) = default;
~generator() = default;
struct sentinel {
};
class iterator {
private:
generator* obj = nullptr;
iterator(generator* i_obj)
: obj(i_obj)
{
}
public:
iterator() = default;
iterator(const iterator&) = default;
iterator(iterator&&) = default;
iterator& operator=(const iterator&) = default;
iterator& operator=(iterator&&) = default;
~iterator() = default;
using value_type = const T;
using reference = const T&;
using difference_type = std::ptrdiff_t;
iterator& operator++()
{
obj->handle.get().resume();
if (obj->promise.eptr)
std::rethrow_exception(obj->promise.eptr);
return *this;
}
class postinc_result_proxy {
private:
T val_copy;
public:
const T& operator*() const { return val_copy; }
friend class ::generator<T>::iterator;
};
postinc_result_proxy operator++(int)
{
T val_copy = *(obj->promise.res);
++(*this);
return { std::move(val_copy) };
}
reference operator*() const {
return *(obj->promise.res);
}
bool operator==(sentinel) const {
return obj->promise.res == nullptr;
}
bool operator!=(sentinel) const {
return obj->promise.res != nullptr;
}
friend class ::generator<T>;
};
using const_iterator = iterator;
iterator begin() {
if (promise.eptr)
std::rethrow_exception(promise.eptr);
return { this };
}
sentinel end() { return {}; }
const_iterator begin() const {
if (promise.eptr)
std::rethrow_exception(promise.eptr);
return { this };
}
sentinel end() const { return {}; }
const_iterator cbegin() const {
if (promise.eptr)
std::rethrow_exception(promise.eptr);
return { this };
}
sentinel cend() const { return {}; }
};
// example usage below
struct verbose {
verbose() { std::cout << "verbose constructor called\n"; }
~verbose() { std::cout << "verbose destructor called\n"; }
};
generator<int> fibs()
{
verbose destruct_check;
int a = 0, b = 1;
while (true) {
co_yield b;
std::tie(a, b) = std::make_tuple(b, a + b);
}
}
generator<int> odd_fibs()
{
for (int n : fibs())
if (n % 2 != 0)
co_yield n;
}
int main()
{
{
auto f = fibs();
for (int n : f | std::views::take(10))
std::cout << n << '\n';
}
{
auto of = odd_fibs();
for (int n : of | std::views::take_while([](int n) { return n <= 500; }))
std::cout << n << '\n';
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T18:39:40.100",
"Id": "493720",
"Score": "0",
"body": "Do you know about the [CppCoro](https://github.com/lewissbaker/cppcoro#generatort) library? If you want to reimplement this yourself, then adding the reinvent-the-wheel tag to the question would be appropriate."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T18:45:53.897",
"Id": "493721",
"Score": "1",
"body": "No, I didn't know about it. (Though given the comments on the cppreference page I linked, I was well aware that this was very likely one of the intended use cases of the feature.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T04:08:49.193",
"Id": "493773",
"Score": "0",
"body": "I also reimplemented-the-wheel at https://github.com/Quuxplusone/coro — e.g. https://coro.godbolt.org/z/fx897q — if you want to compare and contrast. I'm unlikely to write a real answer here though, sorry."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T17:04:53.997",
"Id": "250918",
"Score": "3",
"Tags": [
"generator",
"c++20"
],
"Title": "Experimenting with C++20 coroutines to create Python-style generator functions"
}
|
250918
|
<p>I'm posting a solution for LeetCode's "Encode and Decode TinyURL". If you'd like to review, please do. Thank you!</p>
<h3><a href="https://leetcode.com/problems/encode-and-decode-tinyurl/" rel="nofollow noreferrer">Problem</a></h3>
<p>TinyURL is a URL shortening service where you enter a URL such as <code>https://leetcode.com/problems/design-tinyurl</code> and it returns a short URL such as <code>http://tinyurl.com/4e9iAk</code>.</p>
<p>Design the <code>encode</code> and <code>decode</code> methods for the TinyURL service. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.</p>
<h3>Code</h3>
<pre><code>
// The following block might slightly improve the execution time;
// Can be removed;
static const auto __optimize__ = []() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cout.tie(nullptr);
return 0;
}();
// Most of headers are already included;
// Can be removed;
#include <iostream>
#include <cstdint>
#include <string>
#include <unordered_map>
#include <utility>
#include <random>
static const struct Solution {
public:
const std::string encode(
const std::string long_url
) {
std::string tiny_encoded;
if (!encoded_url.count(long_url)) {
for (auto index = 0; index < kTinySize; ++index) {
tiny_encoded.push_back(char_pool[rand_generator() % std::size(char_pool)]);
}
encoded_url.insert(std::pair<std::string, std::string>(long_url, tiny_encoded));
decoded_url.insert(std::pair<std::string, std::string>(tiny_encoded, long_url));
} else {
tiny_encoded = encoded_url[long_url];
}
return kDomain + tiny_encoded;
}
const std::string decode(
const std::string short_url
) {
return std::size(short_url) != kDomainTinySize ||
!decoded_url.count(short_url.substr(kDomainSize, kTinySize)) ? "" :
decoded_url[short_url.substr(kDomainSize, kTinySize)];
}
private:
static constexpr char kDomain[] = "http://tinyurl.com/";
static constexpr unsigned int kTinySize = 6;
static constexpr unsigned int kDomainSize = std::size(kDomain) - 1;
static constexpr auto kDomainTinySize = kDomainSize + kTinySize;
static constexpr char char_pool[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
std::unordered_map<std::string, std::string> encoded_url;
std::unordered_map<std::string, std::string> decoded_url;
std::random_device rand_generator;
};
// Your Solution object will be instantiated and called as such:
// Solution solution;
// solution.decode(solution.encode(url));
</code></pre>
|
[] |
[
{
"body": "<p>You are doing the lookup twice.</p>\n<pre><code> if (!encoded_url.count(long_url)) {\n\n .. stuff\n\n } else {\n tiny_encoded = encoded_url[long_url];\n }\n</code></pre>\n<p>I know that it is <code>O(1)</code> for the lookup. But there is a real constant inside that. Avoid it if you can.</p>\n<p>Use <code>find()</code>. Then if it is there you can simply use it.</p>\n<pre><code> auto find = encoded_url.find(long_url);\n if (find == encoded_url.end()) {\n\n .. stuff\n\n } else {\n tiny_encoded = find->second;\n }\n</code></pre>\n<hr />\n<p>This is great if you want random URL that are hard to guess.</p>\n<pre><code> for (auto index = 0; index < kTinySize; ++index) {\n tiny_encoded.push_back(char_pool[rand_generator() % std::size(char_pool)]);\n }\n</code></pre>\n<p>But is that a requirement of the puzzle. Seems (not sure how expensive the generating the random number is) like this is very expensive way of generating a name.</p>\n<p>There is also a chance for a clash. If you are using randomly generated values append a timestamp on the end to avoid a clash.</p>\n<hr />\n<p>Personally I don't like having to specify a type. But if you are goint to do it use the type of the method rather than being this specific:</p>\n<pre><code> encoded_url.insert(std::pair<std::string, std::string>(long_url, tiny_encoded));\n\n\n // Top of the class.\n using Map = std::unordered_map<std::string, std::string>;\n using MapValue = Map::value_type;\n\n // In the code.\n encoded_url.insert(MapValue(long_url, tiny_encoded));\n</code></pre>\n<p>But I think I would simply have used <code>emplace()</code>.</p>\n<pre><code> encoded_url.emplace(long_url, tiny_encoded);\n</code></pre>\n<hr />\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T19:22:08.483",
"Id": "250922",
"ParentId": "250921",
"Score": "4"
}
},
{
"body": "<p>I agree with everything in Martin York's answer. Just one thing: you can avoid having two <code>unordered_map</code>s if you don't create a purely random URL, but instead create one by hashing the original URL. This way, you will always create the same tiny URL for the same long URL, so you don't need <code>encoded_url</code> anymore. Of course, you would still need to handle duplicates in <a href=\"https://en.wikipedia.org/wiki/Hash_table#Collision_resolution\" rel=\"nofollow noreferrer\">some way</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T20:03:05.583",
"Id": "250928",
"ParentId": "250921",
"Score": "3"
}
},
{
"body": "<p>Others have made good points, but I'll add in a stylistic quibble.</p>\n<pre><code>return std::size(short_url) != kDomainTinySize ||\n !decoded_url.count(short_url.substr(kDomainSize, kTinySize)) ? "" :\n decoded_url[short_url.substr(kDomainSize, kTinySize)];\n</code></pre>\n<p>is a heck of a one-liner. The ternary operator is fun but speaking as someone who has absolutely abused it, if you can't fit it comfortably on a line or two then you're going to hate yourself when you go back to read that in 6 months. Also, when you see that many <code>!</code>s running around it's usually time to bust out De Morgan's laws. And it would let us put the uninteresting path further out of sight. So, if we really want the ternary...</p>\n<pre><code>return std::size(short_url) == kDomainTinySize &&\n decoded_url.count(short_url.substr(kDomainSize, kTinySize)) ?\n decoded_url[short_url.substr(kDomainSize, kTinySize)] :\n "";\n</code></pre>\n<p>or if I was feeling a bit audacious maybe even</p>\n<pre><code>return std::size(short_url) == kDomainTinySize \n && decoded_url.count(short_url.substr(kDomainSize, kTinySize))\n ? decoded_url[short_url.substr(kDomainSize, kTinySize)]\n : "";\n</code></pre>\n<p>I lied, second point: I would claim that idiomatic C++ should also rely on implicit type conversion as little as possible, which is to say, change that condition to <code>decoded_url.count(...) != 0</code>. It is more verbose, but it's also immediately clearer to the reader what's meant. Reasonable people could disagree though.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T16:13:38.680",
"Id": "493953",
"Score": "2",
"body": "I would even go so far as to say that you should move the logic of the condition into a named function. `return isValidTinyUrl(short) ? decodeUrl(short) : \"\";` One line ternary operators are fine as long as it is easy to understand the intent."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T22:02:54.463",
"Id": "250935",
"ParentId": "250921",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "250922",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T18:59:22.650",
"Id": "250921",
"Score": "3",
"Tags": [
"c++",
"beginner",
"algorithm",
"programming-challenge",
"c++17"
],
"Title": "LeetCode 535: Encode and Decode TinyURL"
}
|
250921
|
<p>I have a young friend of mine who is starting to learn Python in school and asked me to give him a little assignment. I am in no way a teacher nor a Python expert, but I accepted.</p>
<p>At first I thought it would be fun to start with a bit of parsing for the operation's input, like:</p>
<pre><code>Enter your operation : 3+3
</code></pre>
<p>But it seemed a bit overwhelming for him so we agreed to separate it in three parts (first number, operand and second number).</p>
<p>I did a little correction but I find it clumsy and the point of the exercise is to show him some good practices.</p>
<p>So here is my code:</p>
<pre class="lang-py prettyprint-override"><code>calculate = True
while calculate:
try:
number1 = float(input("Enter the first number : "))
except ValueError:
print("Incorrect value")
exit()
symbol = input("Enter the operation symbol (+,-,/,*,%) : ")
try:
number2 = float(input("Enter the second number : "))
except ValueError:
print("Incorrect value")
exit()
operande = ["+", "-", "*", "/", "%"]
resSentence = "Result of operation \"{} {} {}\" is :".format(number1, symbol, number2)
if symbol not in operande:
print("Incorrect symbol")
elif symbol == "+":
print(resSentence, number1 + number2)
elif symbol == "-":
print(resSentence, number1 - number2)
elif symbol == "*":
print(resSentence, number1 * number2)
elif symbol == "/":
print(resSentence, number1 / number2)
elif symbol == "%":
print(resSentence, number1 % number2)
restart = input("Do you want to do another calcul (Y/n) ? ")
while restart.lower() != "y" and restart.lower() != "n":
print(restart.lower(), restart.lower(), restart.lower()=="n")
restart = input("Please, enter \"y\" to continue or \"n\" to exit the program : ")
if restart.lower() == "n":
calculate = False
</code></pre>
<p>I would have wanted to do a loop when <code>number1</code> or <code>number2</code> is not a valid <code>float</code> until the user enter a valid value, but I did not found a clean way to do it. I would gladly accept advices about this (even though I know this is not a question for this Stack Exchange, a good Pythonic way for doing this would be cool :) ).</p>
|
[] |
[
{
"body": "<p>This is an alternative to your code, it is a bit more complex but it is also more readable. I did manage to do the loop thing but it is kind of hard to follow. Sorry.</p>\n<pre class=\"lang-py prettyprint-override\"><code>running = True\n# Break Things up into functions each function does one single thing\n\ndef calculate(inputOne, operand, inputTwo):\n """\n Calculates inputOne operand and inputTwo\n """\n\n if operand == "+":\n return inputOne + inputTwo\n elif operand == "-":\n return inputOne - inputTwo\n elif operand == "*":\n return inputOne * inputTwo\n elif operand == "/":\n return inputOne / inputTwo\n elif operand == "%":\n return inputOne % inputTwo\n\ndef askInput():\n """\n Asks for a number until a number is given checks if each one is valid\n """\n\n isValid = [False, False, False] # none of the numbers are validated yet\n number1, symbol, number2 = ["", "", ""]\n \n # Here is a good implementation of the loop, it is kind of complex though\n while True:\n try:\n if not isValid[0]: # Asks for number1 if it is not valid\n number1 = int(input("Enter the first number : "))\n isValid[0] = True\n\n if not isValid[1]: # This is added functionality because there was a loophole in your program\n symbol = input("Enter the operation symbol (+,-,/,*,%) : ") # use tuples whenever possible\n supportedOperands = ("+", "-", "/", "*", "%")\n\n if symbol not in supportedOperands:\n raise ValueError\n\n isValid[1] = True\n\n if not isValid[2]: # Asks for number2 if it is not valid\n number2 = int(input("Enter the second number : "))\n isValid[2] = True\n break\n \n except ValueError:\n continue # this just restarts the whole thing\n \n return number1, symbol, number2\n\n\n\ndef continueApp():\n """\n Checks if the input to restart is valid\n """\n restart = input("Do You want to do another calculation (Y/n) ? ").lower()\n\n while True:\n if restart == "y":\n return True\n elif restart == "n":\n return False\n else:\n restart = input("Please, enter \\"y\\" to continue or \\"n\\" to exit the program : ").lower()\n\nwhile running:\n\n numberOne, operand, numberTwo = askInput()\n answer = calculate(numberOne, operand, numberTwo)\n resSentence = f"Result of operation {numberOne} {operand} {numberTwo} is : {answer}"\n print(resSentence)\n\n if continueApp():\n pass\n else:\n running = False\nexit()\n\n\n</code></pre>\n<h1>Tips:</h1>\n<ul>\n<li><h2>Break Things Up into functions:</h2>\n</li>\n</ul>\n<p>Functions are just containers for code that can be executed, functions <em>MUST</em> do <em>ONE</em> and only <em>ONE</em> thing more on functions <a href=\"https://www.w3schools.com/python/python_functions.asp\" rel=\"nofollow noreferrer\">here</a>.</p>\n<ul>\n<li><h2>Please Try to comment on your code, it makes it easier to read and edit.</h2>\n</li>\n</ul>\n<p>This function</p>\n<pre><code>def calc():\n x = 1\n y = 12\n return (((x+y)/x)**y)+(3*x+4*y) # Please don't write like this in any case\n</code></pre>\n<p>would be much better with an explanation or what is going on</p>\n<pre><code>def calc():\n """\n Accepts: Nothing\n Does: Adds X and Y, then divides it by X to the power of Y\n then it adds it to X multiplied by three and 4 multiplied by Y\n Returns: integer (the result of Does) ^^^^^\n """\n x = 1\n y = 12\n return ((x+y)/x**y)+(3*x+4*y) # Again, please don't write code like this\n</code></pre>\n<ul>\n<li><h2>Use f strings (this requires python 3.6 and above)</h2>\n</li>\n</ul>\n<p>f strings are used like this</p>\n<pre><code>value = "12"\nprint(f"Number {value} is an example of an f string") \n\n# Versus\n\nprint("Number {} is an example of an f string".format(value))\n</code></pre>\n<ul>\n<li><h2>Try to space out your code</h2>\n</li>\n</ul>\n<p>Trust me, this makes your code easier to read and understand.</p>\n<pre><code>def calc():\n """\n Accepts: Nothing\n Does: Adds X and Y, then divides it by X to the power of Y\n then it adds it to X multiplied by three and 4 multiplied by Y\n Returns: integer (the result of Does) ^^^^^\n """\n x = 1\n y = 12\n ans = (x + y) / (x ** y)\n ans += (3 * x) + (4 * y) # just adds ans to the right side of the operator\n return ans\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T00:37:21.407",
"Id": "493762",
"Score": "1",
"body": "The `operand` could be the key of a dictionary, that leads to \\$O(1)\\$ search time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T00:49:15.047",
"Id": "493763",
"Score": "0",
"body": "Well I tried to avoid functions since he is a new learner and the exercise should be more oriented about basics programming skills (conditions, loop...) but tyvm"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T00:54:19.980",
"Id": "493764",
"Score": "0",
"body": "Though I like your implementation, I would like to go step by step and avoid using functions since he is young and already have difficulties following a simple script"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T06:43:32.433",
"Id": "493785",
"Score": "0",
"body": "This answer doesn't seem to be focused on code review but rather to offer an alternative solution. Would you mind explaining (edit your answer) how is this any better from the OP's code? What did you improve?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T15:04:54.313",
"Id": "493822",
"Score": "0",
"body": "Yeah, sorry, I will fix that."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T21:54:02.273",
"Id": "250934",
"ParentId": "250924",
"Score": "5"
}
},
{
"body": "<h1>Use more functions</h1>\n<p>You have a function <code>calculate()</code>, but if you see it does much more than just calculate, this makes your code look unreasonably clunky. But there is a very simply solution, use more functions. What if your main-loop could look like</p>\n<pre class=\"lang-py prettyprint-override\"><code>while True:\n number1,number2,operand = take_input()\n result = calculate(number1,number2,operand)\n print(f"Answer : {numebr1} {operand} {number2} = {result}")\n if input("Do you want to play again? (y/n): ").lower() == 'n':\n break \n</code></pre>\n<p>This makes it easier to maintain your program.</p>\n<h1><code>continue</code> when there is an error</h1>\n<pre class=\"lang-py prettyprint-override\"><code>try:\n number1 = float(input("Enter the first number : "))\nexcept ValueError:\n print("Incorrect value")\n exit()\n</code></pre>\n<p>Ask yourself, why would a program terminate if the user enters invalid input? <strong>Give him a another chance xD</strong></p>\n<h1>Maintain consistent indentation</h1>\n<pre class=\"lang-py prettyprint-override\"><code>try:\n number2 = float(input("Enter the second number : "))\nexcept ValueError:\n print("Incorrect value")\n exit()\n</code></pre>\n<p>Try to maintain consistent indentation, since you have used <code>4</code> spaces earlier, there is no good reason to use <code>8</code> later, it might just confuse people who read the code later.</p>\n<h1>Code logic 1</h1>\n<p>Let's consider this sample input</p>\n<pre><code>Enter the first number : 1\nEnter the operation symbol (+,-,/,*,%) : I like python\nEnter the second number : 2\nIncorrect symbol\n</code></pre>\n<p>Clearly, the <code>symbol</code> is wrong. Why did I have to enter the second number, just to find out I made a mistake while entering the <code>symbol</code>? It should've told me right away that my symbol was incorrect, so I could've corrected it.</p>\n<p>Just move the <code>if symbol not in operands</code> statement so it sits right next to the input.</p>\n<h1><code>eval</code></h1>\n<p><a href=\"https://www.w3schools.com/python/ref_func_eval.asp#:%7E:text=The%20eval()%20function%20evaluates,statement%2C%20it%20will%20be%20executed.\" rel=\"nofollow noreferrer\"><strong>Eval in Python</strong></a> <br></p>\n<p>This would be the biggest improvement in your program, since it converts about 10-15 lines of code, into one.</p>\n<blockquote>\n<p>The <code>eval()</code> function evaluates the specified expression, if the\nexpression is a legal Python statement, it will be executed.</p>\n</blockquote>\n<p>That sounds familiar, aren't we basically evaluating simple expressions?</p>\n<p>Using <code>eval</code>, your calculation part would look like</p>\n<pre class=\"lang-py prettyprint-override\"><code>result = eval(f"{number1}{operand}{number2}")\n</code></pre>\n<p>Example, <code>number1 = 5,number2 = 10, operand = '+'</code></p>\n<p>This is what is basically happening</p>\n<pre class=\"lang-py prettyprint-override\"><code>result = eval("5+10")\n</code></pre>\n<h1>Final</h1>\n<p>Here is the code with the improvements</p>\n<pre class=\"lang-py prettyprint-override\"><code>def take_input():\n err_msg = "Invalid input"\n operands = ['+','-','*','/','%']\n try:\n num1 = float(input("Enter number 1: "))\n except Exception:\n print(err_msg)\n return take_input()\n try:\n num2 = float(input("Enter number 2: "))\n except Exception:\n print(err_msg)\n return take_input()\n\n print("Operands: " + ', '.join(x for x in operands))\n try:\n operand = input("Enter operand: ")\n except Exception:\n print(err_msg)\n return take_input()\n\n if operand not in operands:\n print(err_msg)\n return take_input()\n\n return num1,num2,operand\n\ndef calculate(num1,num2,operand):\n return eval(f"{num1}{operand}{num2}")\n\n\ndef mainloop():\n while True:\n num1,num2,operand = take_input()\n result = calculate(num1,num2,operand)\n print(f"Answer: {result}")\n if input("Do you want to play again? (y/n): ").lower() == 'n':\n break\n\nmainloop()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T10:49:40.550",
"Id": "493803",
"Score": "0",
"body": "I really like the improvements you proposed and how you explained them to me :) As a side question do you think this would be understandable to my young friend (14 y/o) who just started python and only saw `if` statement in class (he is motivated though since he himself came to me to learn more about coding and so far he seems to really enjoy it). I guess the harder will be to not give him the code but to let him do some search and do trial and error by himself ^^. I will wait untill tonight (I am in France) before accepting an answer but so far, I will accept yours :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T10:59:48.300",
"Id": "493805",
"Score": "2",
"body": "Well I'll do my best to explain him as clearly as possible and to let him search by himself :) Wow I would really not have guessed, you have a bright future ahead of you"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T11:05:32.443",
"Id": "493806",
"Score": "1",
"body": "@L.Faros There are plenty of resources to learn python online. [This](https://programmingwithmosh.com/python/new-python-tutorial/) one was extremely useful to me"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T18:34:19.867",
"Id": "493834",
"Score": "1",
"body": "@L.Faros the final code could be thought of as `If` statements. Basically, all `Try/Except` is doing is saying (using the first one as an example) \"If setting `num1` to a float results in a Value error, print the error message and re-run `take_input`. If there is no error setting `num1` to a float, then do that and continue to the next line after `except`\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T18:37:16.543",
"Id": "493836",
"Score": "0",
"body": "Something I noticed, if the users second input results in an error, they have to restart and put in number 1 again. Perhaps that's by design and is intended, but one alternate would be to just ask for the second number again (via whatever method you like). Same with operand. (Though this is a simple program so it's probably overkill. Just something for OP to consider trying)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T19:49:36.167",
"Id": "493849",
"Score": "0",
"body": "My mistake; there is validation being done - it's just doing it in a pretty bad way. 1. You recurse instead of loop. You really shouldn't recurse. 2. Your code doesn't even do what you intended - retries don't return any values; you discard the return values. That aside, `eval` still isn't the right tool, here; given that your operators are well-constrained and well-understood you should not need to force the interpreter to parse anything."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T19:51:41.993",
"Id": "493852",
"Score": "0",
"body": "It's not a performance problem. It's just literally the wrong thing to do, and you'll blow your stack if the user enters enough bad data. Subsequent runs of the function don't depend on previous runs of the function; this is not a proper application of recursion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T19:54:00.157",
"Id": "493855",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/115350/discussion-between-reinderien-and-aryan-parekh)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-06T07:27:14.120",
"Id": "495649",
"Score": "0",
"body": "Although using _eval_ is fine in such educational cases, I’d like to add that using _eval_ without checking/restricting the string that is eval’ed is a very serious security concern."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-06T07:40:00.093",
"Id": "495652",
"Score": "0",
"body": "@agtoever He's right actually, it can be dangerous but it works in this situation."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T04:59:17.090",
"Id": "250941",
"ParentId": "250924",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "250941",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T19:36:32.717",
"Id": "250924",
"Score": "10",
"Tags": [
"python",
"python-3.x",
"calculator"
],
"Title": "Basic python calculator"
}
|
250924
|
<p>I'm currently making a game using <strong>C++</strong>. I eventually needed a logger, but I wasn't satisfied with any of the existing solutions. After a while, I wrote my own header called <strong><em>log.h</em>:</strong></p>
<pre><code>
#include <iostream>
#include <iomanip>
#include <string>
#include <ctime>
#include <fstream>
#include <sstream>
class Logger {
private:
std::string logFileName = "log.txt";
bool print = true;
bool save = true;
void log(std::string s, std::string i) {
time_t cuT;
struct tm *loT;
time(&cuT);
loT = localtime(&cuT);
std::stringstream ss;
ss << std::setw(2) << std::setfill('0') << loT->tm_hour << ':';
ss << std::setw(2) << std::setfill('0') << loT->tm_min << ':';
ss << std::setw(2) << std::setfill('0') << loT->tm_sec;
ss << i << s << "\n";
if(save) {
std::ofstream of;
of.open(logFileName, std::ios_base::app | std::ios::out);
of << ss.rdbuf();
}
if(print) {
std::cout << ss.str();
}
}
public:
void configure(std::string logFileName_, bool print_, bool save_) {
this->print = print_;
this->save = save_;
this->logFileName = logFileName_;
}
void note(std::string s) {
log(s, " NOTE: ");
}
void error(std::string s) {
log(s, " ERROR: ");
}
void warn(std::string s) {
log(s, " WARNING: ");
}
};
</code></pre>
<p>My library can print the current time as well as other information to the console and save this data into a file. But I did a couple of benchmarks and it turns out that my logging program is a lot slower compared to the normal <strong>std::cout</strong>.</p>
<p>Since speed is crucial for games, I wanted to ask whether there are ways to optimize my program or, if necessary, to improve it.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T19:53:26.660",
"Id": "493725",
"Score": "0",
"body": "By the way, sorry if my question isn't perfect. I'm completely new to StackExchange. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T20:06:10.500",
"Id": "493728",
"Score": "2",
"body": "Can you describe what was unsatisfactory with the other solutions, and what requirements you have set for your logger?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T20:19:08.410",
"Id": "493729",
"Score": "0",
"body": "Well actually it was the learning experience as well as the complexity of other solutions, I would never understand something fully until I write it myself. And to be honest: **it's also quite fun to code**. I haven't actually set any goals, I'm just currently looking for optimizations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T20:35:44.963",
"Id": "493730",
"Score": "0",
"body": "Have a look at https://github.com/emilk/loguru"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T20:38:33.503",
"Id": "493731",
"Score": "2",
"body": "One of the biggest things about a logging system is being able to enable/disable or set logging level (so less import stuff is not logged). I don't see any of that. Also the concept of log sinks does not seem to exist so you can either log to cout or a file. what about syslog?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T20:50:04.380",
"Id": "493732",
"Score": "0",
"body": "I will look at **loguru**, thanks. But as I said, I made this library for myself. I only added the features that I would likely need. And by the way, I couldn't find anything about \"Log-Sinks\". The only thing I saw on google were literally \"log sinks\". Anyway, I like your suggestions like the logging level. Thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T21:17:54.563",
"Id": "493736",
"Score": "2",
"body": "Some minor suggestions - 1) if the strings may be heavy, better pass them by const reference `const std::string&` to avoid copy 2) add the constructor, which call `configure` function"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T22:22:27.073",
"Id": "493747",
"Score": "1",
"body": "Sinks are objects that encapsulate some behavior for handling a logged message. The logger itself doesn't have any notion of whether the message is going to stdout, a file, a database, or whatever, it just has a bunch of sinks that it hands the messages off to. The sinks do the work of actually outputting the message somewhere."
}
] |
[
{
"body": "<p>Some things to note;</p>\n<ol>\n<li>When doing time related things in C++, use <code>std::chrono</code>, not <code>clock()</code>.</li>\n<li>Your log will not work if it's used in multiple files. Instead of being in a .h file, put the definition of the logger in a cpp file and build both together.</li>\n<li>Use include guards for header files</li>\n</ol>\n<pre><code> #ifndef LOG_H\n #define LOG_H\n\n // Code\n\n #endif\n</code></pre>\n<ol start=\"4\">\n<li>Define constructors and use them properly and get rid of configure.</li>\n</ol>\n<pre><code> Log(std::string fileName, bool printToConsole, bool saveToFile) :\n logFileName(fileName),\n print(printToConsole),\n save(saveToFile)\n {\n }\n</code></pre>\n<ol start=\"5\">\n<li>Do not use underscores for naming things. General rules for c++ are class names are PascalCase and functions are camelCase.</li>\n<li>std::cout is slow, consider using sprintf to make it faster.</li>\n<li>Don't write to a file every time you call log. Opening files and writing to them is slow. Consider writing to the file on a timestamp or aggregating a few logs before writing them.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T22:17:26.513",
"Id": "493744",
"Score": "2",
"body": "To build on #7, try storing the logs in some sort of buffer. You could flush the buffer after a certain size, and this is common in loggers, but it's worth noting that if your program crashes, anything in the buffer disappears. Most logging systems also flush the buffer after a certain time interval too, just to minimize the likelihood of that happening to any particular message. Doing that though will probably involve adding another thread to run the pump, but it would be a good exercise."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T21:49:56.547",
"Id": "250933",
"ParentId": "250926",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "250933",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T19:52:08.113",
"Id": "250926",
"Score": "4",
"Tags": [
"c++",
"c",
"logging"
],
"Title": "Simple Logger in C++"
}
|
250926
|
<p>I am trying to recode some c functions myself.
This is an my implementation of <strong>realloc</strong> function, any updates or suggestion about how to improve it are welcomed.</p>
<pre><code>void *ft_realloc(void *old_ptr, size_t old_size, size_t size) {
void *new_ptr;
if (size == 0 && old_ptr != NULL)
{
free (old_ptr);
return (NULL);
}
else if (old_ptr == NULL)
{
if (!(old_ptr = malloc (size)))
return (NULL);
ft_memset(old_ptr, 0, size);
return (old_ptr);
}
else if (size >= old_size) {
if (!(new_ptr = malloc (size)))
return (NULL);
ft_memset(new_ptr, 0, size);
ft_strncpy (new_ptr, old_ptr, old_size);
free (old_ptr);
return (new_ptr);
}
else if (size < old_size)
{
if (!(new_ptr = malloc(size)))
return (NULL);
ft_memset(new_ptr, 0, size);
ft_strncpy (new_ptr, old_ptr, size);
free (old_ptr);
return (new_ptr);
}
return (NULL);
}
</code></pre>
<p><code>ft_memset</code> and <code>ft_strncpy</code> are just my implementation of <code>memset</code> and <code>strncpy</code> they behave the same way!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T22:05:25.127",
"Id": "493740",
"Score": "5",
"body": "Welcome to the Code Review site. There isn't enough here to review. Rather than explaining what` ft_memset()` and `ft_strncpy()` are they should be included in the question. The rest of `ft_realloc()` depends a lot on the code using it so that should be included in the question as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T04:04:55.673",
"Id": "493893",
"Score": "3",
"body": "Welcome to CodeReview@SE. (`ft_strncpy` reads *erroneous* - think about embedded NULs.) `any [suggestion is] welcome` Tag [tag:reinventing-the-wheel]. Don't write, never present uncommented code. Reduce code multiplication."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T07:14:16.263",
"Id": "494006",
"Score": "0",
"body": "@greybeard , Hello, you are write, i will try to comment my code next time. Thank you for the review."
}
] |
[
{
"body": "<pre><code>#include <stddef.h>\n#include <stdlib.h>\n\nvoid *ft_realloc(void *old_ptr, size_t old_size, size_t size) {\n if (size == 0 && old_ptr != NULL)\n {\n free (old_ptr);\n }\n else if (old_ptr == NULL)\n {\n if (old_ptr = malloc(size))\n {\n ft_memset(old_ptr, 0, size);\n return (old_ptr);\n }\n }\n else\n {\n void *new_ptr;\n if (new_ptr = malloc(size))\n {\n ft_memset(new_ptr, 0, size);\n \n if (size >= old_size)\n ft_strncpy (new_ptr, old_ptr, old_size);\n else\n ft_strncpy (new_ptr, old_ptr, size);\n \n free (old_ptr);\n return (new_ptr);\n }\n }\n return (NULL);\n}\n</code></pre>\n<p>My insightful observation: OP's code has redundancies.\nMy answer: I removed some redundancies, which makes the code possible faster and easier to maintain.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T22:14:34.640",
"Id": "493743",
"Score": "7",
"body": "Welcome to Code Review! This answer doesn't really offer much for the OP. Please (re-) read [The help center page _How do I write a good answer?_](https://codereview.stackexchange.com/help/how-to-answer). Note it states: \"_Every answer must make at least one **insightful observation** about the code in the question. Answers that merely provide an alternate solution with no explanation or justification do not constitute valid Code Review answers and may be deleted._\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T08:09:40.273",
"Id": "493789",
"Score": "0",
"body": "Thank you for your time, indeed i had some redundancies to eliminate, thank you very much !"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-25T15:01:27.943",
"Id": "494252",
"Score": "0",
"body": "`&& old_ptr != NULL` not needed. Just free when `size == 0`. `free(NULL)` is OK."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-25T15:05:01.103",
"Id": "494253",
"Score": "0",
"body": "`ft_strncpy` is very likely wrong - there is nothing in `realloc()` involving _strings_. `ft_memcpy()` would make more sense."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-25T15:07:11.050",
"Id": "494254",
"Score": "0",
"body": "`ft_memset(new_ptr, 0, size);` is wasteful. Better only zero memory beyond the former size - if at all as `realloc()` does not do that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-25T15:16:15.717",
"Id": "494255",
"Score": "0",
"body": "An alternative to `if (old_ptr = malloc(size)) { ft_memset(old_ptr, 0, size); return (old_ptr); }` would be `return calloc(1, size);`"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T21:23:15.277",
"Id": "250932",
"ParentId": "250929",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T20:39:07.667",
"Id": "250929",
"Score": "1",
"Tags": [
"c"
],
"Title": "this is my realloc version, is it good ? any suggestion are welcomed"
}
|
250929
|
<p>I would like to create a small virtual PLC application, where the user may choose from a variety of logic gates and put them together to form a boolean program. I just have written the logic gates, which all work as intended. May you give me some tips in regarding programming style? My class <strong>Gate</strong> uses a <em>static int</em> variable named <em>gateValuesForced</em>. This variable shall be an indicator for the user that any of the <em>Gates</em> has used method <em>Gate.force()</em> and not has used <em>Gate.unforce()</em> in sucession. Did I've implemented this in the right way? Also in regard to my method <em>Gate.finalize()</em>.</p>
<p><strong>Package operatoren - Class Gate</strong></p>
<pre><code>package operatoren;
public final class Gate{
private boolean value = false, force = false, forceValue = true;
private static int gateValuesForced = 0;
public final void setValue(boolean value) {
this.value = value;
}
public final void flipValue() {
if(value) value = false;
else value = true;
}
public final void setForceValue(boolean forceValue) {
this.forceValue = forceValue;
}
public final void flipForceValue() {
if(forceValue) forceValue = false;
else forceValue = true;
}
public final boolean force() {
if(!force) {
force = true;
gateValuesForced++;
return true;
}
else {
return false;
}
}
public final boolean unforce() {
if(force) {
force = false;
gateValuesForced--;
return true;
}
else {
return false;
}
}
public final boolean getValue() {
if(force) return forceValue;
else return value;
}
public final boolean getForceValue() {
return forceValue;
}
public final boolean isForced() {
return force;
}
public final static int gateValuesForced() {
return gateValuesForced;
}
protected void finalize() {
unforce();
}
public Gate() {
}
}
</code></pre>
<p><strong>Package operatoren - Class LogicGate</strong></p>
<pre><code>package operatoren;
import java.util.ArrayList;
import java.util.List;
public abstract class LogicGate {
public List<Gate> input = new ArrayList<Gate>();
public Gate output = new Gate();
public abstract boolean calc();
public LogicGate(int inputs) {
for(int i = 0; i < inputs; i++) {
input.add(new Gate());
}
}
}
</code></pre>
<p><strong>Package operatoren - Class AND</strong></p>
<pre><code>package operatoren;
import java.util.NoSuchElementException;
public class AND extends LogicGate{
public boolean calc() {
if(this.input.size() > 1) {
for(int i = 1; i < this.input.size(); i++) {
if(this.input.get(i-1).getValue() && this.input.get(i).getValue()) {
this.output.setValue(true);
}
else {
this.output.setValue(false);
break;
}
}
return this.output.getValue();
}
else {
throw new NoSuchElementException("AND-Gate has less than 2 inputs.");
}
}
public AND() {
super(2);
}
}
</code></pre>
<p><strong>Package test - Class Test</strong></p>
<pre><code>package test;
import operatoren.*;
public class Test {
public static void testLogicGate(LogicGate logicGate) {
System.out.println(" ------- " + logicGate.toString() + " ------- ");
boolean intToBoolean = false;
for(int i = 0; i < (1 << logicGate.input.size()); i++) {
for(int j = 0; j < logicGate.input.size(); j++) {
if((i & (1 << j)) > 0) {
intToBoolean = true;
}
else {
intToBoolean = false;
}
logicGate.input.get(j).setValue(intToBoolean);
System.out.println("logicGate.input.get(" + j + ").getValue() = " + logicGate.input.get(j).getValue());
}
logicGate.calc();
System.out.println("logicGate.output.getValue() = " + logicGate.output.getValue() + "\n");
}
if(Gate.gateValuesForced() != 0) {
System.out.println("Gate.gateValuesForced() = " + Gate.gateValuesForced());
}
}
public static void main(String[] args) {
AND testAND = new AND();
/* uncomment one or more of following lines for testing */
//testAND.input.add(new Gate());
//testAND.input.get(0).setForceValue(false);
//testAND.input.get(0).force();
testLogicGate(testAND);
}
}
</code></pre>
<p>You may uncomment one or more of those comments to view another test situation.</p>
|
[] |
[
{
"body": "<p>Few suggestions:</p>\n<ul>\n<li>The class <code>Gate</code> is <code>final</code>, therefore all its methods are implicitly <code>final</code>, no need to specify the modifier on each method. <a href=\"https://docs.oracle.com/javase/tutorial/java/IandI/final.html#:%7E:text=You%20can%20declare%20some%20or,of%20its%20methods%20are%20final%20.\" rel=\"nofollow noreferrer\">Docs</a>.</li>\n<li>The name <code>Gate</code> is a bit confusing because that class represents an input or output.</li>\n<li><strong>One variable per declaration</strong>: <code>private boolean value = false, force = false, forceValue = true;</code> is <a href=\"https://google.github.io/styleguide/javaguide.html#s4.8.2-variable-declarations\" rel=\"nofollow noreferrer\">not considered</a> good practice.</li>\n<li>You can refer to <a href=\"https://google.github.io/styleguide/javaguide.html\" rel=\"nofollow noreferrer\">Google Java Style Guide</a> for additional style improvements</li>\n<li>The method <code>Gate#flipValue</code>:\n<pre><code>public final void flipValue() {\n if(value) value = false;\n else value = true;\n}\n</code></pre>\nCan be simplified to:\n<pre><code>public final void flipValue() {\n value = !value;\n}\n</code></pre>\n</li>\n<li>Regarding the method <code>AND#calc</code>:\n<pre><code>public boolean calc() {\n if(this.input.size() > 1) {\n for(int i = 1; i < this.input.size(); i++) {\n if(this.input.get(i-1).getValue() && this.input.get(i).getValue()) {\n this.output.setValue(true);\n }\n else {\n this.output.setValue(false);\n break;\n }\n }\n return this.output.getValue();\n }\n else {\n throw new NoSuchElementException("AND-Gate has less than 2 inputs.");\n }\n} \n</code></pre>\nFirst, the output of this method is not used in other parts of your code so it can be <code>void</code>. Second, it's enough to find one input==false to set the output to false, therefore the logic can be simplified. Third,\nchecking the input size in this method is too late, it should be done in the constructor.</li>\n<li>The constructor of the class <code>AND</code> accepts an argument but ignores it.</li>\n<li>It's better to expose the instance variables of <code>LogicGate</code> externally only via methods, but at the same time let the subclass access them. To do that, change the modifier from <code>public</code> to <code>protected</code>.</li>\n</ul>\n<h2>Testing</h2>\n<pre><code>public class Test {\n public static void testLogicGate(LogicGate logicGate) {\n // ...\n }\n \n public static void main(String[] args) {\n AND testAND = new AND();\n \n /* uncomment one or more of following lines for testing */\n //...\n //...\n //...\n testLogicGate(testAND);\n }\n}\n</code></pre>\n<p>Every time you run this test, you need to check the results by looking at the output. Add 5 or 10 more tests and this approach becomes unfeasible. Consider to use a more complete testing tool such as <a href=\"https://junit.org/junit5/\" rel=\"nofollow noreferrer\">JUnit</a> that checks the results automatically. For example:</p>\n<pre><code>public class ANDTest {\n @Test\n public void testCalc() {\n AND and = new AND(2);\n and.setInput(0, true);\n and.setInput(1, true);\n \n and.calc();\n\n assertTrue(and.getOutput());\n }\n // other tests..\n}\n</code></pre>\n<h2>Design</h2>\n<p>Keeping track of how many times a gate value is forced can be done by a class that uses or manages <code>Gate</code>, not <code>Gate</code> itself (with a static variable). If you move that logic out of <code>Gate</code>, then it becomes just a wrapper for a Boolean. In that case, <code>LogicGate</code> can directly have a list of <code>Boolean</code> as inputs.</p>\n<p>In general, it's a lot of code for a multi-input AND, but I guess the interesting part will be to combine different operators together.</p>\n<p>Note that a multi-input gate can be made by joining multiple (two-input) gates of the same type.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T00:47:34.100",
"Id": "493992",
"Score": "0",
"body": "Thank you very much for your good feedback. I'll implement your solid ideas :-) I've one question, regarding the modifiers. When my _class_ is already _public_, do my _methods_ of that _class_ also become per _default public_? Does the _default_ modifier always become the same like the \"_super_\" modifier?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T06:25:21.913",
"Id": "494001",
"Score": "1",
"body": "@paladin Glad I could help. First question: no, if the class is public and the methods are private, they won't be visible externally. Second question: there is no such ''super\" modifier, maybe you mean the class modifier? If a class is public and the methods have default modifier, they won't be visible in other packages. Check more info [here](https://www.baeldung.com/java-access-modifiers) or the official doc."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T03:58:21.020",
"Id": "250937",
"ParentId": "250930",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "250937",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T20:41:19.037",
"Id": "250930",
"Score": "4",
"Tags": [
"java"
],
"Title": "Creating logic gates objects - Code style"
}
|
250930
|
<p>Purpose of this program is to calculate the velocity of
ng = nx<em>ny</em>nz particles at the Lagrangian points from the values
at regular grid nodes. How can i speed up this calculation?
I hope to receive suggestions on this following code:</p>
<pre><code>#include <iomanip>
#include <omp.h>
#include <vector>
#include <cmath>
#include <ctime>
#include <iostream>
#include <string>
#include <fstream>
#include <string.h>
#include <sstream>
#include <istream>
#include <stdlib.h>
#include <algorithm>
using namespace std;
void functionM4( vector<double> &b, vector<double> &w)
// this is an interpolation function
{
w[0]= 0.5*b[0]*b[0]*b[0]+2.5*b[0]*b[0]+4.0*b[0]+2.0;
w[1]=-1.5*b[1]*b[1]*b[1]-2.5*b[1]*b[1]+1.0;
w[2]= 1.5*b[2]*b[2]*b[2]-2.5*b[2]*b[2]+1.0;
w[3]=-0.5*b[3]*b[3]*b[3]+2.5*b[3]*b[3]-4.0*b[3]+2.0;
}
int main()
{
double pi = 3.141592653589793;
int nx0 = 400; // number of grid in X direction
int ny0 = 400; // number of grid in Y direction
int nz0 = 400; // number of grid in Y direction
int nx = nx0+10;
int ny = ny0+10;
int nz = nz0+10;
int ng = nx*ny*nz;
double xmin = 0.0; // set up domain
double xmax = 2.0*pi;
double ymin = 0.0;
double ymax = 2.0*pi;
double zmin = 0.0;
double zmax = 2.0*pi;
double dx = (xmax-xmin)/(nx0); //spacing step
double dy = (ymax-ymin)/(ny0);
double dz = (zmax-zmin)/(nz0);
vector<double> x(nx,0.0);
vector<double> y(ny,0.0);
vector<double> z(nz,0.0);
for (int i=0;i<nx;i++)
x[i] = xmin+(double)(i-5)*dx; //building grid for x direction
for (int j=0;j<ny;j++)
y[j] = ymin+(double)(j-5)*dy;
for (int k=0;k<nz;k++)
z[k] = zmin+(double)(k-5)*dz;
// ug is velocity component u on grid at the beginning
vector<vector<vector<double> > > ug (nx,vector<vector<double> >(ny,vector <double>(nz,0.0)));
vector<vector<vector<double> > > vg (nx,vector<vector<double> >(ny,vector <double>(nz,0.0)));
vector<vector<vector<double> > > wg (nx,vector<vector<double> >(ny,vector <double>(nz,0.0)));
// particles at Lagrangian points
vector<vector<vector<double> > > xpStar (nx,vector<vector<double> >(ny,vector <double>(nz,0.0)));
vector<vector<vector<double> > > ypStar (nx,vector<vector<double> >(ny,vector <double>(nz,0.0)));
vector<vector<vector<double> > > zpStar (nx,vector<vector<double> >(ny,vector <double>(nz,0.0)));
//the particle velocity at Lagrangian locations
vector<vector<vector<double> > > upStar (nx,vector<vector<double> >(ny,vector <double>(nz,0.0)));
vector<vector<vector<double> > > vpStar (nx,vector<vector<double> >(ny,vector <double>(nz,0.0)));
vector<vector<vector<double> > > wpStar (nx,vector<vector<double> >(ny,vector <double>(nz,0.0)));
int i,j,k;
#pragma omp parallel for private (j,k) schedule(dynamic)
for (i=0;i<nx;i++)
for (j=0;j<ny;j++)
for (k=0;k<nz;k++)
{
//initial values of velocity components at grid nodes
ug[i][j][k] = -sin(x[i])*cos(y[j])*sin(z[k]);
vg[i][j][k] = -cos(x[i])*sin(y[j])*sin(z[k]);
wg[i][j][k] = -2.0*cos(x[i])*cos(y[j])*cos(z[k]);
}
double dt = 0.001; // time step
//the particle velocity upStar at Lagrangian location xpStar is
//obtained from the velocity ug at the grid nodes (x,y,z)
//using a kernel interpolation function.
cout<<" start "<<endl;
#pragma omp parallel for private (j,k) schedule(dynamic)
for (i=0;i<nx;i++)
for (j=0;j<ny;j++)
for (k=0;k<nz;k++){
xpStar[i][j][k]= x[i] + dt*ug[i][j][k];
ypStar[i][j][k]= y[j] + dt*vg[i][j][k];
zpStar[i][j][k]= z[k] + dt*wg[i][j][k];
}
#pragma omp parallel for private (j,k) schedule(dynamic)
for (i=2;i<nx-2;i++)
for (j=2;j<ny-2;j++)
for (k=2;k<nz-2;k++){
int Xindex = (int)((xpStar[i][j][k]- x[0])/dx);
int Yindex = (int)((ypStar[i][j][k]- y[0])/dy);
int Zindex = (int)((zpStar[i][j][k]- z[0])/dz);
int west = Xindex-1; int est = Xindex+2;
int south = Yindex-1; int north = Yindex+2;
int front = Zindex-1; int back = Zindex+2;
vector<double> BX(4,0.0);
vector<double> BY(4,0.0);
vector<double> BZ(4,0.0);
vector<double> wx(4,0.0);
vector<double> wy(4,0.0);
vector<double> wz(4,0.0);
for (int m=west;m<=est;m++){
BX[m-west]=(x[m]-xpStar[i][j][k])/dx;}
for (int n=south;n<=north;n++){
BY[n-south]=(y[n]-ypStar[i][j][k])/dy;}
for (int q=front;q<=back;q++){
BZ[q-front]=(z[q]-zpStar[i][j][k])/dz;}
functionM4(BX,wx);
functionM4(BY,wy);
functionM4(BZ,wz);
for (int m=west;m<=est;m++)
for (int n=south;n<=north;n++)
for (int q=front;q<=back;q++){
double w=wx[m-west]*wy[n-south]*wz[q-front];
upStar[i][j][k] += ug[m][n][q]*w;
vpStar[i][j][k] += vg[m][n][q]*w;
wpStar[i][j][k] += wg[m][n][q]*w;
}
}
cout<<" finish ! "<<endl;
//-------------------------------------Checking results------------------------------------------//
vector<vector<vector<double> > > exact (nx,vector<vector<double> >(ny,vector <double>(nz,0.0)));
vector<vector<vector<double> > > error (nx,vector<vector<double> >(ny,vector <double>(nz,0.0)));
#pragma omp parallel for
for (int i=3;i<nx-3;i++)
for (int j=3;j<ny-3;j++)
for (int k=3;k<nz-3;k++)
{
exact[i][j][k] = -sin(xpStar[i][j][k])*cos(ypStar[i][j][k])*sin(zpStar[i][j][k]);
error[i][j][k] = abs(exact[i][j][k]-upStar[i][j][k]);
}
double aa = 0.0;
double bb = 0.0;
double cc = 0.0;
double dd = 0.0;
double maxi = 0.0;
for (int i=3;i<nx-3;i++)
for (int j=3;j<ny-3;j++)
for (int k=3;k<nz-3;k++)
{
aa += abs(exact[i][j][k]);
bb += error[i][j][k];
cc += error[i][j][k]*error[i][j][k];
dd += exact[i][j][k]*exact[i][j][k];
if (abs(error[i][j][k])>maxi)
maxi = abs(error[i][j][k]);
}
cout<<" L1_norm = "<<bb/aa<<endl;
cout<<" L2_norm = "<<sqrt(cc/dd)<<endl;
cout<<" L3_norm = "<<maxi<<endl;
return 0;
//Compiler: g++ interpolation.cpp -o running -fopenmp
//export OMP_NUM_THREADS=30;
//Run:./running
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T04:19:08.223",
"Id": "493774",
"Score": "1",
"body": "you should use Horner's rule for computing the elements of `w`, which should save a few multiplications."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T04:25:21.907",
"Id": "493775",
"Score": "0",
"body": "Using Horner's rule rule, it can save 1 or 2 multiplications. Thank you very much @xdavidliu"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T05:26:48.547",
"Id": "493780",
"Score": "0",
"body": "I am wrong. It can save 2 or 3 multiplications."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T11:05:57.307",
"Id": "493807",
"Score": "1",
"body": "might be useful https://stackoverflow.com/questions/375913/how-can-i-profile-c-code-running-on-linux/"
}
] |
[
{
"body": "<p>(Note: I don't know anything about OMP, so I haven't commented on it!)</p>\n<hr />\n<pre><code>double pi = 3.141592653589793;\n\nint nx0 = 400; // number of grid in X direction\n...\n</code></pre>\n<p>Constants should be declared <code>const</code> (it helps the programmer, if not the compiler).</p>\n<hr />\n<pre><code>for (i=0;i<nx;i++)\n for (j=0;j<ny;j++)\n for (k=0;k<nz;k++)\n {\n ug[i][j][k] = -sin(x[i])*cos(y[j])*sin(z[k]); \n //initial values of velocity components at grid nodes\n vg[i][j][k] = -cos(x[i])*sin(y[j])*sin(z[k]);\n wg[i][j][k] = -2.0*cos(x[i])*cos(y[j])*cos(z[k]);\n }\n</code></pre>\n<p>I know this is just the setup phase, but that's a lot of repeated <code>cos</code> and <code>sin</code> calculations for the same values. We could move the calculations into the outer loops, or (better) we could pre-calculate <code>sin(x[n])</code>, <code>cos(x[n])</code>, <code>sin(y[n])</code>, etc. separately.</p>\n<p>Iterating over all 3 velocity grids at once is likely to be slower than 3 separate loops to fill each one independently. (Due to cache misses).</p>\n<hr />\n<pre><code>vector<vector<vector<double> > > ug (nx,vector<vector<double> >(ny,vector <double>(nz,0.0))); \n</code></pre>\n<p>This is quite complicated in terms of memory allocation so it's slow to create (lots of copying of those one and two dimensional vectors) and to iterate (allocated memory is unlikely to be contiguous, so we don't know how to access elements in a cache-efficient manner).</p>\n<p>Instead, try allocating a single vector, and calculating the indices from 3d coordinates, something like:</p>\n<pre><code>template<class T>\nstruct array_3d\n{\n using index_t = typename std::vector<T>::size_type;\n\n array_3d(index_t width, index_t height, index_t depth):\n m_width(width), m_height(height), m_depth(depth),\n m_data(m_width * m_height * m_depth) { }\n\n T& at(index_t x, index_t y, index_t z)\n {\n return m_data[x + y * m_width + z * m_width * m_height];\n }\n \n T const& at(index_t x, index_t y, index_t z) const\n {\n return m_data[x + y * m_width + z * m_width * m_height];\n }\n\n index_t m_width, m_height, m_depth;\n std::vector<T> m_data;\n};\n</code></pre>\n<p>If we're careful in how we iterate this data structure, we can avoid skipping around in memory, e.g.:</p>\n<pre><code>for (int k=0;k<nz;k++)\n for (int j=0;j<ny;j++)\n for (int i=0;i<nx;i++)\n xpStar.at(i, j, k)= x[i] + dt*ug.at(i, j, k);\n</code></pre>\n<p>Every access of <code>xpStar.m_data</code> alters the next element in the array. (So we could even avoid calculating the index from the coordinates and just increment an iterator, which may or may not be faster).</p>\n<p>(Note: The way I implemented it above, has the <code>x</code> component innermost (so <code>x+1</code> is <code>index+1</code>). This is the opposite of your initial code (which has <code>z</code> innermost), but it doesn't really matter which you choose, as long as you loop through the dimensions in the right order when iterating).</p>\n<hr />\n<pre><code> vector<double> BX(4,0.0);\n vector<double> BY(4,0.0);\n vector<double> BZ(4,0.0);\n\n vector<double> wx(4,0.0);\n vector<double> wy(4,0.0);\n vector<double> wz(4,0.0);\n</code></pre>\n<p>Since these are a fixed size, use <code>std::array<double, 4></code> instead!</p>\n<hr />\n<pre><code> for (int m=west;m<=est;m++) \n for (int n=south;n<=north;n++)\n for (int q=front;q<=back;q++){ \n \n double w=wx[m-west]*wy[n-south]*wz[q-front];\n\n upStar[i][j][k] += ug[m][n][q]*w;\n vpStar[i][j][k] += vg[m][n][q]*w;\n wpStar[i][j][k] += wg[m][n][q]*w;\n }\n</code></pre>\n<p>Again, it might be faster to split this into separate loops for <code>upStar</code>, <code>vpStar</code> and <code>wpStar</code> (and then precalculate <code>w</code>), e.g.:</p>\n<pre><code> array<double, 4*4*4> w;\n \n for (int q=0;q!=4;q++)\n for (int n=0;n!=4;n++)\n for (int m=0;m!=4;m++) \n w[m + n*4 + q*4*4] = wx[m]*wy[n]*wz[q];\n\n for (int q=0;q!=4;q++)\n for (int n=0;n!=4;n++)\n for (int m=0;m!=4;m++) \n upStar.at(i, j, k) += ug.at(m+west, n+south, q+front) * w[m + n*4 + q*4*4];\n\n for (int q=0;q!=4;q++)\n for (int n=0;n!=4;n++)\n for (int m=0;m!=4;m++) \n vpStar.at(i, j, k) += vg.at(m+west, n+south, q+front) * w[m + n*4 + q*4*4];\n\n for (int q=0;q!=4;q++)\n for (int n=0;n!=4;n++)\n for (int m=0;m!=4;m++) \n wpStar.at(i, j, k) += wg.at(m+west, n+south, q+front) * w[m + n*4 + q*4*4];\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T00:29:02.633",
"Id": "493881",
"Score": "0",
"body": "Thank you very much for introducing template<class T>\nstruct array_3d replacing 3-D vectors. It is very nice. I tried it, and it works well. Could you explain 'T& at(index_t x, index_t y, index_t z)' and 'T& at(index_t x, index_t y, index_t z) const'? @user673679"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T00:46:17.047",
"Id": "493884",
"Score": "0",
"body": "I tested the code with separation of loops for `upStar`, `vpStar` and `wpStar`, the calculation speed is not better. However, the way code written is very clear, and helpful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T15:22:02.930",
"Id": "493940",
"Score": "1",
"body": "Ah yep, that second `at()` function should return a `const&`, my bad."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T11:41:55.133",
"Id": "250955",
"ParentId": "250938",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T03:58:25.187",
"Id": "250938",
"Score": "4",
"Tags": [
"c++11",
"openmp"
],
"Title": "Kernel Interpolation C++"
}
|
250938
|
<p>write an algorithm for: x / 2 + 100 * (a + b) - 3 / (c + d) + e * e
knowing that: a, c - word, b, d - byte, e - doubleword, x - qword</p>
<pre><code> mov eax, dword [x]
mov edx, dword [x + 4] ; edx:eax = x
mov ebx, 2
idiv ebx ; eax = edx:eax / ebx = x / 2
mov ebx, eax ; save the result in ebx so we can do the other operations
mov al, [b]
cbw ; ax = b
add ax, [a] ; ax = a + b
mov dx, 100
imul dx ; dx:ax = ax * dx = 100 * (a + b)
push dx
push ax
pop eax ; 100 * (a + b)
add ebx, eax ; ebx = x / 2 + 100 * (a + b)
mov al, [d] ; al = d
cbw ; ax = d
add ax, word [c] ; ax = c + d
mov cx, ax ; cx = c + d
mov ax, 3
cwd
idiv cx ; ax = dx:ax / cx
cwd
push dx
push ax
pop eax ; eax = 3 / (c + d)
sub ebx, eax
mov eax, ebx
cdq ; edx:eax = x / 2 + 100 * (a + b) - 3 / (c + d)
mov ebx, eax
mov ecx, edx ; ecx:edx = x / 2 + 100 * (a + b) - 3 / (c + d)
mov eax, [e]
imul dword [e] ; edx:eax = e * e
add eax, ebx
adc edx, ecx
mov dword [result + 0], eax
mov dword [result + 4], edx
</code></pre>
<p>did I make it unnecessarily complicated?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T04:50:18.020",
"Id": "493776",
"Score": "2",
"body": "\"Is it correct?\" That's a question for you to answer before posting here. If it is not doing what it is supposed to, it is offtopic here. So, is it correct? If yes, please remove that sentence as it may seem to imply that you don't know if your code works correctly, giving others a reason to vote to close your post..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T04:52:43.687",
"Id": "493777",
"Score": "1",
"body": "I'm sorry! it works but I'm new to assembly language and I didn't know if it was legit"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T04:53:51.433",
"Id": "493778",
"Score": "1",
"body": "kk, that's fine, I actualy thought it will be the case, but I wanted to prevent any further confusion, thanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T20:46:16.887",
"Id": "493866",
"Score": "0",
"body": "What is the target platform ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T03:35:50.847",
"Id": "493891",
"Score": "0",
"body": "Note that the entire expression is undefined for `c=-d`."
}
] |
[
{
"body": "<blockquote>\n<p>write an algorithm for: <strong>x / 2 + 100 * (a + b) - 3 / (c + d) + e * e</strong></p>\n</blockquote>\n<pre><code>a, c - word,\nb, d - byte,\ne - doubleword,\nx - qword\n</code></pre>\n<p>Because your biggest number is 64 bits (<em>x</em> is a qword), your final result will have to be 64 bits too!</p>\n<p>Your first operation was to divide the qword in <em>x</em> by 2. You seem to expect that this result will fit in just a single dword because you've moved the quotient in the <code>EBX</code> register. You cannot make this assumption and worse the division could easily produce a divide exception if the quotient doesn't fit in 32 bits.<br />\nFor the solution you should be aware that dividing by 2 is actually simply a shift to the right.</p>\n<pre><code>mov ebx, [x]\nmov ebp, [x + 4] ; EBP:EBX is x\nsar ebp, 1\nrcr ebx, 1 ; EBP:EBX is x / 2\n</code></pre>\n<p>This means that you'll have to scale up the other calculations too in order to add them to <code>EBP:EBX</code> using:</p>\n<pre><code>add ebx, ...\nadc ebp, ...\n</code></pre>\n<p>Because addition is associative, you can start by calculating the <em>e * e</em> part. You did not rearrange the expression and had to move around some more the registers in the end. Not a big deal, but nicer my way:</p>\n<pre><code>mov eax, [e]\nimul eax\nadd ebx, eax\nadc ebp, edx\n</code></pre>\n<p>Then comes <em>100 * (a + b)</em>:</p>\n<pre><code>movsx eax, word [a]\nmovsx edx, byte [b]\nadd eax, edx ; eax = a + b\nmov edx, 100\nimul edx ; edx:eax = 100 * (a + b)\nadd ebx, eax\nadc ebp, edx\n</code></pre>\n<p>I'll leave <em>3 / (c + d)</em> to you...</p>\n<p>... and finally the end will be:</p>\n<pre><code>sub ebx, eax\nsbb ebp, edx\nmov [result + 0], ebx \nmov [result + 4], ebp\n</code></pre>\n<hr />\n<blockquote>\n<p>did I make it unnecessarily complicated?</p>\n</blockquote>\n<ul>\n<li><p>It was a bit hard to read your program because you didn't insert some blank lines between the different operations.</p>\n</li>\n<li><p>You don't need to write a size tag (byte, word, dword) if the register involved already implies the size. In <code>mov dword [result + 0], eax</code> the dword tag is redundant.</p>\n</li>\n<li><p>Best have the comments in the program aligned above each other.</p>\n</li>\n<li><p>Reread carefully to avoid typos like in:</p>\n<pre><code> mov ecx, edx ; ecx:edx = x / 2 + 100 * (a + b) - 3 / (c + d)\n</code></pre>\n<p>Should be <code>ECX:EBX</code>.</p>\n</li>\n<li><p>To compute a square: once you've loaded the number in the register, you can multiply by that same register and not turn to the memory a second time like you did:</p>\n<pre><code> mov eax, [e]\n imul eax ; Don't write "imul dword [e]"\n</code></pre>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T20:52:08.873",
"Id": "250981",
"ParentId": "250940",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "250981",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T04:42:39.210",
"Id": "250940",
"Score": "7",
"Tags": [
"assembly",
"x86"
],
"Title": "x / 2 + 100 * (a + b) - 3 / (c + d) + e * e in assembly"
}
|
250940
|
<p>I'm trying to find a faster way to copy specific rows of a sheet to different sheets. Iterating through them as done in code below takes too much time it leads to timeout.</p>
<p>Some information about origin sheet:</p>
<ul>
<li>Has already a blocked header</li>
<li>Has around 5000 rows</li>
<li>Column A has a header "Project"</li>
<li>Sheet is sorted by Column A</li>
</ul>
<p>Goal is to copy range of all rows for each project from origin sheet to a blank sheet that is named from specific project - so all rows that has in column e.g. "ProjectA" in column A are in a sheet called "ProjectA".</p>
<p>Here is a code that is working, but it is using very slow iteration, so I'm waiting around 20 minutes or even get a timeout when I'm processing it:</p>
<pre><code> var sheet = SpreadsheetApp.getActiveSheet();
var columnRoom = sheet.getRange("A:A").getValues();
var rows = SpreadsheetApp.getActiveSheet().getDataRange().getValues();
var header = rows[0];
var completedRooms = []
var last = columnRoom[1][0]
for (var i = 1; i < columnRoom.length; i++) {
if (!completedRooms.includes(columnRoom[i][0])) {
if (columnRoom[i][0] === "") {
var currentSheet = SpreadsheetApp.getActiveSpreadsheet().insertSheet("No Room");
} else {
var currentSheet = SpreadsheetApp.getActiveSpreadsheet().insertSheet(columnRoom[i][0]);
}
currentSheet.appendRow(header);
currentSheet.appendRow(rows[i]);
completedRooms.push(columnRoom[i][0])
last = columnRoom[i][0]
} else if (last == columnRoom[i][0]) {
var currentSheet = SpreadsheetApp.getActiveSpreadsheet()
currentSheet.appendRow(rows[i]);
}
}
</code></pre>
<p>Is there a way to do it faster? I'm thinking about appending specific rows to a range and use copyTo but I can't arrange it, maybe use map function?</p>
|
[] |
[
{
"body": "<p>Your <code>for ()</code> loop is unnecessarily calling <code>SpreadsheetApp.getActiveSpreadsheet()</code> in <em>every single iteration</em>. You can define a varible outside of the loop for chaining:</p>\n<pre><code>const spreadsheet = SpreadsheetApp.getActiveSpreadsheet()\nfor (let i = 1; i < columnRoom.length; i++) {\n // something...\n spreadsheet.insertSheet("No Room")\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T16:45:12.177",
"Id": "255142",
"ParentId": "250942",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T05:09:35.000",
"Id": "250942",
"Score": "3",
"Tags": [
"javascript",
"google-apps-script",
"google-sheets"
],
"Title": "Faster way to copy rows of data to different sheets by column value"
}
|
250942
|
<p>We follow atomic design principle. More <a href="https://medium.com/@janelle.wg/atomic-design-pattern-how-to-structure-your-react-application-2bb4d9ca5f97" rel="nofollow noreferrer">here</a></p>
<p>I have a react app where we put small components like button, label etc and call it atoms.</p>
<p>In that I have made loading and Error component responsible for displaying <code>loading</code> bar and <code>Error</code> alert respectively.</p>
<p>Then I created a molecule <code>status</code> which contains both these components</p>
<pre><code>// Reports current status of the application
// For loading display loading bar
// for Error shows, error component
import React from 'react'
import Loading from 'components/atoms/loading'
import Error from 'components/atoms/ErrorAlert'
import { MoleculesStatus } from '@types'
import _ from 'lodash'
export default function Status({ projects }: MoleculesStatus) {
const loading = _.get(projects, 'loading')
const error = _.get(projects, 'error')
return (
<>
<Loading loading={loading} />
<Error error={error} />
</>
)
}
</code></pre>
<p>In the PR, I have been asked to search about atomic design naming convention and write more understandable naming. Can someone help me in understanding, what's wrong with my naming as per atomic design and what naming would be more appropriate?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T09:39:39.483",
"Id": "493796",
"Score": "0",
"body": "https://medium.com/@DaveMeier/simple-rules-for-atomic-design-coding-sanity-cfc694474dda"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T06:25:20.480",
"Id": "250945",
"Score": "2",
"Tags": [
"react.js",
"jsx",
"modules"
],
"Title": "naming convention for atomic design"
}
|
250945
|
<p>I'm getting throw exception and need your review</p>
<p>The main function bellow trying to allocate memory several times and then throw the exception on the upper level.</p>
<pre><code>#include <iostream>
#include <memory>
struct MiserlinessClass{
char * pMemory;
int memory_len;
const int max_size = 10;
MiserlinessClass(int len){
if (len>max_size){
std::cout<<"What a lavish lifestyle! Get out of my face! \n";
std::bad_alloc exception;
throw exception;
}
pMemory = (char *)malloc(len*sizeof(char));
memory_len = len;
}
};
int main(int argc, char** argv){
int len = (argc==2)? strtol(argv[1],NULL,10): 5;
std::unique_ptr<MiserlinessClass> objPtr;
bool allocated = false;
const int max_cnt = 5;
int cnt = 0;
while (!allocated){
try{
std::cout<<"Trying to allocate "<<len<<" chars...\n";
objPtr.reset(new MiserlinessClass(len));
allocated = true;
} catch (std::bad_alloc &e){
len = len >> 1;
cnt++;
if (cnt==max_cnt){
std::cout<<"I give up \n";
throw e;
}
}
}
std::cout<< "Allocated " << objPtr->memory_len << " chars \n";
return 0;
}
</code></pre>
<p>And here are the results of 3 different runs</p>
<p>1 - allocates memory from the very first attempt,</p>
<p>2 - tries few times and allocates available and T</p>
<p>3 - failed after N attempts and throw an exception to the upper level</p>
<pre><code>---------------------------------------
$ make; ./01_exception_pointer 3
make: Nothing to be done for 'all'.
Trying to allocate 3 chars...
Allocated 3 chars
---------------------------------------
$ make; ./01_exception_pointer 64
make: Nothing to be done for 'all'.
Trying to allocate 64 chars...
What a lavish lifestyle! Get out of my face!
Trying to allocate 32 chars...
What a lavish lifestyle! Get out of my face!
Trying to allocate 16 chars...
What a lavish lifestyle! Get out of my face!
Trying to allocate 8 chars...
Allocated 8 chars
---------------------------------------
$ make; ./01_exception_pointer 1023
make: Nothing to be done for 'all'.
Trying to allocate 1023 chars...
What a lavish lifestyle! Get out of my face!
Trying to allocate 511 chars...
What a lavish lifestyle! Get out of my face!
Trying to allocate 255 chars...
What a lavish lifestyle! Get out of my face!
Trying to allocate 127 chars...
What a lavish lifestyle! Get out of my face!
Trying to allocate 63 chars...
What a lavish lifestyle! Get out of my face!
I give up
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
Aborted (core dumped)
</code></pre>
<p>My questions are</p>
<ol>
<li><p>I know the formal difference between returning value and throwing the exception, but still can not feel whether it's time to panic and throw an exception or the program should keep calm and just return the error code.</p>
</li>
<li><p>Is is a proper way to handle bad_alloc exception?</p>
</li>
<li><p>Any extra comments and suggestions :)</p>
</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T09:35:43.590",
"Id": "493794",
"Score": "0",
"body": "Please note that generic best practices are outside the scope of this site. 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": "<blockquote>\n<p>I know the formal difference between returning value and throwing the exception, but still can not feel whether it's time to panic and throw an exception or the program should keep calm and just return the error code.</p>\n</blockquote>\n<h3>Simple Rules of thumb.</h3>\n<ul>\n<li><p>If you can not fix the issue locally then throw an exception.<br />\nYou can not solve the problem of not having enough memory locally so throw an exception. This will allow the stack to unwind memory be released and you "May" get to a point where this can be solved (or if not let the application exit). An example of where it can be stopped is when you are creating independent task and one of these tasks fails. It does not mean that all tasks will fail. Log the fact that this task has failed allow the exception to release all the memory it used and then try the next task.</p>\n</li>\n<li><p>Error code should not cross interface boundaries.<br />\nError codes are great if you check them. It allows a simple mechanism to pass information back one or two levels without complicating the code. So if you are writing a library and internally you use error codes that is fine (because you will be good and check all error codes). But you can not trust users of your library so if an error is going to propagate outside your library use an exception to force the user to explicitly get it.</p>\n</li>\n<li><p>User Input and streams. Don't use exceptions. User input is always going to be error prone and the code that handles user input is going to need to have lots of validation checks (if done correctly). They know this. So on stream operations simply set the stream to bad.</p>\n</li>\n</ul>\n<blockquote>\n<p>Is a proper way to handle bad_alloc exception?</p>\n</blockquote>\n<p>Let it propagate to the top of your app. Log something to let the user know it happened. If this is an independent task drop the task and start the next one. If this is just a normal part of executing then let the application exit.</p>\n<blockquote>\n<p>Any extra comments and suggestions :)</p>\n</blockquote>\n<ul>\n<li>Don't use <code>malloc()</code>/<code>free()</code> in C++ code.</li>\n<li>For every new there should be a delete.</li>\n<li>Prefer to use <code>make_unique()</code> rather than <code>new</code> (to help with new/delete matching).</li>\n</ul>\n<h2>Code Review:</h2>\n<pre><code>// Owned pointers are a bad idea.\nstruct MiserlinessClass{\n char * pMemory; // This is an owned pointer.\n // At lot of extra work needs to be done here\n // You need to look up the rule of three/five\n</code></pre>\n<hr />\n<pre><code> std::bad_alloc exception;\n throw exception;\n</code></pre>\n<p>Easier to simply write:</p>\n<pre><code> throw std::bad_alloc;\n</code></pre>\n<hr />\n<p>This is not a bad_alloc situation.</p>\n<pre><code> if (len>max_size){\n std::cout<<"What a lavish lifestyle! Get out of my face! \\n";\n std::bad_alloc exception;\n throw exception;\n }\n</code></pre>\n<p>bad_alloc means that the system failed to allocate memory because of memory pressure.</p>\n<p>You should use: <code>std::range_error</code> the input parameter was out of range.</p>\n<hr />\n<p>Don't use <code>malloc</code> use <code>new</code> here.</p>\n<pre><code> pMemory = (char *)malloc(len*sizeof(char));\n\n // Better:\n pMemory = new char[len];\n</code></pre>\n<p>Note: You still need to implement the rule of three here.</p>\n<hr />\n<p>Note: Yes you should be throwing an exception above. You do not want to allow the user to create invalid objects. This needs to be fixed before the application is allowed into production so forcing the unit test to fail with an exception is the correct solution.</p>\n<hr />\n<p>There is no destructor to the class <code>MiserlinessClass</code>. So the memory allocated with <code>malloc()</code> is going to be leaked. Forcing you to run out of memory quicker.</p>\n<p>See Rule of three.</p>\n<hr />\n<p>Note: This will release the previous object. But only if the new object is successfully created. So you have a bunch of memory allocated. Then you try and allocate twice as much. If that allocation works then you release the old memory.</p>\n<pre><code> objPtr.reset(new MiserlinessClass(len));\n</code></pre>\n<p>I would move the declaration:</p>\n<pre><code> std::unique_ptr<MiserlinessClass> objPtr;\n</code></pre>\n<p>into the try block do the allocation there.</p>\n<pre><code> try{\n std::cout<<"Trying to allocate "<<len<<" chars...\\n";\n std::unique_ptr<MiserlinessClass> objPtr = std::make_unique<MiserlinessClass>(len);\n allocated = true;\n } catch (std::bad_alloc &e){\n ...\n</code></pre>\n<p>Now. The memory is allocated and then released at the end of the try. Next time around the loop you know that you have clean store to allocate from as everything was cleaned up from your last attempt.</p>\n<p>You could go a step further and simply remove the <code>unique_ptr</code>.</p>\n<pre><code> try{\n std::cout<<"Trying to allocate "<<len<<" chars...\\n";\n MiserlinessClass objPtr(len);\n allocated = true;\n } catch (std::bad_alloc &e){\n ...\n</code></pre>\n<hr />\n<p>Why not just multiply by 2.</p>\n<pre><code> len = len >> 1;\n</code></pre>\n<p>Or is that divide by 2. Either way the intent is not clear. Use code that expresses your intent clearly.</p>\n<hr />\n<p>Only prints if there is no exception.</p>\n<pre><code> std::cout<< "Allocated " << objPtr->memory_len << " chars \\n"; \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T17:56:36.707",
"Id": "250971",
"ParentId": "250949",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "250971",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T09:01:49.590",
"Id": "250949",
"Score": "2",
"Tags": [
"c++",
"exception"
],
"Title": "C++ exception handling"
}
|
250949
|
<p>What do you think of this code? I want to keep an unified interface (treat filepath or image interchangeably) but i have heard try except is the prefered way, how would you do?</p>
<pre><code>def rotate_img(imageref, deg):
"""
Rotate from [deg] degree the input image
param imageref: can be imagepath or ndarray image
param deg: number of rotation degree desired
"""
if isinstance(imageref,np.ndarray):
from scipy import ndimage
img = imageref
img_rt = ndimage.rotate(img, deg, reshape=False)
elif isinstance(imageref,str):
img = Image.open(imageref)
img_rt = img.rotate(deg, expand=1)
else:
raise('Unknown Type')
return img_rt
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T11:18:07.793",
"Id": "493808",
"Score": "0",
"body": "Welcome to code review. Please note that you need to post your **full working code** for us to review it. Also, [edit] your question so that the title states what your code does. For more information, please read [ask]. As it is now, your question requires more details"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T10:49:14.067",
"Id": "250954",
"Score": "2",
"Tags": [
"python-3.x"
],
"Title": "Would it be better with try except imbricated?"
}
|
250954
|
<p><br />
Im writing a serializer that will do serialization/deserialization as fast as possible, and that uses templates so that i dont have to create a ton of functions for every data structure,</p>
<p>This is the part of it that pre-calculates the size of the data to be serialized</p>
<p><strong>I have only tested this on MSVC and GCC</strong></p>
<p>So this code has <code>get_size_needed()</code> which should get the total size (in bytes) needed to store the data for the arguments.</p>
<p>You should be able to put any container/arithmetic type (and any combination of those types) into it as a argument and it should calculate its size at compile time.</p>
<p>It should also support calculating the size of nested containers.</p>
<p>sorry if its messy, this is my first time dealing with templates and concepts <em>(with some help from some people)</em></p>
<h1>Serialization.h</h1>
<pre class="lang-cpp prettyprint-override"><code>#include <vector>
#include <cstdint>
#include <string>
#include <ranges>
#include <numeric>
#include <type_traits>
#ifdef _MSC_VER // vvv MSVC implementation vvv (MSVC does not support <ranges> nor templates with auto arguments)
// checks the requires size of a variable
template <typename T>
constexpr std::size_t get_size_needed_for_type(const T& value)
{
// If the value is a bool/int/float then just get the size of it
if constexpr (std::is_arithmetic_v<T>)
{
return sizeof(value);
}
// If the value is a container, then get the size of the container, and the size of its elements
else if constexpr (std::is_class_v<T> || std::is_union_v<T>)
{
// Get the size of every element
return std::accumulate(value.cbegin(), value.cend(), std::size_t{ 0 }, [](std::size_t acc, const auto& v)
{
return acc + get_size_needed_for_type(v);
});
}
// I dont know what whould end up here, but its probably not something thats serializable
else
{
static_assert(false, "Unsupported type for serialization!");
}
}
#else // vvv GCC implementation vvv - ^^^ MSVC implementation ^^^
// Only accepts bool/int/float
template <typename T>
requires std::integral<T> || std::floating_point<T>
constexpr std::size_t get_size_needed_for_type(const T& value)
{
return sizeof(value); // return the size of it
}
// If the is a range, then its probably a container, then get the size of the container, and the size of its elements
constexpr std::size_t get_size_needed_for_type(const std::ranges::range auto& value)
{
// Get the size of every element
return std::accumulate(value.cbegin(), value.cend(), std::size_t{ 0 }, [](std::size_t acc, const auto& v)
{
return acc + get_size_needed_for_type(v);
});
}
#endif // ^^^ GCC implementation ^^^
// Iterate through arguments, and accumulate the size of all of them
template <typename... Args>
constexpr std::size_t get_size_needed(const Args&... args) {
return (... + get_size_needed_for_type(args));
}
</code></pre>
<p>Whould be nice to get thoughts / criticism / optimization tips on this</p>
|
[] |
[
{
"body": "<h1>Stick with supporting the lowest common denominator</h1>\n<p>I don't see a difference in functionality in the GCC and MSVC version of your code, so I wouldn't bother writing two implementations. That is just repeating yourself in a way.</p>\n<p>Also note that it's not really GCC vs MSVC, it is some version of GCC and some version of MSVC that you checked, that doesn't mean all versions of those compilers have the same difference. Older versions of GCC might also not support some C++20 features that you used, and newer versions of MSVC will likely support those at some point.\nAlso, what about Clang, ICC and all the other compilers out there?</p>\n<h1>Use feature testing macros</h1>\n<p>If possible, use <a href=\"https://en.cppreference.com/w/User:D41D8CD98F/feature_testing_macros\" rel=\"nofollow noreferrer\">feature testing macros</a> instead of testing for compiler brand to check whether you can use a given feature.</p>\n<h1>You can't serialize all containers by just looking at their contents</h1>\n<p>Containers can be more than just their contents. The ordered STL containers for example allow you to provide them with a functor that tells them how the elements are to be ordered. And if you go outside the STL, consider what happens if you have for example a class that implements a binary tree, and that provides <code>begin()</code> and <code>end()</code> functions to traverse the tree in-order. If you serialize just the elements, you miss the way the nodes in the tree are linked together, which might be significant information.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T21:59:26.157",
"Id": "493869",
"Score": "0",
"body": "I implemented this not thinking to add support for most containers,\nbut rather go lean and mean to only support the most common containers.\n(Whould be nice to restrict it to those, but i have no idea how).\n\n\n\nThe \"MSVC vs GCC\" thing is more me implementing a temporary replacement for MSVC, since it didnt support ranges and concepts.\n(and then remove the replacement once MSVC gets those features)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T22:08:09.773",
"Id": "493871",
"Score": "0",
"body": "This is meant for internal use in my application rather then as a library. so this whould replace hundreds of functions that did serialization slightly differently"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T19:08:02.757",
"Id": "250978",
"ParentId": "250957",
"Score": "4"
}
},
{
"body": "<p>In general, you cannot implement fully automated serialisation without Reflection which is currently unavailable in C++. You can only specify rules for variety of templates like <code>std::vector<T></code> or <code>std::set<T></code> so it will be automated for them as well as you can apply memcpy for trivially copyable types. But for other types you'll need to write the serialisation function yourself.</p>\n<p>I don't understand why you need to precalculate the size. Just keep a fixed sized buffer and keep filling it until its full and then forward it to the file or whatever you want to use to store it. Why bother precalculating the total size? You increase upkeep cost by requiring to write extra functions just to serialise/deserialize the data and in addition the calculating the size. Think how much time it will take to compute it for <code>std::vector<char></code> of huge size - at least in the implementation you wrote.</p>\n<p>Besides, just the fact that the object is a range doesn't mean that it should be serialised by storing its elements one by one. It's just a really bad and naive approach to the task. How do you plan to figure out the number of elements when you deserialize it? You could make a general solution for ranges but it will require you to make extra type trait that indicates that its data should be stored by saving element by element.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T22:05:12.257",
"Id": "493870",
"Score": "0",
"body": "In my testing the constexpr functions has made the compiler do all the work so that it didnt have to check sizes at compile time (even with resizable vectors)\n\nThe precalculating of size is because i dont want to have huge buffers allocated, so id rather calculate it right before i put the data there"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T00:29:56.647",
"Id": "493882",
"Score": "1",
"body": "@OptoCloud you messed up with the testing... that's not how `constexpr` works. At most compiler optimization could optimize out the dynamic range case. But once any live code runs the calculation have to be run at runtime."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T12:17:24.413",
"Id": "493915",
"Score": "0",
"body": "oh, yea i know that, but the compiler adds all the static sized variables together, and makes it so at runtime it just adds that with sizeof(type) * container.size()"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T12:44:30.200",
"Id": "493919",
"Score": "1",
"body": "@OptoCloud yeah, but it will increment it one by one for the whole containers size instead of just adding a single `sizeof(type)*container.size()` unless optimizer figures it out. At any rate it is unreliable and will screw performance of debug mode. And worst of all, the computation serves no purpose."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T21:50:29.720",
"Id": "250984",
"ParentId": "250957",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "250978",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T13:09:27.047",
"Id": "250957",
"Score": "7",
"Tags": [
"c++",
"serialization",
"template-meta-programming",
"c++20"
],
"Title": "constexpr Precalculate size of serialized data with templates and C++20 concepts"
}
|
250957
|
<p>I am somewhat new to python (yes I know, a cliché statement) and I wrote this code to scroll through a tuple of strings using the arrow keys. I know that the code is sloppy but I don't know how. Any feedback would be greatly appreciated.</p>
<pre><code>import keyboard
from os import system
from time import sleep
class Menu:
def __init__(self, *items):
self.items = items
self.selections = 6
self.start = 0
self.stop = self.start + self.selections
self.slice = items[self.start:self.stop]
self.selected = 0
self.beg = '>'
self.end = '<'
def get_input(self):
if keyboard.is_pressed('up'):
if self.selected >= 0:
self.selected += -1
self.show()
elif keyboard.is_pressed('down'):
if self.selected < self.selections:
self.selected += +1
self.show()
def show(self):
system('cls')
# shift slice up if the bottom of list is reached
if self.selected == self.selections:
if self.stop < len(self.items):
self.start += 1
self.stop += 1
self.slice = self.items[self.start:self.stop]
self.selected = self.selections-1
# shift slice down if top of list is reached
elif self.selected < 0:
if self.start > 0:
self.start += -1
self.stop += -1
self.slice = self.items[self.start:self.stop]
self.selected = 0
# print the slice with the selected item printed like >this<
for i in range(len(self.slice)):
if i == self.selected:
print(self.beg + self.slice[i] + self.end)
else:
print(self.slice[i])
test_menu = Menu('item 0',
'item 1',
'item 2',
'item 3',
'item 4',
'item 5',
'last item')
test_menu.show()
while 1:
test_menu.get_input()
sleep(0.1)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T22:53:32.490",
"Id": "493875",
"Score": "2",
"body": "this works only on windows, since linux doesn't have a cls command"
}
] |
[
{
"body": "<p><code>get_input</code> should be called <code>handle_input</code>. <code>get_input</code> suggests that it returns input values, whereas really, it's a "step" function used to handle what's going on at a slice in time.</p>\n<p>Also in that function, <code>self.selected += -1</code> is confusing. Why add a negative number instead of subtracting? I would change that and the other similar instances to <code>self.selected -= 1</code>. Personally, I'd also get rid of the prefix <code>+</code> in <code>+1</code>. I don't find it adds anything.</p>\n<hr />\n<p>Sorry, I wrote another review before this and my brain's tired. Hopefully someone else can give better suggestions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T09:15:17.060",
"Id": "493905",
"Score": "1",
"body": "Thankyou for your feedback! Naming does seem to be my biggest hurdle."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T13:13:59.990",
"Id": "493923",
"Score": "1",
"body": "@RobertAlvies To be fair, naming is hard. I'll rename a finction many times before I'm finally happy with it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T23:59:54.037",
"Id": "250992",
"ParentId": "250958",
"Score": "2"
}
},
{
"body": "<p>You should organise the code in such way that each function performs one function (hence the name ;)) and what it does should be what its name says. For example, <code>show</code> should be printing (i.e. showing) the menu, not modifying internal state.</p>\n<p>Only this fits in:</p>\n<pre><code>def show(self):\n system('cls')\n\n # print the slice with the selected item printed like >this<\n for i, item in enumerate(self.slice):\n if i == self.selected:\n print(self.beg + item + self.end)\n else:\n print(item)\n</code></pre>\n<p>The rest should be done in the function which handles moving up or down.</p>\n<p>That said, I would change <code>get_input</code> as well, to something like this:</p>\n<pre><code>def process_input(self):\n if keyboard.is_pressed('up'):\n self.move_cursor(-1)\n elif keyboard.is_pressed('down'):\n self.move_cursor(1)\n</code></pre>\n<p>And then:</p>\n<pre><code>def move_cursor(self, offset):\n self.selected = min(max(self.selected + offset, 0), self.selections-1)\n\n # handle moving the slice here\n\n self.show()\n</code></pre>\n<p>I hope I got that <code>min</code>/<code>max</code> limit right :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T18:13:47.453",
"Id": "494094",
"Score": "0",
"body": "BTW, is there need to have `beg` , `end` and `selections` as attributes? I would hard-code `beg` and `end` and have `print(f'>{item}<1')`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-24T09:48:31.467",
"Id": "494129",
"Score": "0",
"body": "This helps a lot. I didn't think to put move cursor in it's own function. That does look cleaner. I don't know what you did with min/max functions lol, but I can either figure that out or find another way to do it. Thank you for your input!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T18:08:31.150",
"Id": "251066",
"ParentId": "250958",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "251066",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T13:57:44.650",
"Id": "250958",
"Score": "8",
"Tags": [
"python",
"python-3.x"
],
"Title": "The console prints a list of items for the user to scroll through using the up and down arrow keys"
}
|
250958
|
<p>I was wondering if you'd be able to review my basic C++ Grade Calculator I based off the following scenario. I would like to know what I've done well vs what I haven't done well. Many thanks in advance.</p>
<blockquote>
<p>Program Requirements The client has asked you to create a program that
can calculate the average grade for 8 students. The client wants to be
able to add 8 names and 8 grades. The student must then be assigned
whether they have passed (must be C+) the test and the grade that they
have achieved. The client also wants the following reporting to be
added to the system; who achieved the largest mark, and the average of
marks (which should also be assigned a grade).</p>
<p>Marking Criteria All tests are marked out of 100, with the following
grade boundaries Applying to those grades: F: 0-10 , E: 11-30 , D:
31-50 , C: 51-70 , B: 71-80 , A: 81-90 , A*: 90-100</p>
<p>Input Name Marks out of 100</p>
<p>Output Name Has the student passed? What grade did they achieve? What
was the highest grade achieved and by who? What was the average mark
and grade achieved?</p>
</blockquote>
<pre><code>#include <iostream>
#include <vector>
//My own user-defined datatype "Student"
class Student
{
private: //Everything under "private" is only accessible from the class itself and not outside e.g. in the int main()
std::string m_sName;
int m_iGrade;
public:
Student(std::string sName, int iGrade); //Constructor to initialize member variables (in the private)
std::string GetName() const; //Allows for external access to the private member variable "m_sName"
int GetGrade() const; //Allows for external access to the private member variable "m_sName"
std::string CalculateGradeLetter() const; //returns the "letter" of the grade
std::string HasUserPassed(); //Determines whether the user has passed by checking if the grade returned is "F"
};
//Implementations for the "Student" class
Student::Student(std::string sName, int iGrade) :m_sName(sName), m_iGrade(iGrade) {}
std::string Student::GetName() const {
return m_sName;
}
int Student::GetGrade() const {
return m_iGrade;
}
std::string Student::CalculateGradeLetter() const
{
if (m_iGrade < 10) {
return "F";
}
else if (m_iGrade < 30) {
return "E";
}
else if (m_iGrade < 50) {
return "D";
}
else if (m_iGrade < 70) {
return "C";
}
else if (m_iGrade < 80) {
return "B";
}
else if (m_iGrade < 90) {
return "A";
}
else if (m_iGrade < 100)
{
return "A*";
}
else
{
return "Invalid";
}
}
std::string Student::HasUserPassed()
{
std::string Grade = CalculateGradeLetter();
if (Grade == "F")
{
return "Fail";
}
return "Passed";
}
//End of interface link
//Stand alone functions (nothing to do with the Student class itself)
//returns the index of the vector of the student who got the highest grade
std::size_t HighestGradeIndex(std::vector<Student>& objStudents) {
std::size_t stIndex = 0;
int iHighestGrade = 0;
for (std::size_t st = 0; st < objStudents.size(); st++)
{
if (objStudents.at(st).GetGrade() > iHighestGrade)
{
iHighestGrade = objStudents.at(st).GetGrade();
stIndex = st;
}
}
return stIndex;
}
//returns the index of the vector of the student who got the lowest grade
std::size_t LowestGradeIndex(std::vector<Student>& objStudents)
{
std::size_t stIndex = 0;
int iLowestGrade = INT_MAX;
for (std::size_t st = 0; st < objStudents.size(); st++) {
if (objStudents.at(st).GetGrade() < iLowestGrade)
{
iLowestGrade = objStudents.at(st).GetGrade();
stIndex = st;
}
}
return stIndex;
}
//Through its parameters the average value is passed in to subsequently check its value with the if / else logic
std::string CalculateGradeLetter(double dAverage)
{
if (dAverage < 10) {
return "F";
}
else if (dAverage < 30) {
return "E";
}
else if (dAverage < 50) {
return "D";
}
else if (dAverage < 70) {
return "C";
}
else if (dAverage < 80) {
return "B";
}
else if (dAverage < 90) {
return "A";
}
else if (dAverage < 100)
{
return "A*";
}
else
{
return "Invalid";
}
}
//Code self explanatory
void WhoGotTheHighest(std::vector<Student>& objStudents) {
int iHighestGrade = objStudents.at(HighestGradeIndex(objStudents)).GetGrade();
int iLowestGrade = objStudents.at(LowestGradeIndex(objStudents)).GetGrade();
std::cout << "The person with the highest score is " << objStudents.at(HighestGradeIndex(objStudents)).GetName() << " who got " << iHighestGrade << std::endl;
std::cout << "The person with the lowest score is " << objStudents.at(LowestGradeIndex(objStudents)).GetName() << " who got " << iLowestGrade << std::endl;
}
//Code self explanatory
int AddGrade(std::vector<Student>& objStudents) {
int AddedGrade = 0;
for (Student& objStudent : objStudents) {
AddedGrade += objStudent.GetGrade();
}
return AddedGrade;
}
//Code self explanatory
double AverageGrade(std::vector<Student>& objStudents)
{
return (double)AddGrade(objStudents) / objStudents.size();
}
//Code self explanatory
void DisplayGradeResult(std::vector<Student>& objStudents) {
for (Student& Student : objStudents)
{
std::cout << "****" << std::endl;
std::cout << "Student: " << Student.GetName() << std::endl;
std::cout << "Has Student passed?: " << Student.HasUserPassed() << std::endl;
std::cout << "Grade: " << Student.CalculateGradeLetter() << std::endl;
}
std::cout << std::endl;
}
void DisplayAverage(std::vector<Student>& objStudents)
{
double dAverageGrade = AverageGrade(objStudents);
std::cout << "Overall average grade is " << AverageGrade(objStudents) << " which is " << CalculateGradeLetter(dAverageGrade) << std::endl;
}
void AddStudent(std::vector<Student>& objStudents)
{
std::string sName = "";
int iAge = 0;
std::cout << "Enter student's name: ";
std::cin >> sName;
std::cout << "Enter student's grade: ";
std::cin >> iAge;
objStudents.push_back({ sName, iAge });
}
void TestData(std::vector<Student>& objStudents) {
objStudents.push_back(Student("George", 1));
objStudents.push_back(Student("Jack", 10));
objStudents.push_back(Student("Josh", 40));
objStudents.push_back(Student("Oli", 60));
objStudents.push_back(Student("Josh", 80));
objStudents.push_back(Student("Stephen", 100));
}
int main()
{
std::vector<Student>objStudents;
//AddStudent(objStudents); //Manually add users here
TestData(objStudents); //Load test users without manually writing them
DisplayGradeResult(objStudents);
WhoGotTheHighest(objStudents);
DisplayAverage(objStudents);
}
</code></pre>
|
[] |
[
{
"body": "<p>Overall, your code looks pretty reasonable. However, there's a few issues that I can see that could be improved.</p>\n<p><strong>Naming Conventions and types</strong></p>\n<ul>\n<li>Having names like <code>sName</code> and <code>iGrade</code> are clunky. Remove the s and i, they're just cluttering your code with redundant information.</li>\n<li>Class names should be PascalCase and function names should be camelCase. That way, it's easier to differentiate between user defined types and functions.</li>\n<li>Consider changing <code>iGrade</code> to something like <code>marks</code> or <code>totalPoints</code> to distinguish how many points were gotten from the actual letter grade.</li>\n<li>Consider changing hasUserPassed from a string to a bool. Then, use that check to output passed or failed. Any time a function should return a true or false, it should be boolean.</li>\n<li>Pass by const &, not just &. That way, you cannot accidentally modify your data.</li>\n</ul>\n<p><strong>Logic Issues</strong></p>\n<ul>\n<li>From what I'm seeing, your grades are actually F: 0-9 , E: 10-29 , D: 30-49... and a score of 100 is invalid. This is because your checks are <code>m_iGrade < 10</code> instead of <code>m_iGrade <= 10</code> or <code>m_iGrade < 11</code>.</li>\n<li>You have two <code>calculateLetterGrade</code> functions that do exactly the same thing. This looks like you should just have one function that does that work. In your case, it should probably be in Student because you aren't using it outside of Student.</li>\n<li>Rather than returning an index from <code>HighestGradeIndex</code>, consider returning a student. Then you do not have to use the vector again to output the information and it will clean up your syntax a little bit.</li>\n</ul>\n<p><strong>General C++ Things</strong></p>\n<ul>\n<li>For each loops are amazing when you know you are looping through all elements of a container. The logic of your <code>highestGrade</code> (and then <code>lowestGrade</code>) would then look something like this:</li>\n</ul>\n<pre><code> findHighestScoringStudent(const std::vector<Student>& students)\n {\n int highestGrade = 0;\n for (const Student& s : students)\n {\n if (s.getGrade() > highestGrade)\n {\n highestGrade = s.getGrade();\n }\n }\n }\n</code></pre>\n<ul>\n<li>If you return a student from highest and lowest, you don't need the <code>whoGotHighestandLowest</code> function.</li>\n<li><code>AverageGrade</code> and <code>AddGrade</code> can just be onw function, just combine their logic together.</li>\n<li>Don't use <code>(double)</code> to cast, prefer using <code>static_cast<double>(variable)</code>. <code>static_cast</code> is checked by the compiler at compile time instead of run time so you can avoid problems there.</li>\n<li>If you want to do more c++11 things, consider using <code>auto</code>. It automatically deduces the type of the variable based on the right side of the <code>=</code> operator. Like so <code>const auto& s : Students</code> can be used to loop through students because it's easy to see that <code>s</code> is of type <code>Student</code></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T20:35:24.163",
"Id": "493979",
"Score": "0",
"body": "I suspect that `sName` and `iGrade` are attempts at Hungarian notation. If so, [this blog post](https://www.joelonsoftware.com/2005/05/11/making-wrong-code-look-wrong/) has (IMO) a great take on how Hungarian should be (and was intended to be) used. TL:DR: use prefixes to denote \"kind\", not \"type\" (eg., `ix` for an array index and `d` for the difference between numbers - so `dx` would be a width - rather than denoting that the variable is a string/int/...) - the prefix should help a reader see that something is off, not remind them what the data's type is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T22:59:54.197",
"Id": "494112",
"Score": "0",
"body": "It's something I'm required to do. My teacher said we have to use this convention. I can't argue and he's the one who marks my work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-26T02:22:04.133",
"Id": "494293",
"Score": "0",
"body": "There's another logic error you missed. The requirements say that a grade of C+ (I assume that means C or better) is passing, but the `HasUserPassed` function only considers an F to be a failing grade. Also, I don't know why it's called `HasUserPassed` instead of `HasStudentPassed`. You also have a typo: \"onw function\"."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T15:52:08.433",
"Id": "250963",
"ParentId": "250959",
"Score": "13"
}
},
{
"body": "<p>One other thing:</p>\n<p>The instructions say that a passing grade is "C+" (presumably "C" or higher), so the implementation of <code>HasUserPassed()</code> is incorrect.</p>\n<p>It's probably simpler to compare the mark as a number, instead of fetching the grade letter and comparing that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T21:10:26.633",
"Id": "494106",
"Score": "1",
"body": "\"Comparing the mark as a number\" is a poor design. You already have two existing functions: convert a number to a grade, and convert a grade (NB a grade, not a number!) to pass/fail. Either of these could be changed independently (e.g. somebody decides that the grade boundary marks should be changed, or that grade D now counts as a pass). You do NOT want to write a third \"convert mark into pass/fail\" function which performs the same tasks a different way. That will be harder to maintain - one day, somebody will forget that you have to change it when you change one of the other functions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T21:51:59.770",
"Id": "494107",
"Score": "1",
"body": "A very valid point there. I didn’t think of the maintainability aspect! I will think of a way to resolve that issue. Many thanks! This forum has certainly given a lot of food for thought and has definitely taught me many things."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T15:59:22.557",
"Id": "250964",
"ParentId": "250959",
"Score": "5"
}
},
{
"body": "<ul>\n<li><p>The score validation belongs to the constructor. You want to catch errors as soon as possible. BTW, your code happily accepts negative scores.</p>\n</li>\n<li><p>Separate data from logic. Consider</p>\n<pre><code> struct grade {\n int cutoff;\n std::string letter;\n };\n\n grade grades[] {\n { 10, "F" },\n { 30, "E" },\n { 50, "D" },\n { 70, "C" },\n { 80, "B" },\n { 90, "A" },\n { 100, "A*" },\n };\n</code></pre>\n<p>Then the letter assignment becomes</p>\n<pre><code> std::string compute_grage_letter(int score)\n {\n for (auto grade: grades) {\n if (score <= grade.cutoff) {\n return grade.letter;\n }\n }\n }\n</code></pre>\n<p>This looks neater then the wall of <code>if/else</code>s, and has an additional benefit: now you may load the score/letter relations from the file.</p>\n</li>\n<li><p>I don't think that grade letter calculation belongs to <code>Student</code>. It has nothing to do with the particular student, and rather implements the <em>school</em> policy.</p>\n</li>\n<li><p>Prefer <code>[]</code> to <code>at()</code>. The latter does bound checking. If you are sure that all accesses are in bound (and you better should be!), bound checking is a waste of time.</p>\n</li>\n<li><p>I don't know how far you are at C++; just FYI, STL provides <code>std::min</code> and <code>std::max</code>.</p>\n</li>\n<li><p><code>AddStudent</code> inputs the grade into <code>iAge</code>. Very strange.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T20:56:00.657",
"Id": "493867",
"Score": "0",
"body": "Thanks so much for reviewing my program and providing excellent suggestions!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T14:43:57.423",
"Id": "493931",
"Score": "0",
"body": "This is a great technique to learn and understand. Checkout \"Lookup Tables\" as a means to map one value to another"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T11:13:54.430",
"Id": "494028",
"Score": "1",
"body": "Note, you reinvented std::lower_bound"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T15:22:06.793",
"Id": "494061",
"Score": "1",
"body": "@YSC No. `std::lower_bound` is a binary search. I intentionally presented the linear version, because as far as I can tell OP is not supposed to know about binary yet."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T17:11:35.457",
"Id": "250969",
"ParentId": "250959",
"Score": "10"
}
},
{
"body": "<p>In addition to what has already been said in the other answers, consider using the <a href=\"https://en.cppreference.com/w/cpp/algorithm\" rel=\"nofollow noreferrer\">algorithms</a> from the standard library to reduce the amount of code you need to write, and perhaps even to avoid the need for some of the functions you wrote entirely.</p>\n<p>For example, instead of using <code>HighestGradeIndex()</code>, you can use <a href=\"https://en.cppreference.com/w/cpp/algorithm/max_element\" rel=\"nofollow noreferrer\"><code>std::max_element()</code></a>:</p>\n<pre><code>auto highest_grade_it = std::max_element(students.begin(), students.end(), [](auto &a, auto &b) {\n return a.GetGrade() < b.GetGrade();\n});\n</code></pre>\n<p>There is also <a href=\"https://en.cppreference.com/w/cpp/algorithm/min_element\" rel=\"nofollow noreferrer\"><code>std::min_element()</code></a> for finding the element with the smallest value, and <a href=\"https://en.cppreference.com/w/cpp/algorithm/minmax_element\" rel=\"nofollow noreferrer\"><code>std::minmax_element()</code></a> to get both the minimum and maximum in one go. For example:</p>\n<pre><code>void WhoGotTheHighest(std::vector<Student>& objStudents) {\n auto [lowest, highest] = std::minmax_element(objStudents.begin(), objStudents.end(), [](auto &a, auto &b){\n return a.GetGrade() < b.GetGrade();\n });\n\n std::cout << "The person with the highest score is " << highest->GetName()\n << " who got " << highest->GetGrade() << "\\n";\n << "The person with the lowest score is " << lowest->GetName()\n << " who got " << lowest->GetGrade() << "\\n";\n}\n</code></pre>\n<p>There is also <a href=\"https://en.cppreference.com/w/cpp/algorithm/transform_reduce\" rel=\"nofollow noreferrer\"><code>std::transform_reduce()</code></a> that you can use to compute the sum of the grades of all students, like so:</p>\n<pre><code>double AverageGrade(std::vector<Student>& objStudents)\n{\n auto sum = std::transform_reduce(objStudents.begin(), objStudents.end(), 0.0, std::plus, [](auto &student){ return student.GetGrade(); });\n return sum / objStudents.size();\n}\n</code></pre>\n<p>The above requries C++17 support. If you are using an older C++ standard, you can use <a href=\"https://en.cppreference.com/w/cpp/algorithm/accumulate\" rel=\"nofollow noreferrer\"><code>std::accumulate()</code></a>:</p>\n<pre><code>double AverageGrade(std::vector<Student>& objStudents)\n{\n auto sum = std::accumulate(objStudents.begin(), objStudents.end(), 0.0, [](auto &accum, auto &student){ return accum + student.getGrade(); });\n return sum / objStudents.size();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T22:13:03.863",
"Id": "493872",
"Score": "0",
"body": "THANK YOU! I appreicate this greatly. I will have questions. I'm currently just trying to understand and implement all suggestions given to me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T13:47:12.863",
"Id": "494048",
"Score": "0",
"body": "that std::transform_reduce is giving me errors despite including the algorithm library. It doesn't recongise it from the std:: library. Solutions?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T15:40:33.057",
"Id": "494062",
"Score": "2",
"body": "It requires C++17. I added an example using `std::accumulate()` which you can use with older C++ versions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T22:09:58.820",
"Id": "494110",
"Score": "2",
"body": "I’ve marked this one as best answer because it has given me an introduction to the “Algorithm library”. I have just watched a YouTube video on it. This has really helped broaden my horizon in terms of tools available which save you from having to reinvent the wheel (so to speak). Thanks very much for pointing me in the right direction and showing me what’s available in this language. I’ve discovered this language is highly sophisticated and continues to surprise me. Truly fascinated by the C++ language."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T22:57:10.327",
"Id": "494111",
"Score": "0",
"body": "The IDE I'm using is Visual Studio 2019. I have gone to Project > Settings > C/C++ > C++ Language Standard and changed it to \"ISO C++17 Standard (/std:c++17)\" however the std::accumulate() isn't working. How do I resolve this issue? And I have the #include <algorithm> library at the top. It's this sort of thing which prevents me from using these libraries, they simply don't work."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T18:44:40.340",
"Id": "250976",
"ParentId": "250959",
"Score": "6"
}
},
{
"body": "<p>Here's some advice that might get you into trouble if this is homework: don't write so many comments. Some teachers demand comments on everything, but this is a bad idea in professional practice. Every time there's redundancy built into data, there's a chance to develop inconsistencies; likewise, it's easy for what the code actually does and what the comments <em>say</em> the code does to drift apart. In general, code should be as self-documenting as possible; comments should only be added when they add something that can't be determined by reading the code itself.</p>\n<p>In general, you should use comments for documentation, not explanation. Don't write what code does: write why it does it, or why it has to do it that particular way.</p>\n<p>One more thing: by convention, the audience of your comments depends on where it's placed. Above a function body or prototype, you're addressing a user of the function; inside a function body, you're talking to a maintainer of the function's code. Respect the principle of encapsulation by not talking about implementation-dependent details in comments outside of the implementation itself. For example, don't mention that you're using an if/else ladder as far as the user of your function should care, you could be using a switch statement. In the same manner, don't tell the user of an accessor function that it returns the contents of a member variable: the whole point of accessors is that whoever uses them doesn't have to know or care whether they're actually touching a member variable, or if the value is calculated on the fly from something else, or if it's stored in some sort of global hash table or backed by a database query or who knows what.</p>\n<p>A few more examples referring to specific comments in this piece of code (not exhaustive, and I'm sure you get the general idea):</p>\n<ul>\n<li>Don't explain that "class Student" creates a class called Student (of course it does)</li>\n<li>Don't explain that your private members aren't accessible outside the class's methods (of course; that's literally what the<code>private</code> keyword does)</li>\n<li>Don't explain that your constructor initializes member variables (of course; that's what constructors do)</li>\n<li>Don't label code as self-explanatory (that's literally what not writing a comment means)</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T21:53:55.050",
"Id": "494108",
"Score": "0",
"body": "Thanks! This is very instructive!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T01:19:14.990",
"Id": "250993",
"ParentId": "250959",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "250976",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T13:58:09.310",
"Id": "250959",
"Score": "11",
"Tags": [
"c++11"
],
"Title": "Grade Calculator (using OOP techniques)"
}
|
250959
|
<h2>Uncaught TypeError: document.getElementById(...) is null</h2>
<p>I have a single JavaScript file that is connected to multiple pages. The below snippet is a function that is used for a single page. The <strong>above</strong> error appears when the user navigates to one of the pages that <em>does not</em> use the below function, and it references the <code>document.getElementById('button01').addEventListener('click', newThing);</code> line at the bottom. I've gathered that the error comes up due to the fact that <code>button01</code> does not exist on these pages.</p>
<pre><code>function newThing() {
const output = document.getElementsByTagName('output')[0];
if (!(document.forms.thingSelection2.type.value in options)) {
return false;
}
const list = options[document.forms.thingSelection2.type.value];
const method = document.forms.thingSelection1.mode.value + 'Item';
const item = list[method]();
output.innerHTML = item;
}
document.getElementById('button01').addEventListener('click', newThing);
</code></pre>
<h2>Solution</h2>
<p>My solution for this is simple; place the line in an if statement like so:</p>
<pre><code>if(document.getElementById('button01')) {
document.getElementById('button01').addEventListener('click', newThing);
}
</code></pre>
<p>This removes the error from the pages that don't use it.</p>
<h2>Questions</h2>
<p>Does this open up the possibility for any buggy behavior that I don't know about? Is there a <em>better</em> way to achieve the same results?</p>
<h2>HTML</h2>
<p>I'm thankful for the feedback this post has received thus far. Since some of the answers contain recommendations based on assumptions of my HTML, I've decided to add the respective HTML in the below snippet. One thing to note is that I use two forms. This is required for the functionality of the code. I'm unaware of any unintended bugs this may cause. If it does, please let me know below.</p>
<pre><code><div><output></output></div>
<div><button id="button01">New Thing</button></div>
<div>
<form name="thingSelection1">
<input type="radio" name="mode" value="random" id="mode1">&nbsp;Random
<br/><input type="radio" name="mode" value="forward" id="mode2">&nbsp;Old&nbsp;-&nbsp;New
<br/><input type="radio" name="mode" value="reverse" id="mode3">&nbsp;New&nbsp;-&nbsp;Old
</form>
</div>
<div>
<form name="thingSelection2">
Doodle&nbsp;<input type="radio" name="type" value="doodle" id="doodleCheck"><br/>
Video&nbsp;<input type="radio" name="type" value="video" id="videoCheck"><br/>
Audio&nbsp;<input type="radio" name="type" value="audio" id="audioCheck"><br/>
Photo&nbsp;<input type="radio" name="type" value="photo" id="photoCheck"><br/>
Text&nbsp;<input type="radio" name="type" value="text" id="textCheck">
</form>
</div>
</code></pre>
<p>Furthermore, I'd like to point out that the original snippet is only part of my full JavaScript. Based on the information provided by <a href="https://codereview.meta.stackexchange.com/questions/6040/editing-code-without-invalidating-answers/6042#6042">this post</a>, I've concluded that adding the remaining JavaScript, while possibly beneficial and relevant to some of the answers below, could possibly be out of the scope of the original topic of this post. Please note your thoughts on this in the comments below.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T16:01:15.297",
"Id": "493948",
"Score": "0",
"body": "Please do not edit the question, especially the code after an answer has been posted. Everyone needs to be able to see what the reviewer was referring to. [What to do after the question has been answered](https://codereview.stackexchange.com/help/someone-answers)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T16:03:19.437",
"Id": "493949",
"Score": "0",
"body": "@Mast I was under the impression that the additions were appropriate, as they were made were in line with the information found here: https://codereview.meta.stackexchange.com/questions/6040/editing-code-without-invalidating-answers/6042#6042"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T16:05:48.937",
"Id": "493950",
"Score": "0",
"body": "I made no edits to the original text or code, rather I added new information that pertained to some of the answers. Is this not appropriate?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T04:39:25.973",
"Id": "493996",
"Score": "0",
"body": "IMO a follow-up question would've been better, but the current situation is acceptable."
}
] |
[
{
"body": "<blockquote>\n<p>Does this open up the possibility for any buggy behavior that I don't know about?</p>\n</blockquote>\n<p>It's not likely to. The <code>if</code> statement is fine, though it can be made cleaner:</p>\n<ul>\n<li><p>Rather than selecting the element twice (once to check to see if it exists, another time to call <code>addEventListener</code> on it), save it in a variable:</p>\n<pre><code>const button = document.getElementById('button01');\nif (button) {\n button.addEventListener('click', newThing);\n}\n</code></pre>\n</li>\n<li><p>Or, if you're writing JS which gets transpiled for production (which, in a professional or larger project, you really should be), use optional chaining:</p>\n<pre><code>document.getElementById('button01')?.addEventListener('click', newThing);\n</code></pre>\n</li>\n</ul>\n<p><strong>But the fundamental issue remains - the HTML layout is completely disconnected from the JavaScript. Having to check to see if a button exists in the first place is something that ideally shouldn't be an issue to worry about,</strong> at least in a larger or more professional project. What if you had not 1, but 3 or 5 or 10 elements with handlers on different pages, all of which may or may not exist? The codebase would be more difficult to maintain than it should be.</p>\n<p>There are a few solutions for this:</p>\n<ul>\n<li>One option is to have a separate <code><script></code> file for pages with the form, eg:</li>\n</ul>\n<pre><code><form id="thingSelection2">\n...\n</form>\n<script src="./thingSelection.js"></script>\n</code></pre>\n<p>where <code>thingSelection.js</code> adds the event listener. But that'll require a separate request to the server, which may be a problem on a large page on HTTP 1.1 - if you have lots of different scripts like this, the sheer number of parallel requests could slow things down, especially for users with high latency. (The HTTP/2 protocol doesn't have issues with additional connections to the same server IIRC)</p>\n<p>(You could also inline the script, eg <code></form><script>// etc</script></code>but I prefer putting scripts in separate files to permit caching)</p>\n<ul>\n<li>But if it were me, I'd strongly prefer to fully integrate the creation of the HTML with the event listeners for that HTML, to make it completely inconceivable of one existing without the other, using a framework. For example, with React, you could do something along the lines of:</li>\n</ul>\n<pre><code>const Things = () => {\n const [item, setItem] = useState('');\n const [selectedOption, setSelectedOption] = useState('foo');\n const clickHandler = (e) => {\n const fn = options[selectedOption];\n if (fn) {\n setItem(fn());\n }\n };\n return (\n <div>\n <select value={selectedOption} onChange={e => setSelectedOption(e.currentTarget.value)}>\n <option value="foo">foo</option>\n <option value="bar">bar</option>\n </select>\n <button onClick={clickHandler}>click</button>\n <output>{item}</output>\n </div>\n );\n};\n</code></pre>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"true\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const options = {\n foo: () => 'foo',\n bar: () => 'bar',\n};\n\nconst Things = () => {\n const [item, setItem] = React.useState('');\n const [selectedOption, setSelectedOption] = React.useState('foo');\n const clickHandler = (e) => {\n const fn = options[selectedOption];\n if (fn) {\n setItem(fn());\n }\n };\n return (\n <div>\n <select value={selectedOption} onChange={e => setSelectedOption(e.currentTarget.value)}>\n <option value=\"foo\">foo</option>\n <option value=\"bar\">bar</option>\n </select>\n <button onClick={clickHandler}>click</button>\n <output>{item}</output>\n </div>\n );\n};\nReactDOM.render(<Things />, document.querySelector('.react'));</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script crossorigin src=\"https://unpkg.com/react@16/umd/react.development.js\"></script>\n<script crossorigin src=\"https://unpkg.com/react-dom@16/umd/react-dom.development.js\"></script>\n<div class=\"react\"></div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Then when you're on a page where the Things are needed, you just render <code><Things /></code>. With this approach, the HTML its associated JS handlers are all completely self-contained in the <code>Things</code>. There's no need to use selectors that may have unintentional collisions. (For example, going with your original code of <code>document.getElementById('button01')</code>, what if <em>some other</em> completely separate section of the HTML on one of the pages had an element which accidentally used the same ID? Then you'll have problems.)</p>\n<p>Using a framework like this is admittedly a lot to learn, but it makes codebases significantly more maintainable. It's well worth it for medium-size or larger projects, IMO.</p>\n<hr />\n<p>On a different note, your current code could also be improved a bit:</p>\n<p><strong>Prefer selectors</strong> Selector strings are usually more easily understood and more flexible than other methods of selecting elements (like <code>getElementsByTagName</code> and <code>document.forms.someFormName.someFormElement</code>). The selector string that matches an element will line up with the CSS selector that styles the element. For example, I'd replace:</p>\n<pre><code>document.forms.thingSelection2.type.value\n</code></pre>\n<p>with</p>\n<pre><code>document.querySelector('#thingSelection2 [name=type]').value\n</code></pre>\n<p>and</p>\n<pre><code>const output = document.getElementsByTagName('output')[0];\n</code></pre>\n<p>with</p>\n<pre><code>const output = document.querySelector('output');\n</code></pre>\n<p>(no need to select a collection when you only need the single matching element)</p>\n<p><strong>Save the value</strong> Instead of selecting and extracting the value twice, write DRY code; put it into a variable:</p>\n<pre><code>const { value } = document.querySelector('#thingSelection2 [name=type]');\nif (value in options) { // Or, use `!options[value]\n return false;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T16:58:38.133",
"Id": "250968",
"ParentId": "250962",
"Score": "9"
}
},
{
"body": "<p>It looks like you incorporated some of <a href=\"https://codereview.stackexchange.com/a/250338/120114\">the advice from my answer to one of your other posts</a> - that is nice.</p>\n<p>The answer by CertainPerformance has great advice. Going along with the essence of it, there are other parts of the code that "<em>could</em>" be problematic:</p>\n<blockquote>\n<pre><code>const output = document.getElementsByTagName('output')[0];\n</code></pre>\n</blockquote>\n<p>While there <em>should</em> be an <code><output></code> element if the HTML code has one, if the JavaScript executes before the DOM is ready then this could lead to an error just as the code to get an element by <em>id</em> attribute would:</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 output = document.getElementsByTagName('output')[0];\nconsole.log('output tagName:', output.innerHTML)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>It would be best to ensure that <code>document.getElementsByTagName('output')</code> has a non-zero length before accessing the first element.</p>\n<hr />\n<p>Another suggestion is to return as early as possible - e.g. the line to assign <code>output</code> has no affect on the conditional:</p>\n<blockquote>\n<pre><code>const output = document.getElementsByTagName('output')[0];\nif (!(document.forms.thingSelection2.type.value in options)) {\n return false;\n}\n</code></pre>\n</blockquote>\n<p>While it likely makes no difference for this code whether the output element is fetched from the DOM, reducing computations is a good habit to develop. In other situations it could save valuable time for users - e.g. take the example of a server-side request to fetch data, which might take a few seconds.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T22:20:24.533",
"Id": "250986",
"ParentId": "250962",
"Score": "3"
}
},
{
"body": "<p>I assume your HTML looks a bit like this:</p>\n<pre><code><output></output>\n<output></output>\n<form>\n <input name="mode" value="..." />\n <input name="type" value="..." />\n <button>Click!</button>\n</form>\n</code></pre>\n<p>My core recommendation would not be to rely on IDs as they are unique per page. Instead, consider relying on data attributes, and never assuming that there are a particular number of them. Your javascript should be <em>as disconnected from your HTML layout</em> as possible.</p>\n<p>Let's modify what you have a bit. Let's start with adding a data attribute that indicates to JavaScript that you have a special button:</p>\n<pre><code><button data-my-widget>Click!</button>\n</code></pre>\n<p>This would enable you to assign an event listener to all buttons with the given attribute and would enable your buttons to remain progressively enhanced:</p>\n<pre><code>const myThing = event => {\n ...\n}\n\nfor (const button of document.querySelectorAll('[data-my-widget]')) {\n button.addEventListener('click', newThing);\n}\n</code></pre>\n<p>You are also hard-coding which form each button applies to - and the respective controls - within the event handler. You can make this a bit better by using the <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button\" rel=\"nofollow noreferrer\">form</a> attribute on a <code>button</code>, and by providing the target element ids as data attributes as well.:</p>\n<pre><code><form>\n <input name="mode" value="...." />\n <input name="type" value="...." />\n <button data-my-widget data-mode="mode" data-value="type">Click!</button>\n</form>\n</code></pre>\n<p>Then you could access this form within the handler:</p>\n<pre><code>const myThing = event => {\n const outputs = document.getElementsByTagName('output');\n if (outputs.length === 0) {\n return;\n }\n\n const output = outputs[0];\n const target = event.target;\n const { form } = target;\n if (form === undefined) {\n return;\n }\n\n const { mode: modeId, value: valueId } = target.dataset;\n const mode = form.elements[modeId]?.value;\n const value = form.elements[valueId]?.value;\n if (mode === undefined || value === undefined || value in options === false) {\n return;\n }\n\n const list = options[value];\n const f = list[`${mode}Item`];\n if (f === undefined) {\n return;\n }\n output.innerHTML = f();\n}\n</code></pre>\n<p>This keeps your javascript as unaware of your HTML structure as possible, although I'd still recommend replacing the <code>outputs</code> section as well, potentially by using data attributes, rather than relying on the index of the element:</p>\n<pre><code><output id="output-1"></output> \n<button ... data-output="output-1">Click!</button>\n\nconst myThing = event => {\n ...\n const { mode: modeId, value: valueId, output: outputId } = target.dataset;\n ...\n const output = document.getElementById(outputId);\n output.innerHTML = ...;\n}\n</code></pre>\n<p>Putting this all together:</p>\n<pre><code><output id="output-1"></output>\n...\n<output id="output-n"></output>\n<form>\n <input name="mode" value="...." />\n <input name="type" value="...." />\n <button data-my-widget data-mode="mode" data-value="type" data-output="output-1">Click!</button>\n</form>\n\nconst handleClick = event => {\n const { form } = event.target;\n if (form === undefined) {\n return;\n }\n\n const { mode: modeId, value: valueId, output: outputId } = target.dataset;\n const mode = form.elements[modeId]?.value;\n const value = form.elements[valueId]?.value;\n const output = document.getElementById(outputId);\n if (mode === undefined || value === undefined || output === undefined) {\n return;\n }\n\n const list = options[value];\n const f = list[`${mode}Item`];\n if (f === undefined) {\n return;\n }\n\n output.innerHTML = f();\n}\n\nfor (const button of document.querySelectorAll('[data-my-widget]')) {\n button.addEventListener('click', handleClick);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T14:44:56.360",
"Id": "493933",
"Score": "0",
"body": "Would it be within the bounds of editing to add my html and remaining JavaScript to the bottom of my original post? Since this post is blowing up, I'd like everyone to get the full story."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T15:29:26.460",
"Id": "493942",
"Score": "1",
"body": "You should be able to add the HTML without invalidating our answers - it would likely be akin to [this scenario on meta](https://codereview.meta.stackexchange.com/a/6042/120114)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T16:29:00.577",
"Id": "493955",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ I made the edit, but it was quickly reversed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T16:30:48.513",
"Id": "493956",
"Score": "1",
"body": "Yes we are discussing it [in chat](https://chat.stackexchange.com/rooms/8595/the-2nd-monitor)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T17:10:30.740",
"Id": "493960",
"Score": "1",
"body": "Hey! Just so you know, my answer is not invalidated by your HTML. you can refer to the form specifically using the `form` attribute on a button, ie `<button form=\"thingSelection1\">`, as long as you change `<form name>` to `<form id>`. It'll still work!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T11:57:01.250",
"Id": "251010",
"ParentId": "250962",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "250968",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T15:46:08.500",
"Id": "250962",
"Score": "8",
"Tags": [
"javascript",
"html",
"error-handling",
"ecmascript-6",
"null"
],
"Title": "Error solution: Uncaught TypeError"
}
|
250962
|
<p>I have a program for finding shortest distance/path and I got a correct answer but I am getting an issue i.e., "Function 'shortestPath' has a complexity of 9. Maximum allowed is 6." This is the algorithm:</p>
<pre><code>const graph = {
start: { A: 5, D: 8 },
A: { B: 9, C: 3 },
D: { C: 4, E: 6 },
C: { B: 5, E: 2 },
B: { end: 7 },
E: { end: 4 },
end: {}
};
function shortestCostNode(costs, processed) {
return Object.keys(costs).reduce((lowest, node) => {
if (lowest === null || costs[node] < costs[lowest]) {
if (!processed.includes(node)) {
lowest = node;
}
}
return lowest;
}, null);
}
// this function returns the minimum cost and path to reach end
function shortestPath(graph) {
// track lowest cost to reach each node
const costs = Object.assign({ end: Infinity }, graph.start);
const parents = { end: null };
for (let child in graph.start) {
parents[child] = 'start';
}
const processed = [];
let node = shortestCostNode(costs, processed);
while (node) {
let cost = costs[node];
let children = graph[node];
for (let n in children) {
if (children.hasOwnProperty(n)) {
let newCost = cost + children[n];
if (!costs[n] || costs[n] > newCost) {
costs[n] = newCost;
parents[n] = node;
}
}
}
processed.push(node);
node = shortestCostNode(costs, processed);
}
let optimalPath = ["end"];
let parent = parents.end;
while (parent) {
optimalPath.push(parent);
parent = parents[parent];
}
optimalPath.reverse();
const result = {
distance: costs.end,
path: optimalPath
};
return result;
}
</code></pre>
<p>How to reduce complexity of Function <code>shortestPath</code>?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T16:24:11.670",
"Id": "493828",
"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-10-21T20:20:53.340",
"Id": "493862",
"Score": "0",
"body": "Also, code not working as expected is **off-topic** on code review, once you have fully working code, feel free to post it here"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T17:22:40.500",
"Id": "494087",
"Score": "0",
"body": "Is this a [programming challenge](https://codereview.stackexchange.com/tags/programming-challenge/info)? If so, please [edit] to include a link to the challenge along with the main description (perhaps with more sample inputs/outputs) and add that [tag:programming-challenge] tag"
}
] |
[
{
"body": "<h3><code>const</code> vs <code>let</code></h3>\n<p>First I would like to applaud the use of <code>const</code> in some places. There are however places where <code>const</code> could be used instead of <code>let</code> - e.g. for <code>optimalPath</code>, since it never gets re-assigned. It is advised to default to using <code>const</code> and then switch to <code>let</code> when re-assignment is deemed necessary. This helps avoid <a href=\"https://softwareengineering.stackexchange.com/a/278653/244085\">accidental re-assignment and other bugs</a>.</p>\n<h3>Adding to <code>optimalPath</code></h3>\n<p>Instead of calling <code>push()</code> to add items to <code>optimalPath</code> and then calling <code>reverse</code>, the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift\" rel=\"nofollow noreferrer\"><code>unshift()</code> method</a> can be used to add items to the beginning of the array, which eliminates the need to reverse the array.</p>\n<h3>Iterating in <code>shortestCostnode()</code></h3>\n<p>Note the MDN documentation for <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce\" rel=\"nofollow noreferrer\"><code>Array.prototype.reduce()</code></a> - for parameter <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#Parameters\" rel=\"nofollow noreferrer\"><code>initialValue</code></a></p>\n<blockquote>\n<p><em><strong>initialValue</strong></em> <code>Optional</code><br>\nA value to use as the first argument to the first call of the <em><code>callback</code></em>. If no <em><code>initialValue</code></em> is supplied, the first element in the array will be used as the initial <em><code>accumulator</code></em> value and skipped as <em><code>currentValue</code></em>. Calling reduce() on an empty array without an <em><code>initialValue</code></em> will throw a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError\" rel=\"nofollow noreferrer\"><code>TypeError</code></a>.</p>\n</blockquote>\n<p>This means that instead of passing <code>null</code> for the initial value, the value could be omitted in order to use the first value as the initial value of <code>lowest</code> and it would skip that first iteration. This would then eliminate the need to check <code>lowest === null</code> in that <code>if</code> condition.</p>\n<h3>Memoization</h3>\n<p>A possible optimization is to memoize results - e.g. if <code>shortestCostNode()</code> ever gets called with duplicate arguments then store the computed return value so it can be looked up on subsequent calls and returned without needing to re-compute the value.</p>\n<h3>Iterating over children items</h3>\n<p>For the loop within the <code>while</code> loop</p>\n<blockquote>\n<pre><code>for (let n in children) {\n</code></pre>\n</blockquote>\n<pre><code> if (children.hasOwnProperty(n)) {\n</code></pre>\n<p>consider using a <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\"><code>for...of</code></a> loop combined with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries\" rel=\"nofollow noreferrer\"><code>Object.entries(children)</code></a></p>\n<p>Then there is no need to check if the property exists in <code>children</code> (instead of higher up in the prototype chain)</p>\n<pre><code>for (const [n, child] of Object.entries(children)) {\n</code></pre>\n<p>That uses <code>const</code> instead of `let because the values don't need to be re-assigned within the loop.</p>\n<p>A more appropriate name for <code>n</code> would be <code>key</code>:</p>\n<pre><code>for (const [key, child] of Object.entries(children)) {\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T18:31:48.997",
"Id": "250974",
"ParentId": "250965",
"Score": "1"
}
},
{
"body": "<h2>Cyclomatic complexity</h2>\n<p>is a measure of the number of possible paths thorough some code. For example an <code>if</code> statement with one clause eg <code>if (foo) {}</code> has two paths, One if foo is true and one if false. Any point where the code can branch, the branches are counted as part of the cyclomatic complexity.</p>\n<p>Unfortunately how the complexity is summed differs so without knowing how the metric was calculated there is no easy way to give an answer. The best you can do is reduce the number of possible branches in the code.</p>\n<h2>Improving the code</h2>\n<p>Looking at your code and there is plenty of room to reduce the number of branches.</p>\n<p>The function <code>shortestCostNode</code> is not needed as the shortest link in a node has no influence on the final result. The shortest link may well move you to the longest path. Searching for the shortest link is no improvement on picking nodes sequentially.</p>\n<p><code>shortestCostNode</code> is the major source of complexity in your solution, it effectively randomizes your search. Because of this you must track which path you have traveled so you don't end up repeating the same path, this adds a lot of baggage.</p>\n<p>If you systematically search all possible paths in order (keeping track of where you have not been) you eliminate the need to track where you have been and can thus remove a lot of code.</p>\n<h2>Use a stack to search a tree</h2>\n<p>As the search for the shortest path involves traveling along paths and then backtracking to the nearest untraveled branch a stack is the best way to keep track of your progress.</p>\n<p>You start at a node, push all paths and the cost so far to a stack, then pop one path and move along that path to the next node adding the cost as you do. Then do the same for the next node.</p>\n<p>When you reach an end node you then check the distance and if it is the shortest so far you save that distance and the path traveled. Then pop the next path step from the stack until all paths have been checked.</p>\n<h2>A Recursive stack</h2>\n<p>The simplest (but not the quickest) way to implement a stack is via recursion.</p>\n<p>Thus you end up with a function something like</p>\n<pre><code>function shortestPath(graph) {\n const result = {distance: Infinity}, endName = "end";\n function followPath(node, totalDist = 0, path = ["start"]) {\n for (const [name, length] of Object.entries(node)) {\n const distance = totalDist + length;\n if (distance < result.distance) {\n if (name === endName) { \n Object.assign(result, {distance, path: [...path, endName]}); \n } else {\n path.push(name);\n followPath(graph[name], distance, path);\n path.pop();\n }\n }\n }\n }\n followPath(graph.start);\n return result;\n}\n</code></pre>\n<p>The function has a Cyclomatic complexity of about 5.</p>\n<p>Note that the function only follows paths while the distance traveled is less than the shortest path found already found. This means that you may not need to check all paths to the end.</p>\n<p>There is also plenty of room for improvement (in terms of complexity and performance), but as you have not defined much about the graphs possible structure there is no point going any further,.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T22:30:53.353",
"Id": "251043",
"ParentId": "250965",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T16:01:36.620",
"Id": "250965",
"Score": "3",
"Tags": [
"javascript",
"functional-programming",
"ecmascript-6",
"complexity",
"iteration"
],
"Title": "Cyclomatic Complexity (complexity)"
}
|
250965
|
<p>My code is</p>
<pre><code>void utf8_append(UChar32 cp, std::string& str) {
size_t offset = str.size();
str.resize(offset + U8_LENGTH(cp));
auto ptr = reinterpret_cast<uint8_t*>(&str[0]);
U8_APPEND_UNSAFE(ptr, offset, static_cast<uint32_t>(cp));
}
</code></pre>
<p>This works but seems ugly. Maybe I am overlooking a simpler approach?</p>
<p>Relevant documentation: <a href="https://unicode-org.github.io/icu/userguide/strings/utf-8.html" rel="nofollow noreferrer">https://unicode-org.github.io/icu/userguide/strings/utf-8.html</a> and <a href="https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/utf8_8h.html" rel="nofollow noreferrer">https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/utf8_8h.html</a>.</p>
|
[] |
[
{
"body": "<p>Beauty is in the eye of the beholder. I say it is perfectly valid and correct code! The only thing you might get rid of is the <code>static_cast<uint32_t></code>, as an <code>UChar32</code>, which is an alias for<code>int32_t</code>, will implicitly cast to <code>uint32_t</code> without warnings.\nYou could also use <code>append()</code> instead of <code>resize()</code>, avoiding the addition, and remove the temporary <code>ptr</code>, to finally get:</p>\n<pre><code>void utf8_append(UChar32 cp, std::string& str) {\n auto offset = str.size();\n str.append(U8_LENGTH(cp), {});\n U8_APPEND_UNSAFE(reinterpret_cast<uint8_t *>(&str[0]), offset, cp);\n}\n</code></pre>\n<p>If you can use C++17, <code>str.data()</code> is slightly nicer than <code>&str[0]</code> in my opinion. Or you could write <code>&str.front()</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T18:37:15.427",
"Id": "493835",
"Score": "0",
"body": "\"without warnings\" Not with this project's warning settings. And no C++17, unfortunately."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T18:48:13.510",
"Id": "493837",
"Score": "0",
"body": "Ah ok. Well if they are that strict then you're stuck with the `static_cast` of course. You could consider using `std::basic_string<uint8_t>` to get rid of both casts, but it will probably open up a can of worms elsewhere in your codebase."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T18:19:32.027",
"Id": "250973",
"ParentId": "250967",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "250973",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T16:46:31.537",
"Id": "250967",
"Score": "3",
"Tags": [
"c++",
"unicode"
],
"Title": "Appending a codepoint to an UTF8 std::string using icu4c"
}
|
250967
|
<p>I've been working on a solution that allows a set of buttons to reveal divs that slide down from above on-click. I needed each button to toggle an active state for itself, but also if the user were to click on one button, reveal a div, and then go on to click another button, that the initially revealed div transition back up and dissapear while the new one appears.</p>
<p>When all the buttons are on one line, my solution works relatively well. But when there are buttons below some of the hidden divs, suddenly the divs those buttons trigger appear from below instead of dropping down from above... IF one of the buttons above has an active state... If not, business as usual.</p>
<p>Appologies if this is confusing, please see my fiddle : <a href="https://jsfiddle.net/maesj_/qdk4z1vm/26/" rel="noreferrer">https://jsfiddle.net/maesj_/qdk4z1vm/26/</a></p>
<p>My solution is an adaptation of a demo <a href="https://css-tricks.com/using-css-transitions-auto-dimensions/" rel="noreferrer">that I found on css-tricks</a> adressing a similar kind of situation, but in my case having mutliple buttons has added a bit more complexity to the mix and I'm wondering if anyone has any ideas on how I might improve my code.</p>
<p>Any thoughts are much appreciated!</p>
<p><strong>HTML</strong></p>
<pre><code><button class="dyn-gallery-btn" type="button"> one </button>
<button class="dyn-gallery-btn" type="button"> two </button>
<div class="dyn-slide"> one text
</div>
<div class="dyn-slide"> two text
</div>
<button class="dyn-gallery-btn" type="button"> three </button>
<button class="dyn-gallery-btn" type="button"> four </button>
<div class="dyn-slide"> three text
</div>
<div class="dyn-slide"> four text
</div>
</code></pre>
<p><strong>CSS</strong></p>
<pre><code>.dyn-slide {
background: red;
transition: height .5s ease-in-out;
height: 0;
overflow: hidden;
}
.dyn-slide.active {
height: auto;
overflow: hidden;
}
.dyn-slide:not(.active) {
height: 0;
overflow: hidden;
}
</code></pre>
<p><strong>JS</strong></p>
<pre><code>const slides = document.querySelectorAll('.dyn-slide')
const buttons = document.querySelectorAll('.dyn-gallery-btn')
buttons.forEach((button, i) => {
button.addEventListener('click', () => {
const slide = slides[i]
const wasActive = slide.classList.contains('active')
slides.forEach(slide => {
slide.classList.remove('active')
slide.style.height = 0;
})
if (!wasActive) {
slide.classList.add('active')
slide.style.height = 'auto';
var height = slide.clientHeight + 'px';
slide.style.height = '0px';
setTimeout(function () {
slide.style.height = height;
}, 0);
} else {
var height = slide.clientHeight + 'px';
slide.style.height = '0px';
setTimeout(function () {
slide.style.height = 0;
}, 0);
}
})
})
</code></pre>
|
[] |
[
{
"body": "<p><strong>Redundant CSS</strong> The rules in <code>.dyn-slide:not(.active)</code> already exist in the <code>.dyn-slide</code> block, so they're not needed - feel free to remove them entirely. (The <code>.dyn-slide.active { height: auto;</code> isn't being used either, since the height is being set directly via JS)</p>\n<p><strong>Semicolons or not?</strong> To be stylistically consistent and to reduce bugs, either use semicolons everywhere they're appropriate, or (if you consider yourself skilled enough not to run into <a href=\"https://stackoverflow.com/questions/2846283/what-are-the-rules-for-javascripts-automatic-semicolon-insertion-asi\">problems with ASI</a>) don't use semicolons. Choose a style you want, then <a href=\"https://eslint.org/docs/rules/semi\" rel=\"nofollow noreferrer\">enforce it</a>.</p>\n<p><strong>Use <code>const</code>, avoid <code>var</code></strong> - you're using modern syntax, which is great, but you're using <code>var</code> in a few places. In ES2015+, best to always use <code>const</code> (or, if you need to reassign, <code>let</code>), but <code>var</code> <a href=\"https://airbnb.io/javascript/#references--prefer-const\" rel=\"nofollow noreferrer\">isn't a great idea</a> - it has weird rules like function scope instead of block scope, and automatically assigns its variables to the global object when used on the top level, among other weirdness. (ESLint rule: <a href=\"https://eslint.org/docs/rules/no-var\" rel=\"nofollow noreferrer\"><code>no-var</code></a>, I highly recommend using a linter to automatically prompt you to fix code quality smells)</p>\n<p><strong>Unused variable</strong> You do</p>\n<pre><code>} else {\n var height = slide.clientHeight + 'px';\n</code></pre>\n<p>but never use the <code>height</code> variable - remove it. (ESLint rule: <a href=\"https://eslint.org/docs/rules/no-unused-vars\" rel=\"nofollow noreferrer\"><code>no-unused-vars</code></a>)</p>\n<p><strong>Whole <code>else</code> block is redundant</strong> Or, remove the whole block there: the element's height has been set to 0 at the beginning of the function, so setting it to 0 again won't change anything.</p>\n<p>You can <strong>save the last active slide</strong> in a variable instead of looping over all slides at the beginning of the click handler.</p>\n<p><strong>Trigger reflow instead of using <code>setTimeout</code></strong> Rather than <code>setTimeout</code>, you can trigger a DOM reflow by reading a style property from the DOM, for example, access the <code>offsetHeight</code> of an element. This allows you to code synchronously:</p>\n<p><strong>Indentation</strong> Some of your indented blocks are not properly aligned. Consider using an IDE to automatically indent correctly - this'll make it easier for you and others to understand the code at a glance.</p>\n<p>Refactored:</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 slides = document.querySelectorAll('.dyn-slide');\nconst buttons = document.querySelectorAll('.dyn-gallery-btn');\nlet lastSlide;\n\nbuttons.forEach((button, i) => {\n button.addEventListener('click', () => {\n const slide = slides[i];\n const wasActive = slide.classList.contains('active');\n if (lastSlide) {\n lastSlide.classList.remove('active');\n lastSlide.style.height = 0;\n }\n lastSlide = slide;\n if (wasActive) {\n return;\n }\n slide.classList.add('active');\n slide.style.height = 'auto';\n const newHeight = slide.clientHeight + 'px';\n slide.style.height = '0px';\n slide.offsetHeight; // Force a reflow\n slide.style.height = newHeight;\n })\n})</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.dyn-slide {\n background: red;\n transition: height .5s ease-in-out;\n height: 0;\n overflow: hidden;\n}\n\n.dyn-slide.active {\n /* Height will be set to either auto or 0 by JS */\n overflow: hidden;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><button class=\"dyn-gallery-btn\" type=\"button\"> one </button>\n<button class=\"dyn-gallery-btn\" type=\"button\"> two </button>\n\n<div class=\"dyn-slide\"> one text\n</div>\n\n<div class=\"dyn-slide\"> two text\n</div>\n\n<button class=\"dyn-gallery-btn\" type=\"button\"> three </button>\n<button class=\"dyn-gallery-btn\" type=\"button\"> four </button>\n\n<div class=\"dyn-slide\"> three text\n</div>\n\n<div class=\"dyn-slide\"> four text\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T19:25:07.587",
"Id": "493976",
"Score": "1",
"body": "You write \"...and automatically assigns its variables to the global object,\" What?, The linked article \"isn't a great idea\" is misinformed and should be removed Some corrections 1 Variables declared with `let` and `const` can be in global scope. 2 `let` and `const` are NOT function scoped as they are not hoisted and can not be accessed before declaration. 3 `var` can be declared outside functions and not be in the global scope eg within a module. 4 No mention of strict mode, modules, or hosting and how they affect the behavior of declarations. ...To name a few"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T19:38:44.937",
"Id": "493978",
"Score": "0",
"body": "Oops, I missed adding \"when declared on the top level\". Yeah, the article is pretty sloppy, I just googled and linked to the first result that looked reasonable on the surface. I'll point to AirBnB instead. But the point is still solid, when writing clean, readable code, `const` should be preferred over `var` by far."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T11:30:09.680",
"Id": "496172",
"Score": "0",
"body": "Thank you !! This was super helpful, I was able to clean up my code and get everything working. Really appreciate it! :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T18:47:12.483",
"Id": "250977",
"ParentId": "250970",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T17:56:09.917",
"Id": "250970",
"Score": "6",
"Tags": [
"javascript",
"css",
"animation"
],
"Title": "Vanilla JS/CSS -- set of buttons to trigger sliders by transitioning height value"
}
|
250970
|
<p><a href="https://codepen.io/Destroyer99/pen/jOrVbGW" rel="nofollow noreferrer">code</a></p>
<p>It is necessary from this piece of code</p>
<pre><code>const rectPos = { x: 0, y: 0 };
const currPos = { x: 0, y: 0 };
const mouseEvent = () => {
canvas.onmousedown = (e) => {
const start = { x: e.offsetX, y: e.offsetY };
canvas.onmousemove = (e) => {
currPos.x = getXPixelRatio * Math.round((rectPos.x + e.offsetX - start.x) / getXPixelRatio);
currPos.y = getYPixelRatio * Math.round((rectPos.y + e.offsetY - start.y) / getYPixelRatio);
currPos.x = edge(currPos.x, 0, w - 25);
currPos.y = edge(currPos.y, 0, h - 25);
renderAll()
drawRect(currPos.x, currPos.y);
}
document.onmouseup = (e) => {
rectPos.x = currPos.x;
rectPos.y = currPos.y;
canvas.onmousemove = null
}
}
}
</code></pre>
<p>It is necessary to separate the event handler and the function itself</p>
<p>Something like this</p>
<pre><code>const mouseDown = () =>{}
const mouseMove = () =>{}
const mouseUp = () =>{}
function mouseEvents() {
canvas.addEventListiner("mousedown", mousedown)
....
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T18:40:06.670",
"Id": "250975",
"Score": "1",
"Tags": [
"javascript",
"canvas"
],
"Title": "Improving the code, events in individual functions (refactoring)"
}
|
250975
|
<p>For practicing designing systems I created a simple bank ATM system.</p>
<p>I didn't want to make it to complicated so I left out things like cash bin per ATM and opening cash trays, etc. I also wanted to neglect APIs to validate pins, etc. (it's just a function that will always return True). I wanted to focus on classes and methods.</p>
<p>So in my example I have</p>
<ul>
<li>an <code>Account</code> class which has an account number, a balance and withdraw and deposit functions.</li>
<li>a <code>Card</code> class which has accounts and a select account function which will search for the account number on the card and then return it.</li>
<li>an <code>ATM</code> class which has the following variables: <code>card_inserted</code>, <code>card_validated</code>, <code>current_account</code>, <code>current_card</code> and the main function are <code>perform_request</code> (which will either give out the balance, deposit or withdraw money), <code>validate_pin</code> (which will make the call to the API, mocked in my code), <code>select_account</code> (which will select an account from the card)</li>
</ul>
<p>I did write a test for it and it worked. I was wondering if I could get some feedback on that (not the test, I know I can do lot's of things to make the tests better but that was just a quick and dirty version of it)?</p>
<p>atm.py:</p>
<pre><code>def validate_api(card_nr, pin):
# validate account nr and pin
# return true or fale
return True
class Card():
def __init__(self, accounts = []):
self.accounts = accounts
def select_account(self, account_nr):
# check if there is a built in filter func in python
for account in self.accounts:
if account.account_nr == account_nr:
return account
raise Exception("Account number invalid")
class Account():
def __init__(self, account_nr = None):
self.account_nr = account_nr
self.balance = 0
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
self.balance -= amount
class ATM():
def __init__(self):
self.card_inserted = False
self.card_validated = False
self.current_account = None
self.current_card = None
def validate_card_and_pin(self):
if not self.card_inserted:
raise Exception('Card must be inserted first')
if self.card_validated is False:
raise Exception
# raise Exception("Card not validated")
def insert_card(self, bank_card):
# code to accept card
self.card_inserted = True
self.current_card = bank_card
def eject_card(self):
self.end_session()
# code to push card out
def validate_pin(self, pin):
if not self.card_inserted:
raise Exception('Card must be inserted first')
# card is inserted, pin has to be validated
# post pin and card number to api
# response will be saved in validated variable
validated = validate_api(card_nr=0,pin=0)
if validated == False:
self.card_validated = False
return self.card_validated
self.card_validated = True
return self.card_validated
def select_account(self, account_nr):
self.validate_card_and_pin()
if self.current_card is None:
raise Exception("no card in ATM")
if self.card_validated is False:
raise Exception("card not validated")
current_account = self.current_card.select_account(account_nr)
self.current_account = current_account
'''
1 = check balance
2 = deposit money
3 = withdraw money
'''
def perform_request(self, request, amount = 0):
self.validate_card_and_pin()
if request == 1:
return self.check_balance()
elif request == 2:
return self.accept_cash(amount)
elif request == 3:
return self.give_out_cash(amount)
else:
raise Exception("invalid request")
def accept_cash(self, amount):
# open cash tray
# count cash
self.current_account.deposit(amount)
return amount
def give_out_cash(self, amount):
# count cash
# open tray
self.current_account.withdraw(amount)
return amount
def check_balance(self):
return self.current_account.balance
def end_session(self):
self.card_inserted = False
self.card_validated = False
self.current_account = None
self.current_card = None
return True
</code></pre>
<p>And here the test:</p>
<pre><code> def test_depositing_50_and_withdrawing_20():
checking = Account(1)
saving = Account(2)
bank_card = Card([checking, saving])
atm = ATM()
atm.insert_card(bank_card)
atm.validate_pin("123")
atm.select_account(1)
atm.perform_request(2, 50)
if atm.perform_request(1) is not 50:
raise Exception("depositing function doesn't work")
atm.end_session()
atm.insert_card(bank_card)
atm.validate_pin("123")
atm.select_account(1)
atm.perform_request(3, 20)
if atm.perform_request(1) is not 30:
raise Exception("withdrawing function doesn't work")
atm.select_account(2)
atm.validate_pin("123")
atm.perform_request(2, 10)
if atm.perform_request(1) is not 10:
raise Exception("depositing function doesn't work")
print("Test successful")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T07:27:16.670",
"Id": "493902",
"Score": "1",
"body": "On another level I would like to add that banks don't keep track of a balance by editing a single value. Instead they use a form of [event sourcing](https://eventsourcing.readthedocs.io/en/stable/topics/introduction.html#what-is-event-sourcing) to keep track of all changes as well and use the event sourcing to calculate what the resulting balance should be."
}
] |
[
{
"body": "<pre><code>class Card():\n</code></pre>\n<p>You don't need parenthesis in the class declarations. Also, while most of your formatting is pretty good, there's a couple nitpicky things. When supplying a default argument, <a href=\"https://www.python.org/dev/peps/pep-0008/#other-recommendations\" rel=\"nofollow noreferrer\">there shouldn't be spaces around the <code>=</code></a>, and there <a href=\"https://www.python.org/dev/peps/pep-0008/#blank-lines\" rel=\"nofollow noreferrer\">should be two blank lines between top-level definitions</a>.</p>\n<hr />\n<p>You should really <a href=\"https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument\">never have a mutable default parameter</a> like you do in:</p>\n<pre><code>def __init__(self, accounts = []):\n</code></pre>\n<p>In this case, since you never modify <code>self.accounts</code>, you're safe. If you ever added an <code>add_account</code> method that associated an account with a card by <code>append</code>ing to <code>self.accounts</code>, you'd see that every <code>Card</code> in your program that was created using the default argument would change when that method is run.</p>\n<p>I'd change it to:</p>\n<pre><code>def __init__(self, accounts=None): # Default to None\n self.accounts = accounts or [] # then create the list inside the method instead\n</code></pre>\n<hr />\n<pre><code># check if there is a built in filter func in python\n</code></pre>\n<p>There are multiple ways of using some fancy shortcut function to find the first element that satisfies a predicate, but honestly, I'd just stick to what you have. A <code>for</code> loop with an early return is pretty easy to understand. Since you want to raise an exception if an account isn't found, the other ways get a little bit sloppy. If you were fine having it return <code>None</code> on an error, you could use:</p>\n<pre><code>def select_account(self, account_nr):\n return next((account for account in self.accounts if account.account_nr == account_nr), None)\n</code></pre>\n<p><code>next</code> attempts to grab the first element of an iterator that you give it. I'm giving it a generator expression, that will produce an element only if <code>account.account_nr == account_nr</code> is true. The <code>None</code> as the second argument is a default value if nothing is found. I still prefer the iterative <code>for</code> style though.</p>\n<hr />\n<p>In <code>Account</code>, you're allowing <code>None</code> to be used as an account number. This strikes me as the kind of field that should not be "nullable", or be allowed to be omitted when creating an object. I think a (unique, existing) account number is pretty fundamental to the idea of a bank account. I would get rid of the default and force the user to supply that information when creating an account. It may be helpful though to have a second <code>starting_balance</code> parameter that lets the user to set the starting account balance, and allow that to default to <code>0</code>.</p>\n<hr />\n<p><code>validate_card_and_pin</code> is a misleading name. It doesn't seem to do the validations. It expects that the validations have already been done and that the internal <code>self.card_validated</code> state is already set. <code>assert_is_validated</code> may be a better name for what it's doing.</p>\n<hr />\n<p>I think <code>validate_pin</code> could be made clearer. Note how a lot of the code at the bottom is duplicated. You're setting <code>card_validated</code> to whatever <code>validated</code> is, then returning that value. The function can be simply:</p>\n<pre><code>def validate_pin(self, pin):\n if not self.card_inserted:\n raise Exception('Card must be inserted first')\n \n self.card_validated = validate_api(card_nr=0,pin=0)\n return self.card_validated\n</code></pre>\n<hr />\n<p>I'd maybe rethink throwing exceptions from the methods. In my eyes, a PIN being entered wrong for example isn't really <em>exceptional</em>. I'm a fan of returning <code>None</code> as a error indicator in cases where a function can only fail in one way; like <code>validate_pin</code>. You just have to be in the habit of identifying when a function returns <code>None</code>, and handling that case properly.</p>\n<p>If you do want to use exceptions though, throwing a plain <code>Exception</code> is a bad idea. This makes it more difficult for the caller to catch and handle specifically exceptions from your code. I think this is an appropriate case to create <a href=\"https://stackoverflow.com/questions/1319615/proper-way-to-declare-custom-exceptions-in-modern-python\">custom exceptions</a>. Something like:</p>\n<pre><code>class PINValidationFailed(RuntimeError):\n pass\n</code></pre>\n<p>Then the caller can catch specifically that exception to handle PIN failures.</p>\n<hr />\n<pre><code>'''\n1 = check balance\n2 = deposit money\n3 = withdraw money\n'''\ndef perform_request(self, request, amount = 0):\n</code></pre>\n<p>If that's intended as a docstring, it needs to be inside the function and indented:</p>\n<pre><code>def perform_request(self, request, amount=0):\n '''\n 1 = check balance\n 2 = deposit money\n 3 = withdraw money\n '''\n</code></pre>\n<hr />\n<p>I think <code>if self.card_validated is False:</code> is clearer as simply <code>if not self.card_validated:</code>.</p>\n<hr />\n<p>After touching this up, I'm left with:</p>\n<pre><code>def validate_api(card_nr, pin):\n # validate account nr and pin\n # return true or false\n return True\n\n\nclass Card:\n def __init__(self, accounts=None):\n self.accounts = accounts or []\n\n def select_account(self, account_nr):\n return next((account for account in self.accounts if account.account_nr == account_nr), None)\n\n\nclass Account:\n def __init__(self, account_nr, starting_balance=0):\n self.account_nr = account_nr\n self.balance = starting_balance\n\n def deposit(self, amount):\n self.balance += amount\n\n def withdraw(self, amount):\n self.balance -= amount\n\n\nclass ATM:\n def __init__(self):\n self.card_inserted = False\n self.card_validated = False\n self.current_account = None\n self.current_card = None\n\n def validate_card_and_pin(self):\n if not self.card_inserted:\n raise RuntimeError('Card must be inserted first')\n\n if not self.card_validated:\n raise RuntimeError("Card not validated")\n\n def insert_card(self, bank_card):\n # code to accept card\n self.card_inserted = True\n self.current_card = bank_card\n\n def eject_card(self):\n self.end_session()\n # code to push card out\n\n def validate_pin(self, pin):\n if not self.card_inserted:\n raise RuntimeError('Card must be inserted first')\n\n self.card_validated = validate_api(card_nr=0, pin=0)\n return self.card_validated\n\n\n def select_account(self, account_nr):\n self.validate_card_and_pin()\n if self.current_card is None:\n raise RuntimeError("no card in ATM")\n\n if self.card_validated is False:\n raise RuntimeError("card not validated")\n\n current_account = self.current_card.select_account(account_nr)\n self.current_account = current_account\n\n\n def perform_request(self, request, amount=0):\n '''\n 1 = check balance\n 2 = deposit money\n 3 = withdraw money\n '''\n self.validate_card_and_pin()\n if request == 1:\n return self.check_balance()\n elif request == 2:\n return self.accept_cash(amount)\n elif request == 3:\n return self.give_out_cash(amount)\n else:\n raise RuntimeError("invalid request")\n\n def accept_cash(self, amount):\n # open cash tray\n # count cash\n self.current_account.deposit(amount)\n return amount\n\n def give_out_cash(self, amount):\n # count cash\n # open tray\n self.current_account.withdraw(amount)\n return amount\n\n def check_balance(self):\n return self.current_account.balance\n\n def end_session(self):\n self.card_inserted = False\n self.card_validated = False\n self.current_account = None\n self.current_card = None\n return True\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T22:55:02.243",
"Id": "493876",
"Score": "0",
"body": "dude, thank you so much! this is exactly what I wanted to know, I don't have much experience with stuff like that, thank you for taking the time to answer so detail oriented, especially for the nitpicking syntax stuff! I was also thinking if there is a better way to do `assert_is_validated`, was reading about decorators, is this something I could use here?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T23:03:24.667",
"Id": "493877",
"Score": "1",
"body": "@Tom No problem. Glad to help. Hopefully someone with a more OOP background can make comments about that aspect."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T23:08:06.360",
"Id": "493878",
"Score": "1",
"body": "@Tom If you want to have it set up where you're just checking the state of the object before allowing something to happen, I don't think having an `assert-thing` function at the top of the method is *necessarily* bad. I've certainly done it, and I've seen it done in standard libraries."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T23:10:15.500",
"Id": "493879",
"Score": "1",
"body": "@Tom [Here](https://github.com/carcigenicate/AI/blob/11b706866c95a7512c51da5e096a22a5e31b664a/src/ai_retry/genetic_algorithm/sequence.clj#L42) is actually an example of me doing it awhile ago (`check-gene-compatibility`). Note I use it in `breed` right below that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T23:14:38.350",
"Id": "493880",
"Score": "0",
"body": "ahhh okk, thank you!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T22:42:22.143",
"Id": "250988",
"ParentId": "250982",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "250988",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T21:15:04.133",
"Id": "250982",
"Score": "5",
"Tags": [
"python-3.x",
"object-oriented"
],
"Title": "Simple bank-atm system design OOP"
}
|
250982
|
<p>I'm learning ASP.NET and I've created a few simple APIs, so I can consider myself maybe an intermediate beginner.</p>
<p>I've decided to create a tutorial serving two purposes: to solidify what I've learned and to fulfil a demand for beginner tutorials in my language.</p>
<p>I just created a very simple API with CRUD functionalities and I'd like you to review it. I've purposefully not used Repository Pattern and DTOs because they can be confusing for someone that's just getting started (at least that was my experience). But I do plan to add those on the next phase, along with validation and error handling.</p>
<p>Please tear everything apart, I need all possible feedback as I need to understand every line of the code I write.</p>
<p>Controller:</p>
<pre><code> [ApiController]
[Route("api/records")]
public class RecordsController : ControllerBase
{
private readonly DataContext _context;
public RecordsController(DataContext context)
{
_context = context;
}
[HttpGet]
public ActionResult<IEnumerable<Record>> GetRecords()
{
return _context.Records.ToList();
}
[HttpGet("{id}")]
public ActionResult<Record> GetRecordById(int id)
{
return _context.Records.Find(id);
}
[HttpPost]
public ActionResult<Record> AddRecord([FromBody] Record record)
{
_context.Records.Add(record);
_context.SaveChanges();
return Ok();
}
[HttpDelete("{id}")]
public ActionResult<Record> DeleteRecord(int id)
{
var recordForDeletion = _context.Records.FirstOrDefault(r => r.Id == id);
_context.Records.Remove(recordForDeletion);
_context.SaveChanges();
return Ok();
}
[HttpPut("{id}")]
public ActionResult<Record> UpdateRecord(int id, [FromBody] Record record)
{
var recordForUpdate = _context.Records.FirstOrDefault(r => r.Id == id);
recordForUpdate.Date = record.Date;
recordForUpdate.Name = record.Name;
recordForUpdate.Value = record.Value;
recordForUpdate.Category = record.Category;
recordForUpdate.Type = record.Date;
_context.SaveChanges();
return Ok();
}
}
}
</code></pre>
<p>DataContext</p>
<pre><code>public class DataContext : DbContext
{
public DataContext(DbContextOptions<DataContext> options) : base(options) { }
public DbSet<Record> Records { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//seed database with dummy data
modelBuilder.Entity<Record>().HasData(
new Record()
{
Id = 1,
Date = "2020-09-30T00:00:01",
Name = "Coles",
Value = 20,
Category = "Groceries",
Type = "Expense"
},
new Record()
{
Id = 2,
Date = "2020-10-01T00:00:01",
Name = "Traslink",
Value = 30,
Category = "Transportation",
Type = "Expense"
},
new Record()
{
Id = 3,
Date = "2020-10-02T00:00:01",
Name = "Cafe 63",
Value = 22,
Category = "Eating Out",
Type = "Expense"
}
);
}
}
}
</code></pre>
<p>Startup:</p>
<pre><code> public class Startup
{
private readonly IConfiguration _config;
public Startup(IConfiguration config)
{
_config = config;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddDbContext<DataContext>(x =>
x.UseSqlite(_config.GetConnectionString("DefaultConnection")));
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T07:40:12.677",
"Id": "493903",
"Score": "4",
"body": "Keep your controllers lean: https://www.infoworld.com/article/3404472/how-to-write-efficient-controllers-in-aspnet-core.html"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T17:21:36.580",
"Id": "493961",
"Score": "1",
"body": "One minor thing I'd like to point out is the use of `FirstOrDefault`. If those are unique IDs (aka Primary Keys) in the data set, use `SingleOrDefault` to help enforce the expectation."
}
] |
[
{
"body": "<p>This implementation is quite far from a production-ready CRUD API. Just to name a few missing things:</p>\n<ul>\n<li>Presentation and Persistence layer separation\n<ul>\n<li>Controller should deal with HTTP related stuff, not with databases</li>\n</ul>\n</li>\n<li>Proper status code handling\n<ul>\n<li>(see the next section for more details)</li>\n</ul>\n</li>\n<li>Model validation</li>\n<li>Error handling\n<ul>\n<li>for example: what if database is not responding?</li>\n</ul>\n</li>\n<li>Pagination</li>\n<li>Taking advantage of async I/O operations\n<ul>\n<li>It can boost scalability</li>\n</ul>\n</li>\n<li>API versioning</li>\n<li>Documentation of the API\n<ul>\n<li>For example via OpenAPI</li>\n</ul>\n</li>\n<li>Authentication and Authorization</li>\n<li>Audit for modifications</li>\n<li>etc.</li>\n</ul>\n<hr />\n<p>Better utilization of status codes</p>\n<ul>\n<li>POST\n<ul>\n<li>If the <code>Id</code> is coming from the user and it should be unique (in order to able to do lookups) then what if the provided <code>Id</code> is already stored in the database? <strong>400 / 409</strong></li>\n<li>BTW <code>Id</code> should not come from the user. That's why it is a good practice to separate database models and API models</li>\n<li>In case of success the <strong>201</strong> is the suggested status code. The persisted resource could be sent back to the user inside the response body or the Location header should point to the new resource</li>\n</ul>\n</li>\n<li>GET\n<ul>\n<li>What if there is no record with the provided <code>Id</code>? <strong>404</strong></li>\n</ul>\n</li>\n<li>DELETE\n<ul>\n<li>Either <strong>204</strong> or <strong>404</strong> is used normally to indicate that a resource is gone</li>\n<li>Your current implementation fails if you try to delete a non-existing record</li>\n<li>Depending on your requirements you may or may not differentiate the deletion of existing and non-existing resources</li>\n</ul>\n</li>\n</ul>\n<p><a href=\"https://github.com/for-GET/http-decision-diagram\" rel=\"nofollow noreferrer\">Here you can find a poster</a>, which can help you to decide when to use which http status code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T21:23:47.423",
"Id": "493984",
"Score": "1",
"body": "Thank you for your answer!It provides a very good checklist to improve my app. My idea was to create an entry level api that does what it's supposed to do (the crud operations) so that the users of the tutorial have a sense of achievement quite quickly. I realised learning from tutorials that it took me weeks or even months (if I wanted to actually understand what was going on) to get something ready for production out of a tutorial. So I made something as simple as possible for someone who's starting. I'll make it clear in my tutorial that all those next steps are necessary in the industry :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T15:36:17.700",
"Id": "251026",
"ParentId": "250987",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T22:31:43.277",
"Id": "250987",
"Score": "2",
"Tags": [
"c#",
".net",
"asp.net",
"asp.net-core"
],
"Title": "Reviewing Basic API"
}
|
250987
|
<p>I was bothered with existing matrix allocation methods that take variable rows and columns, so I made a small class that only needs one memory allocation.</p>
<pre class="lang-cpp prettyprint-override"><code>
template <typename T>
class Matrix{
T* data;
size_t rows, columns;
public:
Matrix(const size_t rows, const size_t columns) : rows(rows), columns(columns) {
// One single allocation to store data
data = new T[rows+columns + 1];
}
T* operator[](const size_t r) {
return data+(r*columns);
}
};
// Example
int main() {
Matrix<int> mat(5,3);
mat[2][1] = 1;
//...
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T08:09:10.197",
"Id": "493904",
"Score": "0",
"body": "What aspects do you expect reviewers to go over?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T21:00:08.750",
"Id": "493983",
"Score": "0",
"body": "Lot missing from this. Have a look at my article on vectors. You should be able to apply the same principles to Matrix allocation. https://lokiastari.com/series/ You may also need to read up on how to overload `operator[]` for 2 dimensional array accesses https://stackoverflow.com/a/1971207/14065"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T07:18:06.123",
"Id": "494007",
"Score": "0",
"body": "@MartinYork Very nice article on your website, ill surely learn a lot from it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T18:35:46.767",
"Id": "494096",
"Score": "0",
"body": "Then there's the out-of-bounds memory access (caused because the memory allocated in the constructor is the wrong amount)."
}
] |
[
{
"body": "<ul>\n<li>Since you have the <code>new</code> keyword, you should make a destructor and <code>delete[]</code>.</li>\n</ul>\n<pre class=\"lang-cpp prettyprint-override\"><code>~Matrix()\n{\n delete[] data;\n data = nullptr;\n}\n</code></pre>\n<p>Note that it is not necessary to set <code>data = nullptr</code> in the destructor, because it will be deleted as soon as the destructor is called.</p>\n<ul>\n<li><p>You are missing a <a href=\"https://en.cppreference.com/w/cpp/language/copy_constructor\" rel=\"nofollow noreferrer\"><strong>copy constructor</strong></a> which can cause problems when assigning one matrix to another</p>\n</li>\n<li><p>What happens if the number passed in <code>[]</code> when slicing from the matrix is out of bounds?</p>\n</li>\n<li><p>Have a glance at <a href=\"https://en.cppreference.com/w/cpp/utility/initializer_list\" rel=\"nofollow noreferrer\"><strong>std::initialzer_list</strong></a> in C++, it will simplify assigning values to the matrix.</p>\n</li>\n<li><p>You will have to overload the arithmetic operators ( <code>+, -, *, /</code>) if you want to perform any kind of operations between two matrices</p>\n</li>\n<li><p>Lastly, I was a little confused to see <code>size_t</code> rather than <code>std::size_t</code>, if you have <code>using std::size_t</code> in your source code, you should have it here too to avoid confusion.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T10:53:26.587",
"Id": "493911",
"Score": "2",
"body": "You're correct about the need for a destructor, copy constructor and so on, but these things can all be avoided by using `std::vector<T> data`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T11:28:07.170",
"Id": "493914",
"Score": "1",
"body": "When you see something like this in the code `//...` it is better not to answer and flag it for community attention because the question is off-topic, missing review context."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T12:21:56.587",
"Id": "493918",
"Score": "1",
"body": "I agree with you people but maybe he missed his \" reinventing the wheel tag \" right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T16:09:43.883",
"Id": "494067",
"Score": "0",
"body": "@MartinYork I wasn't aware of this, can you link any site where I can read about it? I have removed that para so I hope its fine now"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T16:15:06.250",
"Id": "494068",
"Score": "0",
"body": "@AryanParekh: You can read a bunch of my code reviews here. :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T16:24:26.943",
"Id": "494071",
"Score": "0",
"body": "@MartinYork I'm not sure what you mean xD, I did read about variable shadowing, but isn't `rows(rows)` confusing? `this` makes it specific right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T16:38:06.327",
"Id": "494079",
"Score": "0",
"body": "In the **initializer list**: `rows(rows)` is very standard pattern. Both parameter and member are easily distinguishable and so easy to read (In the initializer list). So this is a common pattern. Your constructor parameters tend to have the same name as the variable they are initializing. Also you can not use `this` in the initializer list so that is a mute point."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T16:42:15.593",
"Id": "494080",
"Score": "0",
"body": "Outside the initializer list. Using `this->x = something;` is bad practice. The problem here is that the only reason to use `this->` is because you have shadowed variable `x` and thus need to explicitly distinguish it. The problem comes when you accidentally forget to put the `this->` on the variable. The compiler can not tell if this was a mistake or not and for somebody else reading your code it will also to be hard to tell which `x` the original coder was referring to."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T16:42:17.930",
"Id": "494081",
"Score": "0",
"body": "The solution is not to add `this->` (because some places it is supposed to be there and others not and you can not distinguish between the two), Rather your variables names should be distinct and unique so that you never need to use `this->` in the first place."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T17:06:32.853",
"Id": "494085",
"Score": "0",
"body": "@MartinYork perfect explanation, sorry for that since I'm always learning new stuff every day, the stack exchange network has become my second teacher."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T18:38:07.053",
"Id": "494097",
"Score": "0",
"body": "Why do you have `data = nullptr` in your code, then follow up by saying that it is unnecessary? Just leave it out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T18:52:39.657",
"Id": "494098",
"Score": "0",
"body": "@1201ProgramAlarm Yes it is unnecessary but I mentioned it otherwise since this isn't always the case, and you might forget to set the `data = NULL`, which can be dangerous, I thought it would have been useful to OP if I mentioned it"
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T08:25:20.247",
"Id": "251005",
"ParentId": "250990",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T23:22:11.633",
"Id": "250990",
"Score": "0",
"Tags": [
"c++",
"matrix",
"memory-management",
"memory-optimization"
],
"Title": "Simple C++ Dynamicly allocated Matrix with only one memory allocation"
}
|
250990
|
<p><em>This is a Hackerrank problem: <a href="https://www.hackerrank.com/challenges/crush/problem" rel="noreferrer">https://www.hackerrank.com/challenges/crush/problem</a></em></p>
<blockquote>
<p>You are given a list of size <span class="math-container">\$N\$</span>, initialized with zeroes. You have
to perform <span class="math-container">\$M\$</span> operations on the list and output the maximum of
final values of all the <span class="math-container">\$N\$</span> elements in the list. For every
operation, you are given three integers <span class="math-container">\$a, b\$</span> and <span class="math-container">\$k\$</span> and you
have to add value to all the elements ranging from index <span class="math-container">\$a\$</span> to
<span class="math-container">\$b\$</span> (both inclusive).</p>
<p><strong>Input Format</strong></p>
<p>First line will contain two integers <span class="math-container">\$N\$</span> and <span class="math-container">\$M\$</span> separated by a
single space. Next <span class="math-container">\$M\$</span> lines will contain three integers <span class="math-container">\$a, b\$</span>
and <span class="math-container">\$k\$</span> separated by a single space. Numbers in list are numbered
from <span class="math-container">\$1\$</span> to <span class="math-container">\$N\$</span>.</p>
<p><strong>Constraints</strong></p>
<p><span class="math-container">\$3 \leq N \leq 10^7\$</span></p>
<p><span class="math-container">\$1\leq M \leq 2*10^5\$</span></p>
<p><span class="math-container">\$1 \leq a \leq b \leq N\$</span></p>
<p><span class="math-container">\$ 0 \leq k \leq 10^9\$</span></p>
<p><strong>Output Format</strong></p>
<p>A single line containing <em>maximum value in the updated list</em>.</p>
<p><strong>Sample Input</strong></p>
<pre><code>5 3
1 2 100
2 5 100
3 4 100
</code></pre>
<p><strong>Sample Output</strong></p>
<pre><code>200
</code></pre>
</blockquote>
<p><strong>My code</strong>:</p>
<pre><code>def arrayManipulation(n, queries):
nums = [0] * (n + 1)
for q in queries:
nums[q[0]-1] += q[2]
nums[q[1]] -= q[2]
current = 0
max = 0
for i in nums:
current += i
if current > max: max = current
return max
</code></pre>
<p>Is there any way to optimize this?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T01:09:36.600",
"Id": "493885",
"Score": "2",
"body": "I don't think your program would pass the test cases. You are not modifying `nums` for the _range_ `q[0]` to `q[1]`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T02:03:43.987",
"Id": "493886",
"Score": "1",
"body": "One efficient solution looks something like order the sub intervals defined by the a, b’s. Then start at 0 and go to N and each point you can work out which intervals you have lost the contribution from and which you have gained."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T02:14:08.637",
"Id": "493887",
"Score": "3",
"body": "@hjpotter92 He increments `a` by `k` and decrements `b` by `k`, then sums all the numbers and calculates the max on the way. The code is actually fine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T03:50:29.733",
"Id": "493892",
"Score": "1",
"body": "@Marc yes, you're right. Although, this approach should be explained in the question."
}
] |
[
{
"body": "<p>I don't know of any way to optimize this; I suspect you've cracked the way it was intended to be implemented. The following are just general recommendations.</p>\n<p>Using <a href=\"https://pypi.org/project/black/\" rel=\"nofollow noreferrer\"><code>black</code></a> to format the code will make it closer to idiomatic style, with no manual work.</p>\n<p>After formatting I would recommend running <a href=\"https://pypi.org/project/flake8/\" rel=\"nofollow noreferrer\"><code>flake8</code></a> to find remaining non-idiomatic code. For example, function names should be written in <code>snake_case</code>.</p>\n<p><a href=\"https://docs.python.org/3/whatsnew/3.8.html#assignment-expressions\" rel=\"nofollow noreferrer\">In Python 3.8 onwards you can use the walrus operator</a> to change the last conditional to <code>if (current := current + i) > max:</code>. Not sure if that's a good idea though; I find that syntax clunky.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T18:37:02.093",
"Id": "493967",
"Score": "0",
"body": "Oops, copy/paste error. Thanks, @superbrain"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T03:28:35.607",
"Id": "493994",
"Score": "0",
"body": "Ah, that's what I thought :-) I had even googled \"make it closer to idiomatic style\" to see whether you reused that sentence from an earlier answer, but there were no results."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T06:45:41.477",
"Id": "251000",
"ParentId": "250991",
"Score": "2"
}
},
{
"body": "<p>Nice implementation, it's already very efficient. Few suggestions:</p>\n<ul>\n<li>Expand the variables in the for-loop from <code>for q in queries</code> to <code>for a, b, k in queries</code>. Given the problem description it's easier to read.</li>\n<li>A better name for the variable <code>current</code> can be <code>running_sum</code>.</li>\n<li>Avoid calling a variable <code>max</code>, since it's a built-in function in Python. An alternative name can be <code>result</code>.</li>\n<li>If you change the name of the variable <code>max</code> then you can have <code>result = max(result,running_sum)</code>.</li>\n<li>As @hjpotter92 said, is better to add a description of your approach in the question, you will likely get more reviews. Few bullet points or some comments in the code is better than nothing.</li>\n</ul>\n<p>Applying the suggestions:</p>\n<pre><code>def arrayManipulation(n, queries):\n nums = [0] * (n + 1)\n for a, b, k in queries:\n nums[a - 1] += k\n nums[b] -= k\n running_sum = 0\n result = 0\n for i in nums:\n running_sum += i\n result = max(result, running_sum)\n return result\n</code></pre>\n<p>It's already an efficient solution that runs in <span class=\"math-container\">\\$O(n+m)\\$</span>, so I wouldn't worry about performances. However, there is an alternative solution running in <span class=\"math-container\">\\$O(m*log(m))\\$</span> in the Editorial of HackerRank.</p>\n<p>I implemented it in Python:</p>\n<pre><code>def arrayManipulation(n, queries):\n indices = []\n for a, b, k in queries:\n indices.append((a, k))\n indices.append((b + 1, -k))\n indices.sort()\n running_sum = 0\n result = 0\n for _, k in indices:\n running_sum += k\n result = max(result, running_sum)\n return result\n</code></pre>\n<p>It's based on the fact that it's enough finding the running sum on the sorted indices.</p>\n<p>FYI in the Editorial (or Discussion) section of HackerRank there are optimal solutions and detailed explanations.</p>\n<p>Thanks to @superbrain for the corrections provided in the comments.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T13:10:12.803",
"Id": "493921",
"Score": "1",
"body": "The original is O(n+m). And [apparently](https://codereview.stackexchange.com/a/251014/228314) n is not large enough compared to m in order for O(m log m) to be better :-("
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T14:44:30.200",
"Id": "493932",
"Score": "1",
"body": "@superbrain I agree about `O(n+m)`, in this case is better to keep the term `m` even if smaller than `n`. But [the results](https://postimg.cc/NK9h51B6) I am getting running your benchmark show that the sorting approach is still a bit faster, only `with_accumulate` is slightly better than \"my\" approach. Maybe a different environment?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T15:17:42.883",
"Id": "493938",
"Score": "1",
"body": "Yeah, what environment did you use? I added times with 32-bit Python to my answer now and that looks similar to yours."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T16:12:00.050",
"Id": "493952",
"Score": "0",
"body": "Windows Home 10 64-bit, Python 3.8.6."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T16:24:42.457",
"Id": "493954",
"Score": "0",
"body": "I suspect the most influential factor is the one you left out :-). The Python bit-version. I guess you used 32-bit? Until 3.8.6 I mainly used 32-bit Python as well, as that was the default offered for download. Now for 3.9.0, the default download appears to be 64-bit, so that's what I'm mainly using now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T16:42:19.700",
"Id": "493957",
"Score": "0",
"body": "Yep, I confirm Python 32-bit."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T06:48:45.217",
"Id": "251001",
"ParentId": "250991",
"Score": "6"
}
},
{
"body": "<p>You could use <a href=\"https://docs.python.org/3/library/itertools.html#itertools.accumulate\" rel=\"nofollow noreferrer\"><code>itertools.accumulate</code></a> to shorten your second part a lot and make it faster:</p>\n<pre><code>def arrayManipulation(n, queries):\n nums = [0] * (n + 1)\n for a, b, k in queries:\n nums[a - 1] += k\n nums[b] -= k\n return max(accumulate(nums))\n</code></pre>\n<p>Can be used on Marc's version as well. Benchmarks with various solutions on three worst case inputs:</p>\n<pre><code>CPython 3.9.0 64-bit on Windows 10 Pro 2004 64-bit:\n\n original 798 ms 787 ms 795 ms\n with_abk 785 ms 790 ms 807 ms\nwith_accumulate 581 ms 581 ms 596 ms\n Marc 736 ms 737 ms 736 ms\n optimized_1 698 ms 702 ms 698 ms\n optimized_2 696 ms 694 ms 690 ms\n optimized_3 692 ms 683 ms 684 ms\n Reinderien 516 ms 512 ms 511 ms\n\nCPython 3.9.0 32-bit on Windows 10 Pro 2004 64-bit:\n\n original 1200 ms 1229 ms 1259 ms\n with_abk 1167 ms 1203 ms 1174 ms\nwith_accumulate 939 ms 937 ms 934 ms\n Marc 922 ms 927 ms 923 ms\n optimized_1 865 ms 868 ms 869 ms\n optimized_2 863 ms 863 ms 868 ms\n optimized_3 851 ms 847 ms 842 ms\n Reinderien 979 ms 959 ms 983 ms\n</code></pre>\n<p>Code:</p>\n<pre><code>from timeit import repeat\nfrom random import randint\nfrom itertools import accumulate\nfrom array import array\n\ndef original(n, queries):\n nums = [0] * (n + 1)\n for q in queries:\n nums[q[0]-1] += q[2]\n nums[q[1]] -= q[2]\n current = 0\n max = 0\n for i in nums:\n current += i\n if current > max: max = current\n return max\n\ndef with_abk(n, queries):\n nums = [0] * (n + 1)\n for a, b, k in queries:\n nums[a - 1] += k\n nums[b] -= k\n current = 0\n max = 0\n for i in nums:\n current += i\n if current > max: max = current\n return max\n\ndef with_accumulate(n, queries):\n nums = [0] * (n + 1)\n for a, b, k in queries:\n nums[a - 1] += k\n nums[b] -= k\n return max(accumulate(nums))\n\ndef Marc(n, queries):\n indices = []\n for a, b, k in queries:\n indices.append((a, k))\n indices.append((b + 1, -k))\n indices.sort()\n running_sum = 0\n result = 0\n for _, k in indices:\n running_sum += k\n result = max(result, running_sum)\n return result\n\ndef optimized_1(n, queries):\n changes = []\n for a, b, k in queries:\n changes.append((a, k))\n changes.append((b + 1, -k))\n changes.sort()\n return max(accumulate(k for _, k in changes))\n\ndef optimized_2(n, queries):\n changes = []\n append = changes.append\n for a, b, k in queries:\n append((a, k))\n append((b + 1, -k))\n changes.sort()\n return max(accumulate(k for _, k in changes))\n\ndef optimized_3(n, queries):\n changes = [(a, k) for a, _, k in queries]\n changes += [(b + 1, -k) for _, b, k in queries]\n changes.sort()\n return max(accumulate(k for _, k in changes))\n\ndef Reinderien(n, queries):\n nums = array('q', [0]) * (n + 1)\n for a, b, k in queries:\n nums[a - 1] += k\n nums[b] -= k\n return max(accumulate(nums))\n\n\nfuncs = original, with_abk, with_accumulate, Marc, optimized_1, optimized_2, optimized_3, Reinderien\nnames = [func.__name__ for func in funcs]\n\ndef worst_case():\n n = 10**7\n m = 2 * 10**5\n queries = [sorted([randint(1, n), randint(1, n)]) + [randint(0, 10**9)]\n for _ in range(m)]\n return n, queries\n\n# Check correctness\nn, queries = worst_case()\nexpect = funcs[0](n, queries)\nfor func in funcs[1:]:\n print(func(n, queries) == expect, func.__name__)\n\n# Benchmark\ntss = [[] for _ in funcs]\nfor _ in range(3):\n n, queries = worst_case()\n for func, ts in zip(funcs, tss):\n t = min(repeat(lambda: func(n, queries), number=1))\n ts.append(t)\n print()\n for name, ts in zip(names, tss):\n print(name.rjust(max(map(len, names))),\n *(' %4d ms' % (t * 1000) for t in ts))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-24T16:11:06.140",
"Id": "494154",
"Score": "0",
"body": "`optimized_3` could be changed to use a generator expression on the right-hand side of `+=` to save some memory and potentially also some time. BTW, another approach is `changes = sorted(itertools.chain(*(((a, k), (b + 1, -k)) for a, b, k in queries)))`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-24T18:47:31.030",
"Id": "494191",
"Score": "0",
"body": "@GZ0 Yeah I guess with a generator expression it would take less memory, but I wasn't concerned with that here. Tried now anyway, appears to be very slightly slower or equally fast. The chain one is significantly slower. Loop with `changes += (a, k), (b+1, -k)` seems slightly faster."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T12:42:16.500",
"Id": "251014",
"ParentId": "250991",
"Score": "4"
}
},
{
"body": "<p>Given that your array is a simple list of uniform type, you might see some small benefit in switching to <a href=\"https://docs.python.org/3.8/library/array.html\" rel=\"nofollow noreferrer\">https://docs.python.org/3.8/library/array.html</a> , which is built specifically for this kind of thing. It's a compromise that uses built-ins without needing to install Numpy.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T15:11:11.763",
"Id": "493935",
"Score": "0",
"body": "What kind of benefit?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T15:13:27.477",
"Id": "493937",
"Score": "0",
"body": "@superbrain At the very least, the one that the `array` module itself claims - compactness."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T15:40:24.263",
"Id": "493943",
"Score": "4",
"body": "Well that one is clear, so I thought you wouldn't have said \"might\" for that :-). And I thought converting between `int` objects and fixed-size `array` elements all the time would be slower, but apparently it can even be faster. I'm pleasantly surprised and wondering how it's fast. Added that to my answer, let me know if I did it suboptimally."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T16:04:11.403",
"Id": "494064",
"Score": "1",
"body": "Looked a bit into that now, [how array is fast](https://codereview.stackexchange.com/a/251062/228314)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T14:12:54.717",
"Id": "251020",
"ParentId": "250991",
"Score": "2"
}
},
{
"body": "<h1>List vs Python array vs NumPy array</h1>\n<p>To my surprise, my solution using Reinderien's <a href=\"https://codereview.stackexchange.com/a/251020/228314\">suggestion</a> to use a <a href=\"https://docs.python.org/3/library/array.html\" rel=\"nofollow noreferrer\">Python <code>array</code></a> was fastest in <a href=\"https://codereview.stackexchange.com/a/251014/228314\">my benchmark</a> in 64-bit Python (and not bad in 32-bit Python). Here I look into that.</p>\n<p>Why was I surprised? Because I had always considered <code>array</code> to be rather pointless, like a "NumPy without operations". Sure, it provides <em>compact storage</em> of data, but I have plenty of memory, so I'm not very interested in that. More interested in speed. And whenever you <em>do</em> something with the array's elements, there's overhead from always converting between a Python <code>int</code> object (or whatever type you use in the array) and the array's fixed-size element data. Contrast that with NumPy, where you do operations like <code>arr += 1</code> or <code>arr1</code> += <code>arr2</code> and NumPy speedily operates on <em>all</em> the array elements. And if you treat NumPy arrays like lists and work on them element-wise yourself, it's sloooow. I thought Python arrays are similarly slower at that, and the <em>are</em>, but a lot less so:</p>\n<pre><code> | a[0] a[0] += 1\n--------------------------+---------------------\na = [0] | 27 ns 67 ns\na = array('q', [0]) | 35 ns 124 ns\na = np.zeros(1, np.int64) | 132 ns 504 ns\n</code></pre>\n<p>Accessing a list element or incrementing it is by far the fastest with a list, and by faaar the slowest with a NumPy array.</p>\n<p>Let's add a (bad) NumPy version to the mix, where I badly use a NumPy array instead of a list or a Python array:</p>\n<pre><code>def bad_numpy(n, queries):\n nums = np.zeros(n + 1, np.int64)\n for a, b, k in queries:\n nums[a - 1] += k\n nums[b] -= k\n return max(accumulate(nums))\n</code></pre>\n<p>Times with my worst case benchmark:</p>\n<pre><code>python_list 565 ms 576 ms 577 ms\npython_array 503 ms 514 ms 517 ms\nnumpy_array 2094 ms 2124 ms 2171 ms\n</code></pre>\n<p>So the bad NumPy usage is far slower, as expected.</p>\n<p>The solution has three steps: Initialization of the list/array, the loop processing the queries, and accumulating/maxing. Let's measure them separately to see where each version spends how much time.</p>\n<h2>Initialization</h2>\n<p>I took out everything after the <code>nums = ...</code> line and measured again:</p>\n<pre><code>python_list 52 ms 52 ms 55 ms\npython_array 30 ms 31 ms 32 ms\nnumpy_array 0 ms 0 ms 0 ms\n</code></pre>\n<p>The list is slowest and NumPy is <em>unbelievably</em> fast. Actually 0.016 ms, for an array of ten million int64s, which is 5000 GB/s. I think it must be <a href=\"https://stackoverflow.com/q/58076522/13008439\">cheating somehow</a>. Anyway, we see that the array solutions get a head start in the benchmark due to faster initialization.</p>\n<p>The list <code>[0] * (n + 1)</code> gets initialized <a href=\"https://github.com/python/cpython/blob/v3.9.0/Objects/listobject.c#L548-L551\" rel=\"nofollow noreferrer\">like this</a>, copying the <code>0</code> again and again and incrementing its reference count again and again:</p>\n<pre><code>for (i = 0; i < n; i++) {\n items[i] = elem;\n Py_INCREF(elem);\n}\n</code></pre>\n<p>The Python array <a href=\"https://github.com/python/cpython/blob/v3.9.0/Modules/arraymodule.c#L910-L916\" rel=\"nofollow noreferrer\">repeats faster</a>, using <code>memcpy</code> to repeatedly double the elements (1 copy => 2 copies, 4 copies, 8 copies, 16 copies, etc)</p>\n<pre><code>Py_ssize_t done = oldbytes;\nmemcpy(np->ob_item, a->ob_item, oldbytes);\nwhile (done < newbytes) {\n Py_ssize_t ncopy = (done <= newbytes-done) ? done : newbytes-done;\n memcpy(np->ob_item+done, np->ob_item, ncopy);\n done += ncopy;\n}\n</code></pre>\n<p>After seeing this, I'm actually surprised the Python array isn't <em>much</em> faster than the list.</p>\n<h2>Processing the queries</h2>\n<p>Times for the loop processing the queries:</p>\n<pre><code>python_list 122 ms 125 ms 121 ms\npython_array 96 ms 99 ms 95 ms\nnumpy_array 303 ms 307 ms 305 ms\n</code></pre>\n<p>What? But earlier we saw that the Python array is <em>faster</em> at processing elements! Well, but that was for <code>a[0]</code>, i.e., always accessing/incrementing the same element. But with the worst-case data, it's random access, and the array solutions are apparently better with that. If I change the indexes from <code>randint(1, n)</code> to <code>randint(1, 100)</code>, the picture looks different:</p>\n<pre><code>python_list 35 ms 43 ms 47 ms\npython_array 77 ms 72 ms 72 ms\nnumpy_array 217 ms 225 ms 211 ms\n</code></pre>\n<p>Not quite sure yet why, as all three containers use 80 Mb of continuous memory, so that should be equally cache-friendly. So I think it's about the <code>int</code> objects that get created with <code>+= k</code> and <code>-= k</code> and that they stay alive in the <code>list</code> but not in the arrays.</p>\n<p>Anyway, with the worst case data, the Python array increases its lead, and the NumPy array falls from first to last place. Total times for initialization and query-processing:</p>\n<pre><code>python_list 174 ms 177 ms 176 ms\npython_array 126 ms 130 ms 127 ms\nnumpy_array 303 ms 307 ms 305 ms\n</code></pre>\n<h2>Accumulate and max</h2>\n<p>Times for <code>max(accumulate(nums))</code>:</p>\n<pre><code>python_list 391 ms 399 ms 401 ms\npython_array 377 ms 384 ms 390 ms\nnumpy_array 1791 ms 1817 ms 1866 ms\n</code></pre>\n<p>So this part actually takes the longest, for all three versions. Of course in reality, in NumPy I'd use <code>nums.cumsum().max()</code>, which takes about 50 ms here.</p>\n<h2>Summary, moral of the story</h2>\n<p>Why is the Python array faster than the Python list in the benchmark?</p>\n<ul>\n<li>Initialization: Because the array's initialization is less work.</li>\n<li>Processing the queries: I think because the list keeps a lot of <code>int</code> objects alive and that's costly somehow.</li>\n<li>Accumulate/max: I think because iterating the list involves accessing all the different <code>int</code> objects in random order, i.e., randomly accessing memory, which is not that cache-friendly.</li>\n</ul>\n<p>What I take away from this all is that misusing NumPy arrays as lists is indeed a bad idea, but that using Python arrays is not equally bad but can in fact not only use less memory but also be <em>faster</em> than lists. While the conversion between objects and array entries does take extra time, other effects can more than make up for that lost time. That said, keep in mind that the array version was slower in my 32-bit Python benchmark and slower in query processing in 64-bit Python when I changed the test data to use smaller/fewer indexes. So it really depends on the problem. But using an array <em>can</em> be faster than using a list.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-24T15:27:31.843",
"Id": "494147",
"Score": "0",
"body": "Very nice sleuthing ! Would be interesting to see how `bytearray` performs on these operations. I know it can only be used to store bytes so it does not have the same functionality as other options here. But it is still something similar and can be an option for small integers."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T16:02:53.747",
"Id": "251062",
"ParentId": "250991",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T23:53:52.310",
"Id": "250991",
"Score": "13",
"Tags": [
"python",
"algorithm",
"programming-challenge",
"array"
],
"Title": "Array manipulation: add a value to each of the array elements between two given indices"
}
|
250991
|
<p>I have made my own malloc implementation using this resource as a guide
<a href="https://danluu.com/malloc-tutorial/" rel="nofollow noreferrer">https://danluu.com/malloc-tutorial/</a>
I was hoping to receive some feed back on how I can improve upon it, and If I did any major mistakes. I know my implementation has a lot of fragmentation and I pretty much no idea on how to fix it.</p>
<p>TLDR</p>
<ol>
<li>Feed back on my _malloc and _free implementation.</li>
<li>Does anyone have any good debugger that can be used to debugg x86_64 nasm code</li>
</ol>
<pre><code>bits 64
%define NULL 0
%define SYSCALL_BRK 12
struc block_meta
.next resq 1 ;pointer to the next block of "block_mata" struct
.size resq 1 ;how many bytes can this block hold
.free resb 1 ;is this block free (0 == no its not free) (1 == yes its is free)
endstruc
META_SIZE equ 17 ;the size of block_meta in bytes
section .data
global_base dq NULL ;pointer to the first "block_meta" struct
current_sbrk dq 0
section .text
global _start
global _malloc
_start:
push 400
call _malloc ;allocationg 100 dwords aka 400 bytes(array of 100 dwords). rax contains pointer
mov r15, rax ;saving pointer of array
;test program where we loop through the array and store 0 - 99 in each pos
xor ebx, ebx
._L1:
mov [r15 + rbx * 4], ebx
._L1Cond:
inc ebx
cmp ebx, 100 ;when ebx reaches 100 we have reached the end of the array
jl ._L1
xor ebx, ebx
;print out the array
._L2:
mov eax, [r15 + rbx * 4]
push rax
call _printInt
add rsp, 8
call _endl
._L2Cond:
inc ebx
cmp ebx, 100
jl ._L2
push r15
call _free
add rsp, 16 ;clear the stack
mov rax, 60 ;SYSCALL_EXIT
mov rdi, 0
syscall
;(first)last argument pused onto the stack must be the amount of bytes
;if successfull then rax will contain pointer to the memory
_malloc:
;prolog
push rbp
mov rbp, rsp
;actual code
cmp qword[rbp + 16], 0 ;compare with first argument
jle ._mallocEpilog ;if zero of negetive exit
cmp qword[global_base], NULL ;if the global_base pointer is "NULL" aka 0 allocate space
jz ._setGlobal_Base
;if global_base is not "NULL"
push qword[rbp + 16] ;how many bytes big does the block need to be
push qword[global_base] ;pointer to "meta_data" struct
call ._findFreeBlock
test rax, rax ;if zero no block was found. need to call ._requestSpace if zero
jz ._needMoreSpace
;found free block
mov rdx, rax ;save the pointer to memory block
add rdx, block_meta.free ;set the block to be not free
mov byte[rdx], 0
jmp ._mallocExit
._needMoreSpace:
call ._requestSpace ;we did not find a big enoug block. so make sapce
jmp ._mallocExit
._setGlobal_Base: ;will be used first time malloc is called
push qword[rbp + 16] ;how many bytes does the user want to reserve
push NULL ;the global_base pointer has not been set
call ._requestSpace
mov [global_base], rax ;save the pointer
._mallocExit:
add rsp, 16 ;clean the stack
add rax, META_SIZE ;add offset because of the "meta_block" struct
._mallocEpilog:
;epilog
pop rbp
ret
;(fist)last agument on the stack must be pointer to the last "block_meta" struct
;second argument must be the size in bytes that need to be allocated
;returns pointer to memory block in rax
._requestSpace:
;prolog
push rbp
mov rbp, rsp
mov rdi, [rbp + 24] ;how many bytes for the user
add rdi, META_SIZE ;extra bytes for meta data
push rdi
call ._sbrk ;rax will contain the pointer
add rsp, 8 ;clear stack
mov r8, block_meta.next ;putting the offsets in the register for later use
mov r9, block_meta.size
mov r10, block_meta.free
mov qword[rax + r8], NULL ;just setting it to NULL to get rid of garbage data for the next
cmp qword[rbp + 16], NULL ;the last "block_meta" pointer is NULL then jmp
jz ._fillMetaData
mov rcx, [rbp + 16] ;the current last "block_meta" struct in the list
mov qword[rcx + r8], rax ;mov pointer of allocated memory into next pointer of struct
._fillMetaData: ;setting all the other fields in the struct
mov rdi, [rbp + 24] ;how many bytes for the user
mov qword[rax + r9], rdi ;setting the size field of the struct
mov byte[rax + r10], 0 ;setting the free field to be 0 of struct
;epilog
pop rbp
ret
;(fist)last argument on the stack must be pointer to "block_meta" struct
;second argument is how big the block needs to be
;if successfull then rax will contain pointer to the block
;if failure the rax will contain pointer to the last block of "block_meta" struct
._findFreeBlock:
;prolog
push rbp
mov rbp, rsp
mov rax, [rbp + 16] ;pointer to the "block_meta" struct
mov rdx, [rbp + 24] ;how big do you need the block to be
mov r8, block_meta.next ;offset
mov r9, block_meta.size
mov r10, block_meta.free
jmp ._findFreeBlockLoopCond
._findFreeBlockLoop:
mov [rbp + 16], rax ;save current pointer in argument 1
mov rax, [rax + r8] ;go to the next "block_meta" struct
._findFreeBlockLoopCond:
test rax, rax ;if rax is zero we have reached the end of the linked list. exit
jz ._findFreeBlockExit
cmp byte[rax + r10], 0 ;if zero then block is not empty. loop again
jz ._findFreeBlockLoop
cmp [rax + r9], rdx ;if the current block has does not have enough space loop again.
jl ._findFreeBlockLoop
._findFreeBlockExit:
;epilog
pop rbp
ret
;(fist)last argument must be how much space do you want to reserve
;return pointer in rax
._sbrk:
;prolog
push rbp
mov rbp, rsp
;actual code
mov rax, SYSCALL_BRK ;using brk to get initilial address
mov rdi, [current_sbrk] ;starts at 0. gets updated later
syscall
mov r8, rax ;save for later
mov rax, SYSCALL_BRK
mov rdi, [rbp + 16] ;first argument (how many bytes)
add rdi, r8 ;needs to start at teh address we saved
syscall
mov [current_sbrk], rax ;next time will start at this address
mov rax, r8 ;restore pointer to the memory
;epilog
pop rbp
ret
;(first)last arguemnt on the stack must be the pointer you want to deallocate memory for
_free:
;prolog
push rbp
mov rbp, rsp
;I will be calling the pointer in rax to be the "original block"
mov rax, [rbp + 16] ;pointer to memory that needs to be deallocated
sub rax, META_SIZE ;offset to find the "block_meta" struct
mov rcx, rax
add rcx, block_meta.free ;offset to set free to be 1
mov byte[rcx], 1
._freeEpilog:
;epilog
pop rbp
ret
;print methods for testing!
%define STDIN 0
%define STDOUT 1
%define STDERR 2
%define SYSCALL_READ 0
%define SYSCALL_WRITE 1
%define SYSCALL_EXIT 60
section .data
endl db 10
endlLength equ $ - endl
;no input needed
;just an end line "method"
_endl:
mov rax, SYSCALL_WRITE
mov rdi, STDOUT
mov rsi, endl
mov edx, endlLength
syscall
ret
;last value pushed to stack will be printed
_printInt:
;prolog
push rbp
mov rbp, rsp
;save registers
push rbx
;actual code
mov rsi, rsp
mov rax, [rbp + 16] ;get the value that user wants to print
mov rbx, 10 ;will be used to divide by 10 later
xor rcx, rcx
cqo
cmp rdx, -1 ;check to see if negetive
jne _divisionLoop ;if not negetive jump
;print negetive sign
dec rsi
mov [rsi], byte '-'
mov rax, SYSCALL_WRITE
mov rdi, STDOUT
mov rdx, 1
syscall
inc rsi
;convert to positive number
mov rax, [rbp + 16] ;get the value that needs to be printed
neg rax ;make it a positive
xor rcx, rcx
_divisionLoop:
xor rdx, rdx
div rbx ;divides number by 10 to move over last digit into rdx reg
add dl, '0' ;add the '0' to ascii to convert into ascii val
dec rsi
mov [rsi], dl
inc rcx ;count for how many digits added to stack
test rax, rax
jnz _divisionLoop ;jump if the division did not result in a zero
;print all the values
mov rax, SYSCALL_WRITE
mov rdi, STDOUT
mov rdx, rcx
syscall
;restore register
pop rbx
;epilog
pop rbp
ret
</code></pre>
|
[] |
[
{
"body": "<p>When a block is free'd, check the blocks either side. If an adjacent block is not allocated then merge it with the free'd block.\nThis should help with fragmentation.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T08:22:04.137",
"Id": "251003",
"ParentId": "250996",
"Score": "2"
}
},
{
"body": "\n<blockquote>\n<p>If I did any major mistakes.</p>\n</blockquote>\n<p>Depends on whether you want to follow the Linux 64-bit calling conventions or not. Currently you are using the stack for parameter passing between your functions, where the normal calling convention places the first 6 parameters in the registers <code>RDI</code>, <code>RSI</code>, <code>RDX</code>, <code>RCX</code>, <code>R8</code>, and <code>R9</code>. I believe that your code would benefit from following the conventions.</p>\n<p>Where you <strong>must follow the conventions</strong> is in your <em>sbrk</em> function that does 2 Linux syscalls. In between calls you've preserved a value in the <code>r8</code> register but you are forgetting that the Linux 64-bit calling conventions say that this is a scratch register that the SYSCALL_BRK is free to clobber! Just save the value on the stack.</p>\n<p>Erratum: Apparently <code>SYSCALL</code> is not a "call" in the traditional sense and only ever clobbers <code>RAX</code>, <code>RCX</code>, and <code>R11</code>. That means that your choice of <code>R8</code> is fine. See <a href=\"https://stackoverflow.com/a/2538212/3144770\">Peter Cordes' answer</a> on the matter.</p>\n<blockquote>\n<p>Feed back on my <em>_free</em> implementation.</p>\n</blockquote>\n<p>This is a truly minimalistic version of it. You're putting to much trust in the user (you yourself). How can you be sure that the address that they provide will point to a valid allocation?<br />\nA save way to do this is to follow the chain of allocations and only when you encounter the submitted address do you free that allocation.</p>\n<blockquote>\n<p>Feed back on my <em>_malloc</em> implementation.</p>\n</blockquote>\n<p>This on the other hand is an overly complex code that depends on the ingenious use of modifying and/or recycling of the stacked input parameters.<br />\nIt is easy to lose your way in this code.</p>\n<p>If you would only initialize once the <em>global_base</em> and <em>current_sbrk</em> variables at program startup, it would already bring down complexity a lot. e.g. It would eliminate the successive syscalls in <em>._sbrk</em>.</p>\n<p>And why not use the <em>_malloc</em> stackframe pointer <code>RBP</code> for the local subroutines <em>._requestSpace</em>, <em>._findFreeBlock</em>, and <em>._sbrk</em> ? Then you can do without all of those prologs and epilogs.</p>\n<blockquote>\n<p>I was hoping to receive some feed back on how I can improve upon it</p>\n</blockquote>\n<p>The biggest improvement that you can make is a structural one and it will require you to rewrite the lot but in the end it will be very rewarding...</p>\n<p>Although the tutorial used a linked list, that's not necessarily the best way to manage your meta data. Having both a pointer to the next block and also a block size, is like storing the same information twice (and keeping it up to date too!).<br />\nIf you only maintain a <em>next</em> field then you get the <em>size</em> via:</p>\n<pre class=\"lang-none prettyprint-override\"><code>size = next - (current + META_SIZE)\n</code></pre>\n<p>If you only maintain a <em>size</em> field than you get the <em>next</em> via:</p>\n<pre class=\"lang-none prettyprint-override\"><code>next = current + META_SIZE + size\n</code></pre>\n<p>Do yourself a favor and only store the block size. It's the simpler solution.</p>\n<p>Next comes alignment. Your current implementation uses a <em>META_SIZE</em> of 17 bytes. This is a real disaster when it comes to program performance! Always have the memory that the caller requests aligned at an optimal value like say qword or dqword. I would choose the latter and use next struc:</p>\n<pre class=\"lang-none prettyprint-override\"><code>struc block_meta\n .size resq 1 ; how many bytes can this block hold\n .free resb 1 ; (0 == it's not free) (1 == it's free)\n .pad resb 7\nendstruc\nMETA_SIZE equ 16\n</code></pre>\n<p>This is how you can make the requested block size a muliple of 16 in accordance with the chosen <em>META_SIZE</em> (which has to be a power of 2):</p>\n<pre class=\"lang-none prettyprint-override\"><code>; RDI is the requested allocation size\nadd rdi, META_SIZE - 1\nand rdi, -META_SIZE \n</code></pre>\n<h3>Some code improvements include</h3>\n<p>Code like:</p>\n<pre class=\"lang-none prettyprint-override\"><code>mov rdx, rax\nadd rdx, block_meta.free\nmov byte[rdx], 0\n...\nmov r10, block_meta.free\ncmp byte[rax + r10], 0\n</code></pre>\n<p>can be written like:</p>\n<pre class=\"lang-none prettyprint-override\"><code>mov byte[rax + block_meta.free], 0\n...\ncmp byte[rax + block_meta.free], 0\n</code></pre>\n<p>And in your <em>_printInt</em> code you can shave off quite a few instructions by checking for a negative number the way I showed you in <a href=\"https://codereview.stackexchange.com/q/249137\">a previous answer of mine</a>. By picking up the result from the test a second time after the digit were collected on the stack and prepending the "-" character, you can output the lot in one SYSCALL_WRITE operation instead of two.</p>\n<p>And of course drop the redundant size tags, put your defines on top so you can use them everywhere, don't forget <code>global _free</code>, clear a register using <code>xor edi, edi</code>, etc ...</p>\n<hr />\n<p>As an example this is how I would program <em>._findFreeBlock</em>. The code traverses the memory between <em>global_base</em> and <em>current_sbrk</em> checking for a free block that is large enough. If found then <code>RAX</code> holds the address of the meta data, and if not found then <code>RAX</code> is zero.</p>\n<pre class=\"lang-none prettyprint-override\"><code>; IN (rdi) OUT (rax) MOD (rdx)\n._findFreeBlock:\n mov rax, [global_base]\n jmp .Start\n .Loop:\n mov rdx, [rax + block_meta.size]\n cmp byte [rax + block_meta.free], 1 ; (1 == it's free)\n jne .Next ; Block is not free\n cmp rdx, rdi\n jae .Exit ; Free block is large enough\n .Next:\n lea rax, [rax + META_SIZE + rdx]\n .Start:\n cmp rax, [current_sbrk]\n jb .Loop\n xor eax, eax ; Not found\n .Exit:\n ret\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-25T16:36:00.873",
"Id": "494266",
"Score": "1",
"body": "Thank You! I will try to clear all the bugs/calling convention as you have pointed out and post the new version within a few days!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-19T19:35:07.407",
"Id": "497232",
"Score": "0",
"body": "*How can you be sure that the address that they provide will point to a valid allocation?* - Because passing anything else would be undefined behaviour. Doing extra checking should be optional or a debug-build feature, except for problems you can detect for (nearly) free. Having a debug version with extra checking is certainly useful during development, but presumably extreme efficiency is the goal of hand-written asm."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-19T19:40:27.673",
"Id": "497234",
"Score": "0",
"body": "Alignment: x86-64 System V has `alignof(max_align_t) == 16`. malloc(n) must be usable to store any standard-alignment object that can fit in it, so allocations of 16 bytes or later must always be aligned by 16. Unless you're eschewing the standard ABI altogether, then sure 8-byte alignment could be viable."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-25T13:34:12.473",
"Id": "251124",
"ParentId": "250996",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "251124",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T05:01:51.677",
"Id": "250996",
"Score": "4",
"Tags": [
"assembly",
"x86",
"nasm"
],
"Title": "x86_64 nasm criticism on malloc and free implementation"
}
|
250996
|
<p>I have this code</p>
<pre><code>employee = this.identityService.me;
employeeToken: Observable<string> = this.employee.pipe(map((e) => e.token));
currentHead = new BehaviorSubject(localStorage.getItem('head'));
</code></pre>
<p>What I need to do is to change the <code>currentHead</code> if the local storage is empty. So I do this in the ngOnInit</p>
<pre><code>ngOnInit() {
this.employeeToken.subscribe(e => {
if (!this.currentHead.value || this.currentHead.value === '') {
this.currentHead.next(e);
}
});
}
</code></pre>
<p>It works, but somehow I feel like this should e feasible with rxjs in the initialization of <code>currentHead</code>, no?</p>
<p>Where I failed is, that the local storage is not an observable but <code>this.employee</code> is, so I struggle to compare them. I tried some <em>convert observable to behaviorsubject</em> but that didn't work either.</p>
|
[] |
[
{
"body": "<p>I think the <code>ngOnInit()</code> is the best suitable way for that. Clean and easy to spot. The initialization of the other two variables should also be part of ngOnInit (<code>employee</code> and <code>employeeToken</code>).</p>\n<p>Something like that:</p>\n<pre><code>employee: Empoyee;\nemployeeToken: Observable<string>;\ncurrentHead: BehaviorSubject<ADD-TYPE-HERE>;\n\n...\n\nngOnInit() {\n const headFromStorage = localStorage.getItem('head');\n employee = this.identityService.me;\n employeeToken = this.employee.pipe(map((e) => e.token));\n this.currentHead = new BehaviorSubject(localStorage.getItem('head'));\n \n this.employeeToken.subscribe(e => this.currentHead.next(e));\n}\n\n</code></pre>\n<p>Not sure you need this:</p>\n<pre><code>if (!this.currentHead.value || this.currentHead.value === '') {\n</code></pre>\n<p>Because this is a subscription. Every time the empoloyeeToken change, you have to update it, right?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T12:14:52.713",
"Id": "251538",
"ParentId": "250997",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T05:06:58.847",
"Id": "250997",
"Score": "2",
"Tags": [
"typescript",
"angular-2+",
"rxjs"
],
"Title": "Rewrite BehaviorSuject that takes either localStorage or Observable in Angular"
}
|
250997
|
<p>This is what I've come up with to construct a name using a javascript object and immutable.js:</p>
<pre><code>const getFullName = ({ user }) => {
if (!user || !user.get('response')) {
return '';
}
return `${user.getIn(['response', 'firstName']) || ''} ${user.getIn(['response', 'lastName']) ||
''}`;
};
</code></pre>
<p>As you can see, it looks pretty ugly. I'm wondering if there is a way to clean this code up. This function is called in loop to show all the names in the dataset. I can imagine that this solution may not be a very <code>efficient</code> in such case.</p>
|
[] |
[
{
"body": "<p>Rather than repeating <code>user.getIn(['response'</code> twice, you can extract the response <em>once</em> into a variable. Also, both <code>.getIn</code> and <code>.get</code> accept a default value if the property isn't found in the collection, which you can use instead of <code>|| ''</code>. For example, <code>.get('foo') || ''</code> is (existing falsey values aside) equivalent to <code>.get('foo', '')</code>.</p>\n<p>In up-to-date environments or if the code is being transpiled, you can use optional chaining to more concisely get the nested <code>response</code> if it exists.</p>\n<p>Since you want to return <em>something</em> if one condition is fulfilled, and <em>something else</em> otherwise, rather than using <code>if</code>, you can make things more concise by using the conditional operator:</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 getFullName = ({ user }) => {\n const response = user?.get('response');\n return !response\n ? ''\n : `${response.get('firstName', '')} ${response.get('lastName', '')}`;\n};\n\nconsole.log(getFullName({}));\nconsole.log(getFullName({ user: Immutable.fromJS({}) }));\nconsole.log(getFullName({ user: Immutable.fromJS({ response: { firstName: 'foo' } }) }));\nconsole.log(getFullName({ user: Immutable.fromJS({ response: { firstName: 'foo', lastName: 'bar' } }) }));</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.2/immutable.min.js\"></script></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T14:04:28.847",
"Id": "251019",
"ParentId": "250999",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "251019",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T06:37:59.553",
"Id": "250999",
"Score": "3",
"Tags": [
"javascript",
"immutable.js"
],
"Title": "Cleaner way to construct a name using Immutable.js"
}
|
250999
|
<p>I'm trying to refactor some code so that it does not have so much repetition to it. What I'm trying to do is create an input for a multiple channel/input neural network. The features that are being considered come from two different sources completely and the inputA here is a 2D array and has to be kept in this format.</p>
<p>I have the following code:</p>
<pre><code>'Create Input Values'
inputA= word_embeddings.numpy()
inputB = df['Features'].values
y = df['Target'].values
full_model_inputs = [inputA, inputB]
#Create Dictionary
original_model_inputs = dict(inputA= inputA, inputB= inputB)
'Create Train and Validation Data from Inputs'
#Preserve data dimensionality for data split
df = pd.DataFrame({"inputA":original_model_inputs["inputA"],
"inputB":list(original_model_inputs["inputB"])})
#Data Split
x_train, x_valid, y_train, y_valid = train_test_split(df, y, test_size = 0.25)
#Convert back to original format
x_train = x_train.to_dict("list")
x_valid = x_valid.to_dict("list")
#Format dictionary items as arrays to be functional for model
x_train = {k:np.array(v) for k,v in x_train.items()}
x_valid = {k:np.array(v) for k,v in x_valid.items()}
</code></pre>
<p>Are there any suggestions to improve this code? Just want some insight from the community.</p>
<p>what the dictionary looks like:</p>
<pre><code>{'inputA': array([40., 68., 46., ..., 60., 42., 50.]),
'inputB': array([[-1.915694 , -2.39863253, -1.75456583, ..., 2.11158562,
2.42145038, 1.0996474 ],
[-1.99583805, -2.38059568, -1.94454968, ..., 2.14585209,
2.56227231, 1.2808286 ],
[-2.1607585 , -2.29914975, -1.85722673, ..., 2.04741383,
2.34712863, 1.77104282],
...,
[-2.1576829 , -2.28505015, -1.71492636, ..., 2.05909061,
2.43704724, 1.90647388],
[-1.81904769, -2.74457788, -2.15936947, ..., 2.31333733,
2.50243115, 1.75907826],
[-2.01300311, -2.32310271, -2.00470185, ..., 2.09641671,
2.53372359, 1.22000134]])}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T07:20:25.530",
"Id": "251002",
"Score": "2",
"Tags": [
"python",
"numpy",
"hash-map"
],
"Title": "Converts Pandas and Numpy into Dictionary and Converts back to original format for data split"
}
|
251002
|
<p>I have a set of classes across multiple packages, and I want any logging from within a single "com.name.root.xxx" package and all its child packages, to be logged to a different file. e.g:</p>
<pre class="lang-java prettyprint-override"><code>//Package Name Log To \\
//-------------------------------------------\\
com.name.root.router C:\com\router.log
com.name.root.router.utils C:\com\router.log
com.name.root.init C:\com\init.log
com.name.root.database C:\com\database.log
com.name.root.web C:\com\web.log
com.name.root.web.rest C:\com\web.log
com.name.root.web.http C:\com\web.log
</code></pre>
<p>etc.</p>
<p>I have created a helper class which tracks which log file paths have been set up with file handlers already, and also which packages have already had their loggers set up; and provides accordingly.</p>
<p>I am interested in review for efficiency, and if there's a better (simpler/cleaner/more understandable) way to do this:</p>
<pre class="lang-java prettyprint-override"><code>package com.name.root.util.log;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
public class LogProvider
{
private static final String rootPackageName = "com.name.root";
private static final int rootPackageNameLength = rootPackageName.length();
private static final HashMap<String,FileHandler> fileHandlersByPath = new HashMap<>();
private static final HashSet<String> alreadyProvidedPackages = new HashSet<>();
public static Logger getConfiguredLogger(Class<?> callingClass, String logPathIfNotAlreadySet)
{
return getConfiguredLogger(callingClass, logPathIfNotAlreadySet, Level.FINEST); // default log level
}
public static Logger getConfiguredLogger(Class<?> callingClass, String logPathIfNotAlreadySet, Level maxLogLevelIfNotAlreadySet)
{
String fqClassName = callingClass.getCanonicalName(); // e.g. com.name.root.router.utils
String packageName = fqClassName; // default
if (fqClassName.startsWith(rootPackageName))
{
// we want to just get as far as the main package after "com.name.root" - e.g. "com.name.root.router"
packageName = fqClassName.substring(0,fqClassName.indexOf(".", rootPackageNameLength+1));
}
return getConfiguredLogger(packageName, logPathIfNotAlreadySet, maxLogLevelIfNotAlreadySet);
}
private static Logger getConfiguredLogger(String packageName, String logPathIfNotAlreadySet, Level maxLogLevelIfNotAlreadySet)
{
Logger logger = Logger.getLogger(packageName); // get the logger for the package
if (alreadyProvidedPackages.contains(packageName))
{
return logger; // we've already configured this logger
}
else
{
alreadyProvidedPackages.add(packageName);
logger.setLevel(maxLogLevelIfNotAlreadySet);
String logPath = (logPathIfNotAlreadySet == null || logPathIfNotAlreadySet.isBlank() ? "C:\\com\\output.log" : logPathIfNotAlreadySet);
try
{
// reuse an existing file handler if possible, so we don't get multiple output files if two packages want to log to the same file
FileHandler fh = null;
if (fileHandlersByPath.containsKey(logPath))
{
fh = (fileHandlersByPath.get(logPath));
}
else
{
fh = new FileHandler(logPath, false);
fh.setFormatter(new customSingleLineLogFormatter()); // The formatter itself is out of scope for review
fileHandlersByPath.put(logPath, fh);
}
logger.addHandler(fh);
}
catch (SecurityException | IOException e)
{
e.printStackTrace();
}
return logger;
}
}
}
</code></pre>
<p>Example Usage:</p>
<p>For utility classes (e.g. static database access classes), I am just passing the logger into each method that uses it, because it can be used from multiple packages and should log as if it was a part of the calling class:</p>
<pre class="lang-java prettyprint-override"><code>package com.name.root.util.database
public class StringUtils
{
// just an example
public static long parseStringToEpoch(String s, Logger logger)
{
logger.entering("parseStringToEpoch"); // should turn up in the calling class's log file
}
}
</code></pre>
<p>but for all other classes, each class has its own static final Logger instance which is instantiated along with the class, calling the getConfiguredLogger method:</p>
<pre class="lang-java prettyprint-override"><code>package com.name.root.router.base
public abstract class BaseRouter
{
private static final Logger logger = LogProvider.getConfiguredLogger(BaseRouter.class, "C:\\com\\Router.log");`
// etc, including static methods that log
}
package com.name.root.router.impl
public class ChildRouter
{
private static final Logger logger = LogProvider.getConfiguredLogger(ChildRouter.class, "C:\\com\\Router.log");`
// etc, including main and static methods that log
// sample usage of utilities methods
private static final long testEpoch = StringUtils.parseStringToEpoch("1234567",logger);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-29T17:07:46.093",
"Id": "494678",
"Score": "0",
"body": "I've tried to create a Stack-based solution, [and it is available as a prototype-snippet on GitLab](https://gitlab.com/-/snippets/2034421). However, it has multiple shortcomings, for example that the cached Logger will never be removed, which is important if that Thread is being reused. I would not try to get a stack for every call, that *should* have a negative impact on the performance."
}
] |
[
{
"body": "<p>I am not completely sure what are you trying to accomplish here but you should store all your resources, namely your log files, in a resource source folder, and in code you can access those resources with:</p>\n<pre><code>// the stream holding the file content\nInputStream is = getClass().getClassLoader().getResourceAsStream("file.txt");\n\n// for static access, uses the class name directly\nInputStream is = JavaClassName.class.getClassLoader().getResourceAsStream("file.txt");\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-29T09:50:28.607",
"Id": "494629",
"Score": "0",
"body": "I'm trying to use `java.util.logging` across multiple packages without creating new `Logger` and `FileHandler` instances for each class"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-28T20:46:39.343",
"Id": "251267",
"ParentId": "251006",
"Score": "0"
}
},
{
"body": "<pre class=\"lang-java prettyprint-override\"><code>public class LogProvider\n</code></pre>\n<p>That class should most likely be <code>final</code> and have a <code>private</code> constructor, to make it clear that it is a static utility.</p>\n<hr />\n<pre><code> private static final HashMap<String,FileHandler> fileHandlersByPath = new HashMap<>();\n private static final HashSet<String> alreadyProvidedPackages = new HashSet<>();\n</code></pre>\n<p>Always try to use the lowest common class or interface when declaring variables, in this case <code>Map</code> and <code>Set</code>.</p>\n<hr />\n<p>I'm unsure of your names, normally I'd expect <code>static final</code> variables to constants, therefor named with UPPER_SNAKE_CASE.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>public class LogProvider\n</code></pre>\n<p>The class does not provide logs, it does provide loggers, so it should be named <code>LoggerProvider</code>.</p>\n<p>More commonly is the name <code>LoggerFactory</code> for such classes, though.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>public static Logger getConfiguredLogger(Class<?> callingClass, String logPathIfNotAlreadySet)\n</code></pre>\n<p>I'd drop the "Configured" from the name, as there is no way to get a "not configured" logger, and it also does not matter to the user of the API whether it is configured or not. You might even get away with only having a <code>get</code> method, like this:</p>\n<pre class=\"lang-java prettyprint-override\"><code>Logger LOGGER = LoggerFactory.get(SomeClass.class);\n</code></pre>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>String fqClassName = callingClass.getCanonicalName();\n</code></pre>\n<p>The name of the variable is incorrect, it's the canonical name, not the fully-qualified name. They might or might not be the same.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>String packageName = fqClassName;\n</code></pre>\n<p>This one is also incorrect, it's not the package name (retrieved through <code>Class.getPackageName()</code>) but is the canonical name.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>if (fqClassName.startsWith(rootPackageName))\n</code></pre>\n<p>That check is incorrect, it would also apply to <code>com.name.rootbutdifferentpackage.sub.Class</code>.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> catch (SecurityException | IOException e)\n {\n e.printStackTrace();\n }\n</code></pre>\n<p>You should use a logger to log that...but actually, you most likely want to fail, because in this case you can't provide logging capabilities anymore, which might jeopardize the operation of the application.</p>\n<p>Yes, not being to log information is a serious problem in enterprise environments, in desktop application not at all, but if you have a datacenter with 10k instances running, and 5k of those don't log, you have a problem.</p>\n<hr />\n<p>As far as I can see, your class is not thread-safe, which might lead to failure or that a <code>FileHandler</code> is created twice for the same file, possibly corrupting the log data.</p>\n<p>You need a concept of when to synchronize the access to the stored information. The easiest way might be to use a synchronized list by using a wrapper created by <code>Collections.synchronized*</code>. However, that will only get rid of possible exceptions, it might still corrupt the stored state. You will need to synchronize on something, a lock-object to make sure that you never create the same file twice.</p>\n<pre class=\"lang-java prettyprint-override\"><code>// Requires to be synchronized to allow adding and checking at the same time.\nprivate static Map<String,FileHandler> fileHandlersByPath = Collections.synchronizedMap(new HashMap<>());\n\nprivate static Object insertionLockObject = new Object();\n\n// ...\n\n// Assuming that this method is thread-safe and only delivers the same\n// instance once for the same parameter.\nLogger logger = Logger.getLogger(packageName);\n\n// First "cheap" check to see if it is set.\nif (!alreadyProvidedPackages.contains(packageName)) {\n // If it is not, we must acquire the lock to insert it.\n synchronized(insertionLockObject) {\n // Second check, because another thread could have acquired\n // the lock before us, and already did all the set up.\n if (!alreadyProvidedPackages.contains(packageName)) {\n // Code goes here.\n }\n }\n}\n\nreturn logger;\n</code></pre>\n<hr />\n<blockquote>\n<p>For utility classes (e.g. static database access classes), I am just passing the logger into each method that uses it, because it can be used from multiple packages and should log as if it was a part of the calling class:</p>\n</blockquote>\n<p>That smells. But I see why you are doing it.</p>\n<p>There is no easy way to do what you want here, one could come up with a solution to parse the current StackTrace to retrieve the calling class and package, but that might be a fragile solution without giving it really much thought.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>private static final Logger logger = LogProvider.getConfiguredLogger(BaseRouter.class, "C:\\\\com\\\\Router.log");\n</code></pre>\n<p>As said before, I would expect that variable to UPPER_SNAKE_CASE.</p>\n<p>I missed this before, but why are you passing the whole path? It would be much better if you wouldn't pass a path at all, but instead set one in <code>LogProvider</code> and then create a path/file for this based on the passed in class. That would be much less fragile and deterministic.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T11:06:29.343",
"Id": "494725",
"Score": "0",
"body": "Thanks, the synchronisation stuff especially was a helpful reminder."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-29T12:16:09.467",
"Id": "251296",
"ParentId": "251006",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "251296",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T08:44:46.800",
"Id": "251006",
"Score": "3",
"Tags": [
"java",
"logging"
],
"Title": "Java Logging with a file per root package"
}
|
251006
|
<p>This program is used to create a random bank card number. Card number is created using account type and client location for the first eight digits and the remaining 8 digits are completely random. I'm new to this site, but I believe it's just for code review to get opinions on code. If i'm incorrect please let me know and I can take this down. Otherwise, feel free to give me feedback. Thanks!</p>
<pre><code>import java.util.ArrayList;
import java.util.Scanner;
public class Main {
private static ArrayList<String> storedCardNumbers = new ArrayList<String>();
public static void main(String[] args) {
menu();
}
//create menu for checking list of cards or creating a new card
public static void menu(){
//used to check if client wants to exit program
boolean exit = false;
System.out.println("___________________\n" +
"Welcome to our bank!\n" + "Choose an option below: \n" +
"1. Create new bank card.\n" +
"2. Check existing cards.\n" +
"3. Exit.");
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
if(choice == 1) {
createNewCard();
} else if(choice == 2){
System.out.println("-------------------------");
System.out.println("There are " + storedCardNumbers.size() + " cards in the system");
for (int i = 0; i < storedCardNumbers.size(); i++) {
System.out.println(storedCardNumbers.get(i).toString());
}
System.out.println("-------------------------");
} else if(choice == 3) {
System.out.println("Thank you for coming in!");
exit = true;
} else {
System.out.println("Incorrect choice.\n" +
"Please choose a valid option: ");
menu();
}
if(exit == false) {
System.out.println("Would you like to do anything else?");
menu();
} else {
}
}
//create new bank card with user params
public static String createNewCard() {
// String accountType = setCardAccountType();
// String location = setAccountLocation();
String cardNumber = getCardNumber(setCardAccountType(),setAccountLocation());
System.out.println("New card successfully created.\n" +
"Your new bank card number is: \n" +
cardNumber);
storedCardNumbers.add(cardNumber);
return cardNumber;
}
public static String setAccountLocation() {
String location = "other";
System.out.println("What is your location?\n" +
"1. US East\n" +
"2. US West\n" +
"3. Hawaii\n" +
"4. Alaska\n" +
"5. Other.");
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
if (choice == 1) {
location.equalsIgnoreCase("useast");
} else if (choice == 2) {
location.equalsIgnoreCase("uswest");
} else if (choice == 3) {
location.equalsIgnoreCase("alaska");
} else if (choice == 4) {
location.equalsIgnoreCase("hawaii");
} else if(choice == 5) {
location.equalsIgnoreCase("other");
}else {
System.out.println("Entered invalid selection.\n" +
"Please enter valid selection.");
setCardAccountType();
}
return location;
}
//set the card account type for the creatNewCard method to use
public static String setCardAccountType() {
String accountType = "other";
System.out.println("Which type of account do you have?\n" +
"1. Checking.\n" +
"2. Savings.\n" +
"3. Credit.\n" +
"4. Other.\n" +
"Enter corresponding digit: ");
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
if (choice == 1) {
accountType.equalsIgnoreCase("checking");
} else if (choice == 2) {
accountType.equalsIgnoreCase("savings");
} else if (choice == 3) {
accountType.equalsIgnoreCase("credit");
} else if (choice == 4) {
accountType.equalsIgnoreCase("other");
} else {
System.out.println("Entered invalid selection.\n" +
"Please enter valid selection.");
setCardAccountType();
}
return accountType;
}
//create random number for card
public static int getRandom(int min, int max) {
return (int) (Math.random()*(max - min)) + min;
}
public static String getCardNumber(String accountType, String location) {
//first set of four
int accountKeySet;
//second set of four
int locationKeySet;
//third set of four
int lastEightFirst;
//fourth set of four
int lastEightSecond;
//assign a value to each account type
if(accountType.equalsIgnoreCase("checking")) {
accountKeySet = 4400;
} else if(accountType.equalsIgnoreCase("savings")) {
accountKeySet = 4300;
} else if(accountType.equalsIgnoreCase("credit")) {
accountKeySet = 4200;
} else {
accountKeySet = 4000;
}
//Assign a value to each location of client
if(location.equalsIgnoreCase("useast")) {
locationKeySet = 1011;
} else if(location.equalsIgnoreCase("uswest")) {
locationKeySet = 2011;
} else if (location.equalsIgnoreCase("Alaska")) {
locationKeySet = 3011;
} else if (location.equalsIgnoreCase("hawaii")) {
locationKeySet = 4011;
} else {
locationKeySet = 1022;
}
//create a randomized number for last of card number
lastEightFirst = getRandom(1000,9999);
lastEightSecond = getRandom(1000,9999);
//construct card number
StringBuilder key = new StringBuilder();
key.append(accountKeySet);
key.append(" ");
key.append(locationKeySet);
key.append(" ");
key.append(lastEightFirst);
key.append(" ");
key.append(lastEightSecond);
return key.toString();
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Hi Nicholas and welcome to code review.</p>\n<p>A few things that I noticed in your code:</p>\n<ul>\n<li><p>The indentation isn't consistent. The closing bracket of <code>menu</code> isn't where it should be. The whole <code>setAccountLocation</code> method is one tab to far right. The readability of the code would be better if you'd fix that. In Eclipse, you can press Ctrl + Shift + F to automatically fix the indentation</p>\n</li>\n<li><p>In my experience, opening multiple <code>Scanner</code>s yields problems. I'd recommend to open only one <code>Scanner</code> in your main method and then use it in your other methods</p>\n</li>\n<li><p>In <code>setAccountLocation</code>, you use <code>location.equalsIgnoreCase</code> several times. That does nothing. I think you wanted to assign the strings to the location variable, so you can simply write <code>location = "useast";</code> etc.</p>\n</li>\n<li><p>Same for the account types in <code>setAccountType</code>.</p>\n</li>\n<li><p><code>accountType</code> and <code>location</code> are never entered by a user, so you don't need <code>equalsIgnoreCase</code>, but you can simply use <code>equals</code>.</p>\n</li>\n<li><p>I'd recommend to not pass <code>accountType</code> and <code>location</code> as strings, but to create enums for them.</p>\n</li>\n<li><p>in <code>menu</code>, you have the line <code>System.out.println(storedCardNumbers.get(i).toString());</code>. You don't need the <code>toString</code>, because it already is a string. Also the <code>println</code> method implicitly calls the <code>toString</code> method of every Object that you pass.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-24T03:05:35.187",
"Id": "494115",
"Score": "1",
"body": "Awesome thanks for the response! Yea the indentation is fine on intellij so I think it was just when it was copied over. You review was very helpful thank you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-26T08:45:09.493",
"Id": "494311",
"Score": "0",
"body": "You're welcome. There's one more thing that I saw, but forgot to mention. Whenever the user entered an option in the main menu, you call `menu` recursive. That may not become a problem in a small program like this, but in bigger projects you may run out of memory. Also you have to enter 3 for exit multiple times if you chose an incorrect option. You could use a `while (!exit)` loop instead. (PS: Maybe a silly question, but why did you accept the least helpful answer?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-27T09:17:43.107",
"Id": "494430",
"Score": "0",
"body": "It's been a long time since I've been on here so I really forgot how it works and forgot that you accept only one answer. I accepted yours now. Thanks for the help."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T14:26:07.400",
"Id": "251022",
"ParentId": "251009",
"Score": "4"
}
},
{
"body": "<h2>Always use the base class / interface in the left part of the variable when possible</h2>\n<p>By setting the <code>java.util.List</code> interface in the variable part, this could make the code more refactorable in the future, since you could easily change the list type without changing everything (inheritance).</p>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>private static ArrayList<String> storedCardNumbers = new ArrayList<String>();\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>private static List<String> storedCardNumbers = new ArrayList<String>();\n</code></pre>\n<h2>Replace the <code>for</code> loop with an enhanced 'for' loop</h2>\n<p>In your code, you don’t actually need the index provided by the loop, you can the enhanced version.</p>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>for (int i = 0; i < storedCardNumbers.size(); i++) {\n System.out.println(storedCardNumbers.get(i).toString());\n}\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>for (String storedCardNumber : storedCardNumbers) {\n System.out.println(storedCardNumber);\n}\n</code></pre>\n<p>Also, you can remove the <code>.toString()</code> since it's already a String.</p>\n<h2>Remove the dead code</h2>\n<p>In your code, you have multiple places where the code is dead (does nothing) and can be removed.</p>\n<pre class=\"lang-java prettyprint-override\"><code>if (choice == 1) {\n location.equalsIgnoreCase("useast");\n} else if (choice == 2) {\n location.equalsIgnoreCase("uswest");\n} else if (choice == 3) {\n location.equalsIgnoreCase("alaska");\n} else if (choice == 4) {\n location.equalsIgnoreCase("hawaii");\n} else if (choice == 5) {\n location.equalsIgnoreCase("other");\n} else {\n System.out.println("Entered invalid selection.\\n" +\n "Please enter valid selection.");\n setCardAccountType();\n}\n</code></pre>\n<p>For an example, the <code>location.equalsIgnoreCase(...)</code> is dead code in all cases, even if the condition is met (<code>choice >= 1 5 && choice <= 5</code>), the code won’t do anything; you have two similar case like this one.</p>\n<h2>Simplify the boolean conditions.</h2>\n<p>Instead of having <code>exit == false</code>, you can simplify to <code>!exit</code>; also I suggest that you remove the empty <code>else</code> under this condition.</p>\n<h2>Generating random values</h2>\n<p>This is only a suggestion, but you can also use the <code>java.util.concurrent.ThreadLocalRandom#nextInt</code> method to generate a random number in a defined range (inclusive in this case) with java 7+.</p>\n<pre class=\"lang-java prettyprint-override\"><code>ThreadLocalRandom.current().nextInt(0, 100);\n</code></pre>\n<p>You can read an excellent post on <a href=\"https://stackoverflow.com/questions/363681/how-do-i-generate-random-integers-within-a-specific-range-in-java\">SO</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T00:26:04.437",
"Id": "251045",
"ParentId": "251009",
"Score": "3"
}
},
{
"body": "<blockquote>\n<p>This program is used to create a random bank card number. Card number is created using account type and client location for the first eight digits and the remaining 8 digits are completely random.</p>\n</blockquote>\n<p>This isn't a critique of the coding per se, but of the requirements gathering. Bank cards do not allow for a fully random last eight characters. Because the sixteenth character is a <a href=\"https://en.wikipedia.org/wiki/Luhn_algorithm\" rel=\"nofollow noreferrer\">checksum</a>. So you should generate seven random digits, not eight. Then calculate the last digit from the first fifteen.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T02:39:24.913",
"Id": "251047",
"ParentId": "251009",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "251022",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T10:16:08.887",
"Id": "251009",
"Score": "4",
"Tags": [
"java",
"object-oriented",
"recursion"
],
"Title": "Bank Card Generator Code"
}
|
251009
|
<p>I have code that reduces an array until all remaining elements are the same. It takes a first line which contains an integer n, the number of elements in the array, and a second line which contains space-separated integers, the proper array. For instance with the sample input:</p>
<pre><code>5
3 3 2 1 3
</code></pre>
<p>It should return 2, as we only need to remove 2 and 1.</p>
<p>As it looked like an oriented graph I implemented Astar:</p>
<pre><code>#!/bin/python3
import math
import os
import random
import re
import sys
class Node:
def __init__(self, arr):
self.value = len(set(arr))
self.arr = arr
self.parent = None
self.H = 0
self.G = 0
def children(arr):
s = list(set(arr))
children = []
for deleted_element in s:
arr_copy = list(arr)
arr_copy.remove(deleted_element)
child = Node(arr_copy)
children.append(child)
return children
# return [Node([x for x in arr if x!= deleted_element]) for deleted_element in s] # issue
def astar(start, goal):
# the open and closed sets
openset = []
closedset = []
# current point is the starting point
current = start
#add the starting point to the openset
openset.append(current)
# while the openset is not empty
while openset:
current = min(openset, key=lambda o:o.G + o.H)
# if it is the item we want retrace the path and return it
if len(set(current.arr)) == goal:
print("inside, current.arr: " + str(current.arr))
path = []
while current.parent:
print("path in while: " + str([x.arr for x in path]))
path.append(current)
current = current.parent
print("path: " + str([x.arr for x in path]))
path.append(current)
print("path: " + str([x.arr for x in path]))
return path[::-1]
# remove the item from the openset
openset.remove(current)
# add it to the closed set
closedset.append(current)
# loop through the node's children and siblings
print("current.arr: " + str(current.arr))
for node in children(current.arr):
#If it is already in the closed set, skip it
if node in closedset:
continue
#Otherwise if it is already in the open set
if node in openset:
# check if we beat the G score
new_g = current.G + 1
if node.G > new_g:
# if so, update the node to have a new parrent
node.G = new_G
node.parent = current
else:
# if it isn't in the openset, calculate the G and H score for the node
node.G = current.G
node.H = len(set(current.arr))
#Set the parent to our current item
node.parent = current
#add it to the set
openset.append(node)
# thow an error if path is not found
raise ValueError('No Path Found')
def equalizeArray(arr):
startNode = Node(arr)
path = astar(startNode,1)
path.pop(-1)
print("path: " + str(path))
return len(path)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
arr = list(map(int, input().rstrip().split()))
result = equalizeArray(arr)
fptr.write(str(result) + '\n')
fptr.close()
</code></pre>
<p>It works but for some arrays it seems to take too much time. I am not able to find what is the threshold from which my algorithm lacks performance but it does for examples like:</p>
<pre><code>78
24 29 70 43 12 27 29 24 41 12 41 43 24 70 24 100 41 43 43 100 29 70 100 43 41 27 70 70 59 41 24 24 29 43 24 27 70 24 27 70 24 70 27 24 43 27 100 41 12 70 43 70 62 12 59 29 62 41 100 43 43 59 59 70 12 27 43 43 27 27 27 24 43 43 62 43 70 29
</code></pre>
<p>So how can I improve its performance? I am eager to learn and improve my programming skills.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T05:33:51.330",
"Id": "494000",
"Score": "3",
"body": "This is not your code. Code Review requires the you are the author or maintainer of the code in question, and that you understand how the code works, and why it was written the way it is. By your own admission, this code was copied from elsewhere; it is not your own. This makes it ineligible for Code Review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T07:37:20.847",
"Id": "494008",
"Score": "0",
"body": "@AJNeufeld the code I inspired myself from can be found in the link I provided but it didn’t fit to my problem (from graphical matrices to list of numbers. My code modify it in order to do so. Not only do I understand it but I know every bit of it. Last the core of this code is Astar algorithm. Are you expecting me to author a forked version of the algorithm ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T11:08:16.680",
"Id": "494027",
"Score": "0",
"body": "No, we expect you to post code that you wrote. \"So I retyped it in order to learn it and adapted it to my case so I can feel not being a fraud.\" How does your version differ from the original?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T11:46:34.853",
"Id": "494031",
"Score": "1",
"body": "@Mast I wrote it, I based myself on the link I provided. Children function is different, distance are different and I use lists instead of set in Astar function as I thought it is more convenient to manipulate my nodes in Astar function, and I created a way to interact with the terminal. That being said this Astar function tried to be the same algorithm as the one written by Hart, Nilsson and Raphael in 1968. It just take to much time and I was looking for help here to improve its performance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T13:23:27.870",
"Id": "494039",
"Score": "0",
"body": "Thank you for clarifying that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T13:57:47.580",
"Id": "494053",
"Score": "0",
"body": "It still is utterly unclear what the code does. \"Reduces the array until all remaining elements are equal\". Reduces how? And how does that map to the A* algorithm? Since it exceeds some time limit, it is likely a [tag:programming-challenge]; you should provide a link to the actual problem source in addition to clarifying what what the code it trying to accomplish in your description."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T14:26:26.120",
"Id": "494056",
"Score": "0",
"body": "If your code doesn't work as expected, then its off-topic on Code review. Please read [ask]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T16:27:24.207",
"Id": "494074",
"Score": "0",
"body": "@AryanParekh It does work as expected but I am looking to improve it's performance"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T16:28:52.853",
"Id": "494075",
"Score": "0",
"body": "@RevolucionforMonica I misunderstood your question then, I still recommend you to add a little clarity to the question because its a little confusing, can you give any small edit so I can remove my downvote?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T16:31:51.560",
"Id": "494078",
"Score": "0",
"body": "@AryanParekh Sure"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T16:44:51.557",
"Id": "494083",
"Score": "2",
"body": "It's not clear from the question what the coffee should do, please clarify or provide a link to the challenge you're trying to solve."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T11:59:26.060",
"Id": "251011",
"Score": "0",
"Tags": [
"performance",
"python-3.x",
"time-limit-exceeded",
"a-star"
],
"Title": "Astar algorithm exceeds time limit"
}
|
251011
|
<p>I've written a <a href="https://en.wikipedia.org/wiki/Boolean_satisfiability_problem" rel="nofollow noreferrer">3-SAT</a> solver based on <a href="https://open.kattis.com/problems/satisfiability" rel="nofollow noreferrer">this</a> prompt:</p>
<blockquote>
<p>Alice recently started to work for a hardware design company and as a part of her job, she needs to identify defects in fabricated integrated circuits. An approach for identifying these defects boils down to solving a satisfiability instance. She needs your help to write a program to do this task.</p>
<p><strong>Input</strong><br />
The first line of input contains a single integer, not more than 5, indicating the number of test cases to follow. The first line of each test case contains two integers n and m where 1 ≤ n ≤ 20 indicates the number of variables and 1 ≤ m ≤ 100 indicates the number of clauses. Then, m lines follow corresponding to each clause. Each clause is a disjunction of literals in the form Xi or ~Xi for some 1 ≤ i ≤ n, where ~Xi indicates the negation of the literal Xi. The “or” operator is denoted by a ‘v’ character and is separated from literals with a single space.</p>
<p><strong>Output</strong><br />
For each test case, display satisfiable on a single line if there is a satisfiable assignment; otherwise display unsatisfiable.</p>
<p><strong>Sample Input</strong></p>
<pre><code>2
3 3
X1 v X2
~X1
~X2 v X3
3 5
X1 v X2 v X3
X1 v ~X2
X2 v ~X3
X3 v ~X1
~X1 v ~X2 v ~X3
</code></pre>
<p><strong>Sample Output</strong></p>
<pre><code>satisfiable
unsatisfiable
</code></pre>
</blockquote>
<p>This code basically maintains <code>mySets</code> which is a list of sets, which all represent possible combinations of literals that could make the entire statement true. Every time we parse a new clause, we check if it's negation exists already in a set, if it does, the set is not included.</p>
<p>This works, but it runs a bit slow.</p>
<pre><code>import sys
cases = int(sys.stdin.readline())
def GetReverse(literal):
if literal[0] == '~':
return literal[1:]
else:
return '~' + literal
for i in range(cases):
vars, clauses = map(int, sys.stdin.readline().split())
mySets = []
firstClause = sys.stdin.readline().strip().split(" v ")
for c in firstClause:
this = set()
this.add(c)
mySets.append(this)
for i in range(clauses-1):
tempSets = []
currentClause = sys.stdin.readline().strip().split(" v ")
for s in mySets:
for literal in currentClause:
if not s.__contains__(GetReverse(literal)):
newset = s.copy()
newset.add(literal)
tempSets.append(newset)
mySets = tempSets
if mySets:
print("satisfiable")
else:
print("unsatisfiable")
</code></pre>
<p>I think the problem is here, due to the indented for-loops. 3-SAT is supposed to be exponential, but I would like to speed it up a bit (perhaps by removing a loop?)</p>
<pre><code>for i in range(clauses-1):
tempSets = []
currentClause = sys.stdin.readline().strip().split(" v ")
for s in mySets:
for literal in currentClause:
if not s.__contains__(GetReverse(literal)):
newset = s.copy()
newset.add(literal)
tempSets.append(newset)
mySets = tempSets
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T13:56:24.933",
"Id": "493927",
"Score": "0",
"body": "Welcome to the Code Review site, the title of the question should indicate what the code does, rather than your concerns about the code. Links can break so you should include the text of the programming challenge as well. Please read [How do I ask a good question](https://codereview.stackexchange.com/help/how-to-ask). Questions like this should include the programming-challenge tag."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T17:39:48.187",
"Id": "493962",
"Score": "2",
"body": "It looks like the code is not indented correctly. Shouldn't everything from `mySets = []` to the end be indented under `for i in range(cases):`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T18:45:06.733",
"Id": "493968",
"Score": "0",
"body": "There are indeed indentation problems. If you copy and paste this, the syntax errors will show you what's incorrect."
}
] |
[
{
"body": "<p>Here's a suggested implementation that changes basically nothing about your algorithm, but</p>\n<ul>\n<li>has proper indentation</li>\n<li>uses a little bit of type hinting</li>\n<li>uses set literals and generators</li>\n<li>uses <code>_</code> for "unused" variables</li>\n<li>adds a <code>parse_clause()</code> because the clause code is repeated</li>\n<li>uses a <code>StringIO</code>, for these purposes, to effectively mock away <code>stdin</code> and use the example input you showed</li>\n<li>uses PEP8-compliant names (with underscores)</li>\n</ul>\n<pre><code>from io import StringIO\nfrom typing import List\n\nstdin = StringIO('''2\n3 3\nX1 v X2\n~X1\n~X2 v X3\n3 5\nX1 v X2 v X3\nX1 v ~X2\nX2 v ~X3\nX3 v ~X1\n~X1 v ~X2 v ~X3\n'''\n)\n\n\ndef get_reverse(literal: str) -> str:\n if literal[0] == '~':\n return literal[1:]\n return '~' + literal\n\n\ndef parse_clause() -> List[str]:\n return stdin.readline().strip().split(' v ')\n\n\nn_cases = int(stdin.readline())\nfor _ in range(n_cases):\n n_vars, n_clauses = (int(s) for s in stdin.readline().split())\n my_sets = [{c} for c in parse_clause()]\n\n for _ in range(n_clauses - 1):\n temp_sets = []\n current_clause = parse_clause()\n\n for s in my_sets:\n for literal in current_clause:\n if get_reverse(literal) not in s:\n new_set = s.copy()\n new_set.add(literal)\n temp_sets.append(new_set)\n\n my_sets = temp_sets\n\n if my_sets:\n print('satisfiable')\n else:\n print('unsatisfiable')\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T18:58:25.217",
"Id": "251033",
"ParentId": "251013",
"Score": "3"
}
},
{
"body": "<p>If you instrument your code with some strategically place print statements, you will see that there is some repeated computations going on. In the second test case when processing the clause <code>X2 v ~X3</code>, the set <code>{'X1', 'X2'}</code> gets added to <code>mySets</code> twice. When processing the clause <code>X3 v ~X1</code>, the set <code>{'X3', 'X1', 'X2'}</code> gets added to <code>mySets</code> three times.</p>\n<p>For large cases, it might speed things up to change <code>mySets</code> to a <code>set()</code> instead of a list to eliminate the duplicates. Then the inner sets need to be <code>frozensets</code>.</p>\n<p><code>mySets</code> is a set of possible solutions that satisfy all the clauses, so I renamed it to <code>candidates</code>.</p>\n<p>If you initialize <code>candidates</code> to contain a single empty set, then the first clause doesn't need to be handled separately.</p>\n<p>I think you can stop anytime <code>candidates</code> is empty.</p>\n<p>Also, split up the code into functions.</p>\n<pre><code>def is_satisfiable(n_vars, clauses):\n candidates = {frozenset()}\n\n for clause in clauses:\n temp = set()\n\n for s in candidates:\n for literal in clause:\n\n if GetReverse(literal) not in s:\n\n temp.add(s | {literal})\n\n candidates = temp\n \n if len(candidates) == 0:\n return False\n\n return True\n \n \ndef load_case(f):\n n_vars, n_clauses = f.readline().split()\n clauses = [f.readline().strip().split(' v ') for _ in range(int(n_clauses))]\n return int(n_vars), clauses\n \n \ndef main(f=sys.stdin):\n num_cases = int(f.readline())\n\n for i in range(num_cases):\n n_vars, clauses = load_case(f)\n result = is_satisfiable(n_vars, clauses)\n \n print(f"{'satisfiable' if result else 'unsatisfiable'}")\n</code></pre>\n<p>Called like:</p>\n<pre><code>import io\n\ndata = """\n2\n3 3\nX1 v X2\n~X1\n~X2 v X3\n3 5\nX1 v X2 v X3\nX1 v ~X2\nX2 v ~X3\nX3 v ~X1\n~X1 v ~X2 v ~X3 \n""".strip()\n\nmain(io.StringIO(data))\n</code></pre>\n<p>or</p>\n<pre><code>import sys\n\nmain(sys.stdin) \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T21:47:10.237",
"Id": "251042",
"ParentId": "251013",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "251042",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T12:41:42.753",
"Id": "251013",
"Score": "4",
"Tags": [
"python",
"performance",
"algorithm",
"programming-challenge"
],
"Title": "3-SAT Solver Python"
}
|
251013
|
<p>I'm mainly looking for error checking / type safety advice.</p>
<h1>main.cpp</h1>
<pre><code>#include <iostream>
#include <string>
#include <cmath>
#include <numeric>
void binaryToDecimal();
void decimalToBinary();
int main()
{
std::ios::sync_with_stdio(false);
bool running = true;
int ans;
while (running)
{
std::cout << "1. Binary to decimal\n2. Decimal to binary\n3. Quit\n";
std::cin >> ans;
std::cout << '\n';
switch (ans)
{
case 1:
binaryToDecimal();
break;
case 2:
decimalToBinary();
break;
case 3:
running = false;
break;
default:
break;
}
}
return 0;
}
void binaryToDecimal()
{
int out = 0;
std::string in;
std::cout << "Input binary number: ";
std::cin >> in;
int i = in.size() - 1;
if (i > 32)
{
std::cerr << "That number is too big!\n\n";
return;
}
for (int j = 0; i > -1; --i, ++j)
{
out += static_cast<int>(std::pow(2, i)) * (in[j] - '0');
}
std::cout << in << " when converted to decimal is " << out << "\n\n";
}
void decimalToBinary()
{
std::string out = "";
std::string in;
std::cout << "Input decimal number: ";
std::cin >> in;
if (in.size() > std::to_string(std::numeric_limits<int>::max()).size())
{
std::cerr << "That number is too big!\n\n";
return;
}
int mod = std::stoi(in);
while (mod > 0)
{
out += (mod % 2) + '0';
mod /= 2;
}
std::reverse(out.begin(), out.end());
std::cout << in << " when converted to binary is " << out << "\n\n";
}
</code></pre>
|
[] |
[
{
"body": "<h2>General Observations</h2>\n<blockquote>\n<p>I'm mainly looking for error checking / type safety advice.</p>\n</blockquote>\n<p>There doesn't seem to be a lot of error checking on user input and user input is one of the places where error checking is most important. For instance, the code doesn't handle negative numbers but there is not checking for negative input.</p>\n<p>The code also doesn't check for lack of input, and there are no error messages when the input is wrong.</p>\n<h2>Type Safety</h2>\n<p>Since the program doesn't process negative numbers it might be better to use <code>unsigned</code> or <code>unsigned int</code> for conversion rather than <code>int</code>.</p>\n<h2>Unnecessary Function Prototypes</h2>\n<p>If the <code>main()</code> function were placed at the bottom of the file rather than the top of the file, the function prototypes</p>\n<pre><code>void binaryToDecimal();\nvoid decimalToBinary();\n</code></pre>\n<p>are not needed.</p>\n<h2>Magic Numbers</h2>\n<p>There is a Magic Numbers in the <code>binaryToDecimal()</code> function (32), it might be better to create symbolic constants for them to make the code more readable and easier to maintain. These numbers may be used in many places and being able to change them by editing only one line makes maintenance easier.</p>\n<p>Numeric constants in code are sometimes referred to as <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">Magic Numbers</a>, because there is no obvious meaning for them. There is a discussion of this on <a href=\"https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad\">stackoverflow</a>.</p>\n<p>In this case <code>32</code> probably refers to word size, but that is an arbitrary number, most computers these days have a 64 bit word size. You could get the actual size of the word by using the <code>sizeof()</code> function and then multiplying it by 8 since <code>sizeof()</code> the number of char in the object and 8 bits is the size of a char, there also might be a word size constant hidden in an include header.</p>\n<h2>Complexity</h2>\n<p>While <code>main()</code> is pretty simple now, once you start adding the error checking you need it will get more complex, and it should be broken up into different function.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T15:43:25.690",
"Id": "493944",
"Score": "3",
"body": "`std::numeric_limits<T>::digits()` might be a good choice for the maximum number of bits. https://en.cppreference.com/w/cpp/types/numeric_limits/digits"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T23:37:35.000",
"Id": "493990",
"Score": "0",
"body": "None of the answers to [the Q&A you linked](https://stackoverflow.com/q/7349689) mention anything about using a `union` of a natural integer and `std::bitset`. And I would advise *strongly* against it. It isn't going to do what you hope..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T23:42:15.460",
"Id": "493991",
"Score": "0",
"body": "@CodyGray Removed that paragraph."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T09:54:57.803",
"Id": "494023",
"Score": "0",
"body": "I would dispute \"Unnecessary Function Prototypes\" under Robert Martins step down rule. Humans like to read stories in order."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T12:55:20.737",
"Id": "494036",
"Score": "0",
"body": "@candied_orange I think of `main()` as a special case because it is the operating system entry point. The use of `main()` should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program. The functions that `main()` calls are more important than `main()` itself. `main()` is the final chapter in a mystery that ties all the ends together."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T13:40:15.343",
"Id": "494045",
"Score": "0",
"body": "@pacmaninbw no. That’s even worse. If you’re not going to take advantage of modern language tools like forward declaration to enable human readable step down ordering then at least stay consistent with the previous paradigm."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T14:33:38.220",
"Id": "494057",
"Score": "0",
"body": "@candied_orange If you want to discuss this further join me in the [2nd monitor](https://chat.stackexchange.com/rooms/8595/the-2nd-monitor)."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T15:35:09.280",
"Id": "251025",
"ParentId": "251018",
"Score": "7"
}
},
{
"body": "<h1>Handling invalid input</h1>\n<p>Not handling invalid input can be dangerous, especially in this case since it can cause strange outputs. A good practice is to validate the input before you perform any calculations / process it. Here's an example, imagine you opened <em>command prompt</em> on your laptop and entered a false statement. <br>This would show you <code>unknown command x</code>, Instead, what if it started to spit out random numbers endlessly, and crashed in 2-3 seconds? You don't want this to happen with your programs either.</p>\n<h1>Use <code>enum</code>s or <code>enum class</code>s</h1>\n<p>@pacmaninbw has already written in his review the larger downsides of <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">magic numbers</a>. But how do you avoid this? Use an <a href=\"https://en.cppreference.com/w/cpp/language/enum\" rel=\"nofollow noreferrer\">enum</a>. The syntax is simple, and makes your code more readable for others.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>enum Choices\n{ bin_to_dec = 1, dec_to_bin, quit };\n</code></pre>\n<p>This will automatically set <code>dec_to_bin</code> to <code>2</code>, and <code>quit</code> to <code>3</code>. <br></p>\n<p>Now your <code>switch</code> statement is clear;</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>switch ( ans ) \n{\ncase bin_to_dec:\n ....\n\ncase dec_to_bin:\n ....\n\ncase quit:\n ...\n\ndefault:\n ...\n}\n</code></pre>\n<h1>Logic</h1>\n<p>There is a much simpler way to convert decimal to binary in C++. All you have to do is to use <a href=\"https://en.cppreference.com/w/cpp/utility/bitset\" rel=\"nofollow noreferrer\"><strong>std::bitset</strong></a>.</p>\n<p>It would simplify the implementation greatly</p>\n<h2>Decimal to binary</h2>\n<p>Here is an example</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>void dec_to_bin()\n{\n int number = 736;\n std::cout << (std::bitset<32>)number;\n}\n</code></pre>\n<p>I have used <code>32</code> since that is the max size of <code>signed int</code>.</p>\n<p>Output:</p>\n<blockquote>\n<p>00000000000000000000001011100000</p>\n</blockquote>\n<p><a href=\"https://www.binaryconvert.com/result_signed_int.html?decimal=055051054\" rel=\"nofollow noreferrer\">Yes it's the correct answer</a></p>\n<p>You can even use its <code>to_string()</code> method to get a string representation, which might be useful to remove the extra <code>0</code>'s.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>binary.erase(0, binary.find_first_not_of('0')); \nstd::cout << binary;\n</code></pre>\n<blockquote>\n<p>1011100000</p>\n</blockquote>\n<h2>Binary to decimal</h2>\n<p>The best part is, this works the other way around too, by using <code>.to_ulong()</code> assume you have the binary in a string like this.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>std::string binary = "1011100000"; // from our previous example, we know this is = 736\n\nauto decimal = std::bitset<32>(binary).to_ulong();\n\nstd::cout << decimal;\n</code></pre>\n<blockquote>\n<p>736</p>\n</blockquote>\n<p>Remember that validating input before doing this is a must.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T17:32:14.397",
"Id": "251028",
"ParentId": "251018",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T13:49:30.243",
"Id": "251018",
"Score": "8",
"Tags": [
"c++",
"error-handling",
"converting",
"type-safety"
],
"Title": "Binary to decimal (and back) converter in c++"
}
|
251018
|
<p>This is the follow-up question for <a href="https://codereview.stackexchange.com/q/250790/231235">A Summation Function For Various Type Arbitrary Nested Iterable Implementation in C++</a> and <a href="https://codereview.stackexchange.com/q/250895/231235">A Maximum Function For Various Type Arbitrary Nested Iterable Implementation in C++</a>. In the summation and the maximum cases, the recursive technique is used for iterating all elements. The similar recursive structure is also used here. As the title mentioned, I am trying to implement a <code>TransformAll</code> function which can apply a function to arbitrary nested ranges. I know there is a <a href="https://en.cppreference.com/w/cpp/algorithm/transform" rel="nofollow noreferrer"><code>std::transform</code> function</a> which can apply a function to a range and the applied range can be specified by <code>first1, last1</code> parameters. I want to focus on the nested ranges here. The <code>TransformAll</code> function is with two input parameters, one is input ranges, the other is operation function object. The operation function object would be applied to all elements in the input range then return the result. The main implementation is devided into two types. The first one type as follow is the single iterable case, such as <code>std::vector<long double>{ 1, 1, 1 })</code>.</p>
<pre><code>template<class T, class _Fn> requires Iterable<T>
static T TransformAll(const T _input, _Fn _Func); // Deal with the iterable case like "std::vector<long double>"
template<class T, class _Fn> requires Iterable<T>
static inline T TransformAll(const T _input, _Fn _Func)
{
T returnObject = _input;
std::transform(_input.begin(), _input.end(), returnObject.begin(), _Func);
return returnObject;
}
</code></pre>
<p>The second one is to deal with the nested iterable case like <code>std::vector<std::vector<long double>></code>.</p>
<pre><code>template<class T, class _Fn> requires Iterable<T> && ElementIterable<T>
static T TransformAll(const T _input, _Fn _Func);
template<class T, class _Fn> requires Iterable<T> && ElementIterable<T>
static inline T TransformAll(const T _input, _Fn _Func)
{
T returnObject = _input;
std::transform(_input.begin(), _input.end(), returnObject.begin(),
[_Func](auto element)->auto
{
return TransformAll(element, _Func);
}
);
return returnObject;
}
</code></pre>
<p>The usage of the <code>TransformAll</code>:</p>
<pre><code>std::vector<long double> testVector1;
testVector1.push_back(1);
testVector1.push_back(20);
testVector1.push_back(-100);
std::cout << TransformAll(testVector1, [](long double x)->long double { return x + 1; }).at(0) << std::endl;
std::vector<long double> testVector2;
testVector2.push_back(10);
testVector2.push_back(90);
testVector2.push_back(-30);
std::vector<std::vector<long double>> testVector3;
testVector3.push_back(testVector1);
testVector3.push_back(testVector2);
std::cout << TransformAll(testVector3, [](long double x)->long double { return x + 1; }).at(1).at(1) << std::endl;
</code></pre>
<p>All suggestions are welcome.</p>
<p>The summary information:</p>
<ul>
<li><p>Which question it is a follow-up to?</p>
<p><a href="https://codereview.stackexchange.com/q/250790/231235">A Summation Function For Various Type Arbitrary Nested Iterable Implementation in C++</a> and</p>
<p><a href="https://codereview.stackexchange.com/q/250895/231235">A Maximum Function For Various Type Arbitrary Nested Iterable Implementation in C++</a>.</p>
</li>
<li><p>What changes has been made in the code since last question?</p>
<p>The previous question focus on the summation and the maximum operation. The main idea in this question is trying to process all base elements in various nested ranges with a lambda function and remain the origin structure in output result.</p>
</li>
<li><p>Why a new review is being asked for?</p>
<p>I think the design of this <code>TransformAll</code> function is more complex than the previous summation function case and maximum function case. The return value of the summation function case and the maximum function case is a single value. For keeping the origin structure here, the return type in each recursion epoch may be different. In my opinion about this code, there might be some problems existed. In the nested iterable case, is it a good idea about <code>T returnObject = _input;</code>? The size of <code>returnObject</code> is must the same as <code>_input</code> in order to work well with <code>std::transform</code>. Is there any better idea for allocate the size of this <code>returnObject</code>?</p>
</li>
</ul>
<p><strong>Oct 23, 2020 Update</strong></p>
<p>The used <code>Iterable</code> and <code>ElementIterable</code> concepts are here.</p>
<pre><code>template<typename T>
concept Iterable = requires(T x)
{
x.begin(); // must have `x.begin()`
x.end(); // and `x.end()`
};
template<typename T>
concept ElementIterable = requires(T x)
{
x.begin()->begin();
x.end()->end();
};
</code></pre>
|
[] |
[
{
"body": "<h1>Try to match the conventions of the STL</h1>\n<p>Your algorithms are getting more generic. Consider that you would want to use your algorithms in code that also uses regular STL algorithms. Then it is a bit annoying that you are using a different naming convention. At this point, I think it would be helpful to match the conventions of the STL. I would name the function <code>recursive_transform()</code>, since <code>recursive</code> is a bit more precise than <code>all</code>. Try to make it look like <a href=\"https://en.cppreference.com/w/cpp/algorithm/ranges/transform\" rel=\"nofollow noreferrer\">std::ranges::transform()</a>.</p>\n<p>Your earlier implementations could also be made more generic; for example instead of having separte nested sum and nested max functions, make an algorithm that looks like <a href=\"https://en.cppreference.com/w/cpp/algorithm/reduce\" rel=\"nofollow noreferrer\"><code>std::reduce()</code></a>.</p>\n<h1>Avoid making copies of the input</h1>\n<p>In this part of the code:</p>\n<pre><code>std::transform(_input.begin(), _input.end(), returnObject.begin(),\n [_Func](auto element)->auto\n {\n return TransformAll(element, _Func);\n }\n);\n</code></pre>\n<p>You are passing <code>element</code> by value. Since <code>element</code> might be a nested container, that means you are copying potentially a huge amount of memory. This should be <code>auto &element</code>.</p>\n<p>Also note that the <code>->auto</code> return type is redundant.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T21:38:47.863",
"Id": "251041",
"ParentId": "251021",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "251041",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T14:19:50.637",
"Id": "251021",
"Score": "3",
"Tags": [
"c++",
"recursion",
"c++20"
],
"Title": "A TransformAll Function For Various Type Arbitrary Nested Iterable Implementation in C++"
}
|
251021
|
<p>I'm currently going over <a href="https://algs4.cs.princeton.edu/31elementary/" rel="nofollow noreferrer">Robert Sedgewick's Algorithms</a> book. I implemented a Symbol Table using two parallel array one for keys and one for values. The keys array is ordered and the Symbol Table uses binary search to find the position of the elements in the array.</p>
<p>In the practice section, the implementation of the <code>delete</code> and <code>floor</code> method were left as exercises. Here are the directions for <code>delete</code> and <code>floor</code>:
<a href="https://i.stack.imgur.com/w8YHb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/w8YHb.png" alt="enter image description here" /></a>
<a href="https://i.stack.imgur.com/Mmalf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Mmalf.png" alt="enter image description here" /></a></p>
<p>I would like to see if there is any feedback in the implementation of those elements. Specially <code>floor</code>.
Here is the code:</p>
<pre><code># Binary Search Symbol Table in Ruby
class BinarySearchST
attr_accessor :n, :keys, :vals
def initialize
@n = 0
@keys = []
@vals = []
end
def size
@n
end
def is_empty?
@n.zero?
end
def get(key)
return nil if is_empty?
i = rank(key)
if i < @n && @keys[i] == key
@vals[i]
else
nil
end
end
def rank(key)
lo = 0
hi = @n - 1
while lo <= hi
mid = lo + (hi - lo) / 2
cmp = (key <=> @keys[mid])
if cmp < 0
hi = mid - 1
elsif cmp > 0
lo = mid + 1
else
return mid
end
end
lo
end
def put(key, val)
# Search for key. Update value if found; grow table if new
i = rank(key)
if i < @n && @keys[i] == key
return @vals[i] = val
end
j = @n
while j > i
@keys[j] = @keys[j - 1]
@vals[j] = @vals[j - 1]
j -= 1
end
@keys[i] = key
@vals[i] = val
@n += 1
end
def min
@keys[0]
end
def max
@keys[-1]
end
def select(k)
@keys[k]
end
def ceiling(key)
i = rank(key)
@keys[i]
end
def floor(key)
raise 'ilegalArgumentException' if key == nil
raise 'NoSuchElementException' if @keys.empty?
i = rank(key)
if keys[i] == key || i == 0
keys[i]
else
keys[i - 1]
end
end
def delete(key)
raise 'ilegalArgumentException' if key.nil?
i = rank(key)
@keys.delete_at(i)
@vals.delete_at(i)
end
end
bst = BinarySearchST.new
bst.put('s', 0)
bst.put('e', 1)
bst.put('a', 2)
bst.put('r', 3)
bst.put('c', 4)
bst.put('h', 5)
bst.put('e', 6)
bst.put('x', 7)
bst.put('a', 8)
bst.put('m', 9)
bst.put('p', 10)
bst.put('l', 11)
bst.put('e', 12)
binding.pry
p bst.get('e')
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T22:36:42.757",
"Id": "493987",
"Score": "0",
"body": "`raise 'NoSuchElementException' if @keys.empty?` what about the case that the key does not exist?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T23:21:57.830",
"Id": "493988",
"Score": "0",
"body": "it always gives the floor by the `keys[i - 1]`. `i` will always return a index position in the array, if no key is there it will return `keys[i - 1]` which would be the floor"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T23:22:42.650",
"Id": "493989",
"Score": "0",
"body": "if you for example pass `f` to `floor` it would return `e`"
}
] |
[
{
"body": "<p>It's a good implementation, I can make the following improvement suggestions:</p>\n<ul>\n<li><code>size</code>/<code>n</code> aliasing: either add a comment explaining its purpose (a legitimate one could be the need to comply with some external interface), or pick one name and use it throughout the class.</li>\n<li><code>rank(key) < @n</code> checks: change <code>rank</code> to return <code>nil</code> when the key is not found. This is a common Ruby idiom. In Ruby <code>0</code> is truthy unlike many other languages.</li>\n<li><code>@keys[i] == key</code>: This check may be better off in a separate method, i.e. instead of a single <code>rank</code> method have one method that returns the rank when finding and one that returns the place for insertion.</li>\n<li>Exception raises: the idiomatic Ruby way is to define needed exception classes (you could nest them in the <code>BinarySearchST</code> class) rather than raising strings.</li>\n<li>Further on exception raises, it is a good practice to provide a descriptive message when raising each exception.</li>\n<li>It's understandable if you want to move array elements yourself, but Ruby standard library does provide the <a href=\"https://ruby-doc.org/core-2.7.2/Array.html#method-i-insert\" rel=\"nofollow noreferrer\">Array#insert</a> method which would do that for you.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-29T15:49:46.830",
"Id": "251306",
"ParentId": "251023",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T14:35:04.553",
"Id": "251023",
"Score": "1",
"Tags": [
"algorithm",
"ruby"
],
"Title": "Ruby Symbol Table implementation using Binary Search"
}
|
251023
|
<p>I'm learning Clojure and am a rank n00b at it, trying to learn from books and online tutorials (but I'm sometimes concerned that I am picking up bad habits or at least not all the good habits). For exercise I did the <a href="https://www.hackerrank.com/challenges/breaking-best-and-worst-records" rel="nofollow noreferrer">Breaking the Records</a> problem on Hackerrank.</p>
<h2>TL;DR problem description:</h2>
<p><strong>For a list of scores (in historic order), count the number of times the previous best score was exceeded as well as the previous worst score was undercut.</strong></p>
<p>In an iterative language it is quite easy to <a href="https://codereview.stackexchange.com/a/188606">just iterate through the list</a>; but Clojure does not do iteration and I decided to tackle this problem for exercise in constructing a (tail end) recursive solution. To make it easier for myself, I first did a recursive solution in Java, which I then translated. All in all, it's quite a simple recursive function without rocket surgery involved.</p>
<p>Obviously my code works, as shown by the included unit tests. My concerns are however as follows:</p>
<ul>
<li>When put next to the Java code, the two look fairly similar. Did I follow "idiomatic" Clojure programming, or is it just a clumsy "word-for-word transliteration"?</li>
<li>Are there any areas that could have been more compact and/or easier to understand by using different Clojure constructs?</li>
</ul>
<p>Your critical input will be highly appreciated - <strong>including regarding the unit testing</strong>, as that is arguably an important part of programming, which I want to learn and practice in parallel.</p>
<p>Code:</p>
<pre class="lang-clojure prettyprint-override"><code>(ns hackerrank.breaking-records
(:require [clojure.test :refer :all]))
(defrecord Record [min max countworse countbetter])
(defn recalc-record [rec newscore]
(Record.
(min newscore (:min rec))
(max newscore (:max rec))
(+ (:countworse rec) (if (> (:min rec) newscore) 1 0))
(+ (:countbetter rec) (if (< (:max rec) newscore) 1 0))))
(defn accumulate [curr-record remaining-scores]
(if (nil? (second remaining-scores))
curr-record
(recur (recalc-record curr-record (second remaining-scores)) (rest remaining-scores)))
)
(defn breaking-records [scores]
(let [result (accumulate (Record. (first scores) (first scores) 0 0) scores)]
(list (:countbetter result) (:countworse result))))
(deftest test-records
(testing "edge cases"
(is (= '(0 0) (breaking-records '())) "no games played yet")
(is (= '(0 0) (breaking-records '(5))) "single game"))
(testing "hackerrank examples"
(is (= '(2 4) (breaking-records '(10 5 20 20 4 5 2 25 1))))
(is (= '(4 0) (breaking-records '(3 4 21 36 10 28 35 5 24 42)))))
)
</code></pre>
|
[] |
[
{
"body": "<p>I re-wrote your solution to use more typical Clojure features. When you are looping over data and need to keep track of accumulated state, it is hard to beat <code>loop/recur</code>. A first example:</p>\n<pre><code>(ns tst.demo.core\n (:use clojure.test))\n\n(defn breaking-records\n [scores]\n ; this loop has 5 variables. Init all of them\n (loop [low (first scores)\n high (first scores)\n nworse 0\n nbetter 0\n score-pairs (partition 2 1 scores)]\n (if (empty? score-pairs)\n {:nbetter nbetter :nworse nworse}\n (let [curr-score-pair (first score-pairs)\n new-score (second curr-score-pair)]\n ; start the next iteration with modified versions of the 5 loop vars\n (recur\n (min new-score low)\n (max new-score high)\n (if (< new-score low)\n (inc nworse)\n nworse)\n (if (< high new-score)\n (inc nbetter)\n nbetter)\n (rest score-pairs))))))\n</code></pre>\n<p>and unit tests:</p>\n<pre><code>(deftest test-records\n (testing "edge cases"\n (is (= (breaking-records []) {:nbetter 0 :nworse 0}) "no games played yet")\n (is (= (breaking-records [5]) {:nbetter 0 :nworse 0}) "single game"))\n (testing "hackerrank examples"\n (is (= (breaking-records [10 5 20 20 4 5 2 25 1]) {:nbetter 2 :nworse 4}))\n (is (= (breaking-records [3 4 21 36 10 28 35 5 24 42]) {:nbetter 4 :nworse 0}))))\n\n; ***** NOTE: it's much easier to use vectors like [1 2 3] instead of a quoted list `(1 2 3)\n</code></pre>\n<p>Please see <a href=\"https://github.com/io-tupelo/clj-template#documentation\" rel=\"nofollow noreferrer\">this list of documentation</a>, esp. the Clojure CheatSheet. Also, the template project as a whole shows how I like to structure things. :)</p>\n<p>The function that helps the most is <code>partition</code>. <a href=\"https://clojuredocs.org/clojure.core/partition\" rel=\"nofollow noreferrer\">See the docs</a>.</p>\n<hr />\n<h2>Slight refactoring</h2>\n<p>You can simplify it a small amount and make it a bit more compact by using more specialized functions like <code>reduce</code> and <code>cond-></code>. This version uses a map to hold state and <code>reduce</code> to perform the looping:</p>\n<pre><code>(defn breaking-records\n [scores]\n (let [state-init {:low (first scores)\n :high (first scores)\n :nworse 0\n :nbetter 0}\n accum-stats-fn (fn [state score-pair]\n ; Use map destructuring to pull out the 4 state variables\n (let [{:keys [low high nworse nbetter]} state \n new-score (second score-pair)\n state-new {:low (min new-score low)\n :high (max new-score high)\n :nworse (cond-> nworse\n (< new-score low) (inc))\n :nbetter (cond-> nbetter\n (< high new-score) (inc))}]\n state-new))\n state-final (reduce accum-stats-fn\n state-init\n (partition 2 1 scores))\n result (select-keys state-final [:nworse :nbetter])]\n result))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-26T15:08:54.783",
"Id": "494366",
"Score": "0",
"body": "I *highly* appreciate you taking the time to do this, it does point me to some areas I should be focusing on for learning. It does seem you have not bought into the \"small functions\" exhortations of the Clean Code book/ideology :-) (To be honest, I have started to get second thoughts about that bit too. Ironically, Robert C. Martin's enthusiasm regarding Clojure was a contributing factor for my interest in it.) Also, is there a specific reason for [] being \"much easier\" than '(), *apart* from the one extra character and it standing out from the surrounding parentheses?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-26T15:14:31.170",
"Id": "494368",
"Score": "1",
"body": "When you print a quoted list, the quote disappears, so you always have to add it back when you cut/paste. Same for double-quotes on a string, which is why keywords are nicer for non-user data (e.g. `:nworse`)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T19:14:10.000",
"Id": "251035",
"ParentId": "251024",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "251035",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T14:38:47.397",
"Id": "251024",
"Score": "5",
"Tags": [
"beginner",
"programming-challenge",
"recursion",
"unit-testing",
"clojure"
],
"Title": "Hackerrank: Breaking the records"
}
|
251024
|
<p>I'm currently going over <a href="https://algs4.cs.princeton.edu/31elementary/" rel="nofollow noreferrer">Robert Sedgewick's Algorithms</a> book. I implemented a Symbol Table using two parallel arrays one for keys and one for values. The <code>keys</code> array is ordered and the Symbol Table uses binary search to find the position of the elements in the array.</p>
<p>In the practice section, the implementation of the <code>delete</code> and <code>floor</code> method were left as exercises. Here are the directions for <code>delete</code> and <code>floor</code>:</p>
<p><a href="https://i.stack.imgur.com/vvFtc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vvFtc.png" alt="enter image description here" /></a>
<a href="https://i.stack.imgur.com/0R56p.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0R56p.png" alt="enter image description here" /></a></p>
<p>I would like to see if there is any feedback in the implementation of those elements. Specially <code>floor</code>.</p>
<p>I come from Ruby, so any feedback regarding best practices in JavaScript is also welcome.</p>
<p>Here is the code:</p>
<pre><code>class BinarySearchSt {
constructor() {
this.n = 0;
this.keys = [];
this.vals = [];
}
isEmpty() {
return this.n === 0;
}
get(key) {
if(this.isEmpty() === true) {
return null;
}
let i = this.rank(key);
if (i < this.n && this.keys[i] === key) {
return this.vals[i];
} else {
return null;
}
}
put(key, val) {
let i = this.rank(key);
if(i < this.n && this.keys[i] === key) {
return this.vals[i] = val;
}
for(let j = this.n; j > i; j--) {
this.keys[j] = this.keys[j - 1];
this.vals[j] = this.vals[j - 1];
}
this.keys[i] = key;
this.vals[i] = val;
this.n++;
}
rank(key) {
let lo = 0;
let hi = this.n - 1;
while(lo <= hi) {
let mid = lo + Math.floor((hi - lo) / 2);
let cmp = this.compareTo(key, this.keys[mid]);
if(cmp < 0) {
hi = mid - 1;
} else if(cmp > 0) {
lo = mid + 1;
} else {
return mid;
}
}
return lo;
}
compareTo(val1, val2) {
if((val1 === null || val2 === null) || (typeof val1 !== typeof val2)) {
return null;
}
if (typeof val1 === 'string') {
return (val1).localeCompare(val2);
} else {
if(val1 > val2){
return 1;
} else if (val1 < val2) {
return -1;
}
return 0;
}
}
min() {
return this.keys[0];
}
max() {
return this.keys[-1]
}
select(index) {
return this.keys[index];
}
ceiling(key) {
let i = this.rank(key);
return this.keys[i];
}
floor(key) {
if(this.n === 0) {
throw 'noSuchElementException';
}
if(key === null) {
throw 'ilegalArgumentException';
}
let i = this.rank(key);
if(this.keys[i] === key || i === 0){
return this.keys[i];
}
else {
return this.keys[i - 1];
}
}
delete(key) {
if(key === null) { throw 'ilegalArgumentException' };
let i = this.rank(key);
this.keys.splice(i, 1);
this.vals.splice(i, 1);
}
}
const bst = new BinarySearchSt();
bst.put('s', 0)
bst.put('e', 1)
bst.put('a', 2)
bst.put('r', 3)
bst.put('c', 4)
bst.put('h', 5)
bst.put('e', 6)
bst.put('x', 7)
bst.put('a', 8)
bst.put('m', 9)
bst.put('p', 10)
bst.put('l', 11)
bst.put('e', 12)
console.log(bst.get('e'))
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T19:21:22.543",
"Id": "251036",
"Score": "1",
"Tags": [
"javascript",
"algorithm"
],
"Title": "JavaScript Symbol Table implementation using Binary Search"
}
|
251036
|
<pre class="lang-py prettyprint-override"><code>with open('things.txt') as things:
urls = [url.strip().lower() for url in things]
async def is_site_404(s, url):
async with s.head(f"https://example.com/{url}") as r1:
if r1.status == 404:
print('hello i am working')
async def create_tasks(urls):
tasks = []
async with aiohttp.ClientSession() as s:
for url in urls:
if len(url) >= 5 and len(url) < 16 and url.isalnum():
task = asyncio.create_task(is_site_404(s, url))
tasks.append(task)
return await asyncio.gather(*tasks)
while True:
asyncio.get_event_loop().run_until_complete(create_tasks(urls))
</code></pre>
<p>Hi, this is a basic asynchronous url response checker that I created and it's pretty fast, but I'm wondering if there is any way to get more requests per second with the base of this code. I have it designed so that it runs forever and just prints whenever there is a 404 in this example basically. I'm pretty new to python and coding in general and I would like some guidance/advice from anyone who has more experience with this kind of thing.. maybe there is an aiohttp alternative I should use that's faster? ANY advice is greatly appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T06:41:58.897",
"Id": "494003",
"Score": "0",
"body": "Hi, please [edit] your question so the title states what your code does since reviewers would usually wanna see that first. This is mentioned in [ask]. I would've done this for you, but since it's your question I think you can choose the most appropriate title"
}
] |
[
{
"body": "<p>Overall, your code looks pretty decent. The functions are doing what they should be (<code>create_task</code> shouldn't be running the tasks as well), coroutines are gathered after aggregation.</p>\n<p>I'd suggest a few things to make it more readable (and maintainable)</p>\n<h2><code>if __name__</code> block</h2>\n<p>Put script execution content inside the <code>if __name__ == "__main__"</code> block. Read more about why <a href=\"https://stackoverflow.com/q/419163/1190388\">on stack overflow</a>.</p>\n<h2>Variable naming</h2>\n<p>While you follow the PEP-8 convention on variable naming, the names still could use a rework, for eg. <code>session</code> instead of just <code>s</code>.</p>\n<h2>URL or path</h2>\n<p>URL refers to "<em>Uniform Resource Locator</em>", which is of the form:</p>\n<pre><code>scheme:[//authority]path[?query][#fragment]\n</code></pre>\n<p>You are dealing with only the <code>path</code> here, scheme and authority sections have been fixed as <code>https://example.com/</code>. This is again naming convenience.</p>\n<h2>Gather vs create</h2>\n<p>You are creating as well as gathering tasks in <code>create_tasks</code> function.</p>\n<h2>Type hinting</h2>\n<p>New in python-3.x is the type hinting feature. I suggest using it whenever possible.</p>\n<hr />\n<h3>Rewrite</h3>\n<pre><code>import asyncio\nimport aiohttp\n\nHOST = "https://example.com"\nTHINGS_FILE = "things.txt"\n\n\ndef validate_path(path: str) -> bool:\n return 5 <= len(path) < 16 and path.isalnum()\n\n\nasync def check_404(session: aiohttp.ClientSession, path: str):\n async with session.head(f"{HOST}/{path}") as response:\n if response.status == 404:\n print("hello i am working")\n\n\nasync def execute_requests(paths: list[str]):\n async with aiohttp.ClientSession() as session:\n tasks = []\n for path in paths:\n if validate_path(path):\n task = asyncio.create_task(check_404(session, path))\n tasks.append(task)\n return await asyncio.gather(*tasks)\n\n\ndef main():\n with open(THINGS_FILE) as things:\n paths = [line.strip().lower() for line in things]\n while True:\n asyncio.get_event_loop().run_until_complete(execute_requests(paths))\n\n\nif __name__ == "__main__":\n main()\n</code></pre>\n<p>This can be further rewritten depending on the data being read from file, using a map/filter to only iterate over validated <code>path</code>s in file etc. The above is mostly a suggestion.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T20:46:46.257",
"Id": "494104",
"Score": "0",
"body": "thank you for the insight, really appreciate it and will apply this stuff in the future."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-24T08:35:03.023",
"Id": "494124",
"Score": "0",
"body": "@humid Why haven't you updated the title yet?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T10:15:56.077",
"Id": "251055",
"ParentId": "251037",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T19:43:12.167",
"Id": "251037",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"asynchronous",
"url"
],
"Title": "How can this async url response checker be cleaner/faster?"
}
|
251037
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.