body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>Just created an overlay on hover following a Youtube tutorial - but I adjusted some css to make it responsive.</p>
<p>I'd like to hear hear some reviews or suggestions where I can improve.</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-css lang-css prettyprint-override"><code>#Projects .card {
position: relative;
overflow: hidden;
}
#Projects .card:before {
position: absolute;
content: '';
width: 80%;
height: 220%;
background:rgba(199, 0, 57, .9);
top: -50%;
left: -100%;
z-index: 1;
transform: rotate(20deg);
transform-origin: center top 0;
transition: .5s;
}
#Projects .card:hover:before {
left: 10%;
}
#Projects .card .card-text {
width: 100%;
padding: 0 20px;
position: absolute;
top: -150%;
color: #fff;
left: 0;
z-index: 2;
transition: .5s;
}
#Projects .card:hover .card-text {
top: 20%;
}
@media (max-width: 992px) {
#Projects .card:hover .card-text {
top: 15%;
}
#Projects .card-text a {
font-size: 11px;
}
#Projects .btn {
padding: 5px 15px;
}
#Projects .card-text h3 {
font-size: 18px;
}
#Projects .card-text h5 {
font-size: 18px;
}
}
@media (max-width: 575px) {
#Projects .btn {
padding: 5px 24px;
font-size: 1.1rem;
}
#Projects .card-text h3 {
font-size: 1.5rem;
}
#Projects .card-text h5 {
font-size: 1.5rem;
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<section id="Projects">
<div class="container">
<div class="row">
<div class="col-md-6 col-sm-6">
<div class="card">
<img class="card-img-top img-fluid" src="https://recruiterflow.com/blog/wp-content/uploads/2017/10/stackoverflow.png" alt="Card image cap">
<div class="card-text">
<h3>Project 1</h3>
<h5>Some text...</h5>
<a class="btn btn-primary" href="">View</a>
</div>
</div>
</div>
<div class="col-md-6 col-sm-6">
<div class="card">
<img class="card-img-top img-fluid" src="https://recruiterflow.com/blog/wp-content/uploads/2017/10/stackoverflow.png" alt="Card image cap">
<div class="card-text">
<h3>Project 2</h3>
<h5>Some text...</h5>
<a class="btn btn-primary" href="">View</a>
</div>
</div>
</div>
</div>
</div>
</section></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<p>In large projects is important to save as much space as possible.\nYour selectors are way to specific for example :</p>\n<pre><code>#Projects .card .card-text {}\n</code></pre>\n<p>Whereas this will do:</p>\n<pre><code>.card-text {}\n</code></pre>\n<p>If the purpose of this was a different card-text in a different card you can add another class to card-text as a modifier</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T09:00:59.710",
"Id": "249944",
"ParentId": "249879",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T11:16:40.287",
"Id": "249879",
"Score": "1",
"Tags": [
"html",
"css",
"bootstrap-4"
],
"Title": "Hover on bootstrap card overlay"
}
|
249879
|
<p>My solution to implement a status (string) from combining two other ones.
I need to declare a function which takes two params (two strings) and needs to return another one based on the combination of those two strings.
For ex:</p>
<pre><code>carStatus(status, secondaryStatus) => string
</code></pre>
<p>where secondaryStatus can have multiple options.
I'm using an if/else if statement which returns a third status which I need.
For ex when status is 'OPEN' and secondaryStatus is 'payment1' or 'payment2' or 'payment3', the function must return a new string (status) like 'CONFIRMED'.
So, my solution at this moment would be something like this:</p>
<pre><code>carStatus = (status, secondaryStatus) => {
if(status === 'OPEN' && (secondaryStatus === 'payment1' || 'payment2' || 'payment3')){
return 'CONFIRMED';
} else if(status === 'CANCELLED' && (secondaryStatus === 'payment4' || 'payment5' || 'payment6')){
return 'REMOVED';
} else if(status === 'REVIEW' && (secondaryStatus === 'payment2' || 'payment5' || 'payment5')){
return 'CHECKED';
}
}
<div>carStatus('OPEN', 'payment1')</div>
</code></pre>
<p>In div must be rendered 'CONFIRMED'.</p>
<p>In my implementation, I'll have to write I think other 5 else if statements.. so maybe there is a cleaner way to implement this.</p>
<p>Any help will be appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T12:12:15.690",
"Id": "490239",
"Score": "1",
"body": "Once a question has been answered [it should not be edited/modified](https://codereview.stackexchange.com/help/someone-answers) so that all reviews/answers will be on the same code. You can put the changes in a follow up question."
}
] |
[
{
"body": "<p><strong>Condition bug</strong> Your current implementation has a bug. Your lines like these have the problem:</p>\n<pre><code>(secondaryStatus === 'payment1' || 'payment2' || 'payment3')\n</code></pre>\n<p>JavaScript only has unary operators, binary operators, and a single ternary operator. All the operators used above are binary operators; two expressions will be evaluated into a single expression until a single one is left. Since <code>===</code> has higher operator precedence than <code>||</code>, your code is equivalent to:</p>\n<pre><code>(secondaryStatus === 'payment1' || 'payment2' || 'payment3')\n\n(trueOrFalse || 'payment2' || 'payment3')\n</code></pre>\n<p>The <code>payment2</code> and <code>payment3</code> are not compared against <code>secondaryStatus</code>, and if <code>secondaryStatus</code> is not <code>payment1</code>, the whole expression will evaluate to <code>'payment2'</code>, a truthy value (because <code>||</code> will evaluate to the second value if the first is falsey):</p>\n<pre><code>// || operates left-to-right:\n\n(trueOrFalse || 'payment2' || 'payment3')\n\n((false || 'payment2') || 'payment3')\n\n(('payment2') || 'payment3')\n\n// payment2 is truthy, so the `||` evaluates to it:\n('payment2')\n</code></pre>\n<p>To fix the logic, use an array instead, and check the status against each element in the array.</p>\n<p><strong>Typo?</strong> You have <code>(secondaryStatus === 'payment2' || 'payment5' || 'payment5')</code>, with <code>payment5</code> repeated twice. Did you mean something else, like <code>payment9</code>?</p>\n<p><strong>Names</strong> <code>carStatus</code> does not contain the car's status, as it would sound to contain; it's a function that, when called, returns the car's status. It also takes a confusingly-similarly named <code>status</code> parameter. Call them something else, if at all possible: perhaps <code>getCarStatus</code> and whatever more specific thing the <code>status</code> parameter represents. Maybe call <code>secondaryStatus</code>: <code>paymentType</code>.</p>\n<p><strong>DRY</strong> You also want to make the code more DRY, which fits in well with the idea of using arrays instead. You might use an object, whose keys are the status that's required, and whose values are the possible <code>secondaryStatus</code> values as well as the return value if the <code>secondaryStatus</code> is found.</p>\n<p>Also, since all the payment strings end in a number, and that number is the only thing that changes, use that number to set up the config object instead of the full <code>payment</code> strings:</p>\n<pre><code>const statusOptions = {\n OPEN: { paymentNumbers: [1, 2, 3], status: 'CONFIRMED' },\n CANCELLED: { paymentNumbers: [4, 5, 6], status: 'REMOVED' },\n REVIEW: { paymentNumbers: [2, 5], status: 'CHECKED' },\n};\n// ...\ngetCarStatus = (status, paymentType) => {\n const possibleOption = statusOptions[status];\n if (possibleOption) {\n const paymentNumber = Number(paymentType.match(/\\d+$/)[0]);\n if (possibleOption.paymentNumbers.includes(paymentNumber)) {\n return possibleOption.status;\n }\n }\n}\n</code></pre>\n<p>Live snippet:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const statusOptions = {\n OPEN: { paymentNumbers: [1, 2, 3], status: 'CONFIRMED' },\n CANCELLED: { paymentNumbers: [4, 5, 6], status: 'REMOVED' },\n REVIEW: { paymentNumbers: [2, 5], status: 'CHECKED' },\n};\n// ...\ngetCarStatus = (status, paymentType) => {\n const possibleOption = statusOptions[status];\n if (possibleOption) {\n const paymentNumber = Number(paymentType.match(/\\d+$/)[0]);\n if (possibleOption.paymentNumbers.includes(paymentNumber)) {\n return possibleOption.status;\n }\n }\n};\n\nconsole.log(\n getCarStatus('OPEN', 'payment3'),\n getCarStatus('REVIEW', 'payment2')\n);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p><strong>Component type</strong> It looks like you're using a class component. <a href=\"https://reactjs.org/docs/hooks-faq.html#should-i-use-hooks-classes-or-a-mix-of-both\" rel=\"nofollow noreferrer\">React recommends</a> that you try out using functional components in new code; they say they're a bit easier to work with and understand than class-based components in most circumstances, and I agree. Try using functional components instead, if you haven't already, you might like them.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T08:34:29.150",
"Id": "490211",
"Score": "0",
"body": "Thank you for your help. I tried to fix the logic, to use an array, but I have issues on implementing and understanding, can you please provide an example of how should I implement the logic and check against each element of the array?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T11:08:27.073",
"Id": "490220",
"Score": "0",
"body": "I've updated my solution"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T13:45:41.737",
"Id": "490250",
"Score": "1",
"body": "@Christian The last code block in the question and the live snippet do that, no alterations required to the caller of `getCarStatus`. Eg `getCarStatus('OPEN', 'payment3')` returns `CONFIRMED`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T14:23:37.293",
"Id": "490254",
"Score": "0",
"body": "Thank you for your time and help. Really appreciate it."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T15:01:05.113",
"Id": "249889",
"ParentId": "249881",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249889",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T12:18:38.647",
"Id": "249881",
"Score": "3",
"Tags": [
"javascript",
"react.js"
],
"Title": "Javascript / React data mapper"
}
|
249881
|
<p>I have a basic articles sorting application, the <code>App</code> component gets some articles and pass them to the <code>Articles</code> component which renders a list of the articles sorted by date or by upvotes.</p>
<p>Each article is an object with <code>id</code> (string), <code>title</code> (string), <code>upvotes</code> (number), and <code>date</code> (string format <code>YYYY-MM-DD</code>) properties.</p>
<p>By default the articles are shown by upvotes in descending order.</p>
<p>This is the <code>Articles</code> component:</p>
<pre><code>import React from "react";
function Articles({ articles }) {
return (
<div>
<table>
<thead>
<tr>
<th>Title</th>
<th>Upvotes</th>
<th>Date</th>
</tr>
</thead>
<tbody>
{articles.map(({id, title, upvotes, date}) => (
<tr key={id}>
<td>{title}</td>
<td>{upvotes}</td>
<td>{date}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
export default Articles;
</code></pre>
<p>And this is the <code>App</code> component:</p>
<pre><code>import React, { useState } from 'react';
import './App.css';
import Articles from './components/Articles';
function App({ articles }) {
const sortByUpvotesDesc = (a,b) => b.upvotes - a.upvotes
const sortByDateDesc = (a,b) => b.date > a.date ? 1 : b.date === a.date ? 0 : -1
const [articlesOrder, setArticlesOrder] = useState('byUpvotesDesc')
const mostUpvotedClickHandler = () => {
setArticlesOrder('byUpvotesDesc')
}
const mostRecentClickHandler = () => {
setArticlesOrder('byDatesDesc')
}
return (
<div className="App">
<div>
<label>Sort By</label>
<button onClick={mostUpvotedClickHandler} >Most Upvoted</button>
<button onClick={mostRecentClickHandler} >Most Recent</button>
</div>
<Articles articles={articles.sort(articlesOrder === 'byUpvotesDesc' ? sortByUpvotesDesc : sortByDateDesc)} />
</div>
);
}
export default App;
</code></pre>
<p>I would appreciate any insights and feedback on how to improve this, especially regarding the <code>App</code> component.</p>
|
[] |
[
{
"body": "<p><strong>Date sorting</strong> Your dates are of the format <code>YYYY-MM-DD</code>. You currently sort them with:</p>\n<pre><code>(a, b) => b.date > a.date ? 1 : b.date === a.date ? 0 : -1\n</code></pre>\n<p>When you want to lexiographically compare strings to determine which comes first in the alphabet for sorting, you can do it more concisely with <code>localeCompare</code>, which returns a number indicating whether one string comes before, is the same as, or after another. You can use:</p>\n<pre><code>(a, b) => b.date.localeCompare(a.date);\n</code></pre>\n<p><strong>articlesOrder</strong>'s state relies on, essentially, magic strings:</p>\n<pre><code>const [articlesOrder, setArticlesOrder] = useState('byUpvotesDesc')\n</code></pre>\n<p>Since there are only two possible sorting methods, you might consider using a boolean instead:</p>\n<pre><code>const [orderByUpvotes, setOrderByUpvotes] = useState(true)\n</code></pre>\n<p>If there were more sorting methods, I would feel a bit more comfortable using an enum of sorts (or TypeScript to enforce string comparison safety) than comparing strings like <code>articlesOrder === 'byUpvotesDesc'</code> that need to match across multiple places in the code. For example:</p>\n<pre><code>const SORTING_OPTIONS = {\n byUpvotesDesc: 0,\n byDatesDesc: 1,\n // ...\n};\n// ...\nconst [articlesOrder, setArticlesOrder] = useState(SORTING_OPTIONS.byUpvotesDesc);\n</code></pre>\n<p>Another option would be to omit the <code>articlesOrder</code> variable entirely, and instead only sort the articles when a button is clicked (see below) - but if you want to expand on the component, keeping an <code>articlesOrder</code> variable will probably be useful to indicate to the user what the current sorting order is (for example, to give the top container a visual indicator of what option is currently selected).</p>\n<p><strong>Mutation</strong> You are mutating the prop when you do:</p>\n<pre><code><Articles articles={articles.sort(articlesOrder === 'byUpvotesDesc' ? sortByUpvotesDesc : sortByDateDesc)} />\n</code></pre>\n<p>because <code>.sort</code> sorts in-place. Put the prop into state instead, and when a new sort order needs to occur, copy the array before sorting it so as not to mutate. Also, rather than <code>.sort</code>ing <em>every time</em> the component is rendered, it would be better to sort only when the sort order changes. Here's one possible approach:</p>\n<pre><code>const sortByUpvotesDesc = (a, b) => b.upvotes - a.upvotes\nconst sortByDateDesc = (a, b) => b.date.localeCompare(a.date);\n\nfunction App({ articles: articlesProp }) {\n const [articles, setArticles] = useState(articlesProp);\n const [articlesOrder, setArticlesOrder] = useState();\n\n const sortArticles = (callback) => {\n setArticles(\n articles => articles.slice().sort(callback)\n );\n };\n // The below could be made more abstract and DRY if there were more options\n // but with only two, it would probably be more confusing than useful\n const mostUpvotedClickHandler = () => {\n sortArticles(sortByUpvotesDesc);\n setArticlesOrder(SORTING_OPTIONS.byUpvotesDesc);\n };\n const mostRecentClickHandler = () => {\n sortArticles(sortByDateDesc);\n setArticlesOrder(SORTING_OPTIONS.byDatesDesc);\n };\n // Sort articles on initial mount, before they're rendered, to avoid reflow:\n useLayoutEffect(mostUpvotedClickHandler, []);\n\n return (\n <div className="App">\n <div>\n <label>Sort By</label>\n <button onClick={mostUpvotedClickHandler} >Most Upvoted</button>\n <button onClick={mostRecentClickHandler} >Most Recent</button>\n </div>\n <Articles articles={articles} />\n </div>\n );\n}\n</code></pre>\n<p><strong>Semicolons</strong> Best to be consistent; either use semicolons or don't. If you're skilled and confident that you won't be bitten by the rules of <a href=\"https://stackoverflow.com/questions/2846283/what-are-the-rules-for-javascripts-automatic-semicolon-insertion-asi\">ASI</a>, you can omit them. Use a <a href=\"https://eslint.org/docs/rules/semi\" rel=\"nofollow noreferrer\">linter</a> to enforce your desired style across your codebase.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T00:53:30.200",
"Id": "490073",
"Score": "0",
"body": "Thanks for taking the time to review my code, this is incredibly valuable feedback, I'm internalizing every point you mentioned :D."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T14:39:09.953",
"Id": "249887",
"ParentId": "249882",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "249887",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T13:07:38.833",
"Id": "249882",
"Score": "1",
"Tags": [
"javascript",
"react.js"
],
"Title": "Simple React component to show sorted articles"
}
|
249882
|
<p>I made the following code in C, which is supposed to create a list of booleans $n + 1$ long, such that the $i$'th element is true if $i$ is prime and $i$'th element is false if $i$ is not prime (starting the count from zero). So for n = 10, it is supposed to give [false, false, true, true, false, true, false, true, false, false, false].</p>
<p>The logic of the program works, in the sense that the array primes in sieve(long n) is correct. However, when calling it in main, it gives a wrong result. I expect this has something to do with the pointers.</p>
<p>I have another question if that's ok: is it useful to use pointers here? I've been told that pointers are good when working with large amounts of data, but I don't see how it helps as you have to create a normal variable first, the address of which you then assign to the pointer.</p>
<pre><code>
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <math.h>
bool *sieve(long n) {
bool primes[n + 1]; // we go 0, ..., n such that primes[i] is true iff i is prime
primes[0] = false;
primes[1] = false;
for (int i = 2; i < n + 1; i++) {
primes[i] = true;
}
for (int prime = 2; prime < sqrt(n) + 1; prime++) {
if (primes[prime]) {
for (int j = prime*prime; j < n + 1; j += prime) {
primes[j] = false;
}
}
}
bool (*primesLocation)[n + 1] = malloc((n + 1) * sizeof(bool));
primesLocation = &primes;
return primesLocation;
}
int main(int argc, char **argv){
bool* primes = sieve(100);
for (int i = 0; i < 101; i++) {
if (primes[i]) {
printf("%d, ", i);
}
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T14:47:05.010",
"Id": "490032",
"Score": "3",
"body": "The array `primes[]` no longer exists when you return from the function. Therefore, the pointer you return is invalid. Create the array in `main()` and give `sieve()` a pointer to it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T14:50:09.500",
"Id": "490034",
"Score": "3",
"body": "Welcome to Code Review, where we review code that is working as expected and provide suggestions on how to improve that code. Can you explain exactly how the result is wrong if the primes are correct? This statement `However, when calling it in main, it gives a wrong result. I expect this has something to do with the pointers.` makes the question off-topic because the code isn't working as expected."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T15:15:10.710",
"Id": "490035",
"Score": "0",
"body": "@G.Sliepen VTC, the code is definitely broken."
}
] |
[
{
"body": "<p>Your function is mallocing a value, and then overwriting it with a pointer to a local array, and then return the pointer to local array, which doesn't exist after the end of the function.</p>\n<p>This may work in certain cases, not work in others, and crash in others.</p>\n<p>This line doesn't copy the array, it changes the pointer. You probably meant for this line:</p>\n<pre><code>primesLocation = &primes;\n</code></pre>\n<p>to be this:</p>\n<pre><code>memcpy(primesLocation, primes, (n + 1) * sizeof(bool));\n</code></pre>\n<p>However you don't need the memcopy - just use the one array:</p>\n<pre class=\"lang-c prettyprint-override\"><code> bool* primes = malloc(sizeof(bool) * n + 1);\n \n primes[0] = false;\n primes[1] = false;\n\n for (int i = 2; i < n + 1; i++) {\n primes[i] = true;\n }\n\n for (int prime = 2; prime < sqrt(n) + 1; prime++) {\n if (primes[prime]) {\n for (int j = prime*prime; j < n + 1; j += prime) {\n primes[j] = false;\n }\n }\n }\n\n return primes;\n</code></pre>\n<p>This works. However it has the nasty side effect that the caller needs to remember to free the memory otherwise you'll have a leak.</p>\n<p>So that the caller doesn't need to free memory that it didn't allocate, consider moving the malloc out of the function and changing this to:</p>\n<pre class=\"lang-c prettyprint-override\"><code> bool* sieve(long n, bool* primes);\n\n void main()\n {\n bool* primes = (bool*)malloc(sizeof(bool) * 101);\n auto p = sieve(100, primes);\n free(primes);\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T16:41:37.707",
"Id": "490039",
"Score": "2",
"body": "Welcome to Code Review! Please note, questions involving code that's not working as intended, are off-topic on this site. If OP edits their post to address the problem and make their post on-topic, they make your answer moot. [It is advised not to answer such questions](https://codereview.meta.stackexchange.com/a/6389/120114). Protip: There are tons of on-topic questions to answer; you'll make more reputation faster if you review code in questions that will get higher view counts for being on-topic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T19:57:36.047",
"Id": "490271",
"Score": "0",
"body": "Rather than `(n + 1) * sizeof(bool)`, `sizeof primes` is simpler, cleaner."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T19:59:49.870",
"Id": "490272",
"Score": "0",
"body": "What is `auto p` trying to accomplish here in this C code? Are you thinking of another language? [Where is the C auto keyword used?](https://stackoverflow.com/q/2192547/2410359)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T15:33:33.937",
"Id": "249892",
"ParentId": "249884",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249892",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T14:05:20.383",
"Id": "249884",
"Score": "-1",
"Tags": [
"c",
"pointers"
],
"Title": "Use of pointers in C in Erasthenes sieve program"
}
|
249884
|
<p>I'd like a recommendation on how I can improve the function <code>unquoted_string</code> below - specifically <strong>is there a better way to combine the parsers I have to achieve the desired goal?</strong></p>
<p>Strings in this language are defined by <a href="https://www.rfc-editor.org/rfc/rfc7950#section-6" rel="nofollow noreferrer">YANG RFC 7950 Section 6.1.3</a>. The excerpt relevant to unquoted strings is:</p>
<blockquote>
<p>An unquoted string is any sequence of characters that does not contain any space, tab, carriage return, or line feed characters, a single or double quote character, a semicolon (";"), braces ("{" or "}"), or comment sequences ("//", "/<em>", or "</em>/").</p>
<p>Note that any keyword can legally appear as an unquoted string.</p>
<p>Within an unquoted string, every character is preserved. Note that this means that the backslash character does not have any special meaning in an unquoted string.</p>
</blockquote>
<p>What I've got so far is:</p>
<ul>
<li><code>yang_char</code>: a predicate to match any unicode character that is permitted in the language</li>
<li><code>yang_char_unquoted</code>: a predicate which filters out the exceptions described in the excerpt above</li>
<li><code>unquoted_string</code>: a parser for a valid unquoted string - <strong>this is what I'd like input on</strong></li>
</ul>
<p>In words, unquoted string matches the longest sequence of characters not containing:</p>
<ul>
<li>any of the excluded characters above, or,</li>
<li>any of the digraphs <code>//</code>, <code>/*</code> and <code>*/</code></li>
</ul>
<p>The main concern I have is that each of the <code>take_until</code> calls requires doing a substring search, which seems inefficient. What I really want to do is walk the (hopefully not very long) string returned by the first <code>take_while1</code> call until I find a matching digraph.</p>
<p><strong>Code</strong></p>
<pre><code>extern crate nom;
use nom::{
branch::*,
bytes::complete::*,
character::complete::*,
combinator::*,
error::{ErrorKind, ParseError},
multi::*,
sequence::*,
IResult,
};
fn yang_char(c: char) -> bool {
match c as u32 {
0x00000009 => true,
0x0000000a => true,
0x0000000d => true,
0x00000020..=0x0000d7ff => true,
0x0000e000..=0x0000fdcf => true,
0x0000fdf0..=0x0000fffd => true,
0x00010000..=0x0001fffd => true,
0x00020000..=0x0002fffd => true,
0x00030000..=0x0003fffd => true,
0x00040000..=0x0004fffd => true,
0x00050000..=0x0005fffd => true,
0x00060000..=0x0006fffd => true,
0x00070000..=0x0007fffd => true,
0x00080000..=0x0008fffd => true,
0x00090000..=0x0009fffd => true,
0x000a0000..=0x000afffd => true,
0x000b0000..=0x000bfffd => true,
0x000c0000..=0x000cfffd => true,
0x000d0000..=0x000dfffd => true,
0x000e0000..=0x000efffd => true,
0x000f0000..=0x000ffffd => true,
0x00100000..=0x0010fffd => true,
_ => false,
}
}
/// Variant of yang_char accepting only characters allowed in unquoted
/// strings (see `unquoted_string` for details).
///
/// N.B. This function handles only single characters, so doesn't
/// deal with the comment sequences mentioned in `unquoted_string`
fn yang_char_unquoted(c: char) -> bool {
match c {
' ' => false,
'\t' => false,
'\n' => false,
'\r' => false,
';' => false,
'{' => false,
'}' => false,
_ => yang_char(c),
}
}
/// Per the above, this may contain any valid YANG character, except:
/// - Whitespace (space, tab, line feed, carriage return)
/// - Single or double quotes
/// - Semicolon
/// - Open or close braces ('{' or '}')
/// - Comment sequences ('/*', '//', or '*/')
///
/// In an unquoted string, every character is preserved, which means
/// that backslash has no special meaning.
fn unquoted_string(i: &str) -> IResult<&str, &str> {
let (_, i_tmp) = take_while1(yang_char_unquoted)(i)?;
let len = match alt((take_until("//"), take_until("/*"), take_until("*/")))(i_tmp) {
Ok((_, val)) => val.len(),
Err(nom::Err::Error((val, ErrorKind::TakeUntil))) => val.len(),
err @ Err(_) => return err,
};
Ok((&i[len..], &i[..len]))
}
</code></pre>
<p><strong>Tests</strong></p>
<pre><code>fn test_unquoted_string() {
assert_eq!(unquoted_string("abcd"), Ok(("", "abcd")));
assert_eq!(unquoted_string("1.234"), Ok(("", "1.234")));
assert_eq!(
unquoted_string("a-test-string__.1234"),
Ok(("", "a-test-string__.1234"))
);
assert_eq!(
unquoted_string("a-test//-string__.1234"),
Ok(("//-string__.1234", "a-test"))
);
assert_eq!(
unquoted_string(" "),
Err(nom::Err::Error((" ", ErrorKind::TakeWhile1)))
);
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T14:43:17.967",
"Id": "249888",
"Score": "2",
"Tags": [
"parsing",
"rust"
],
"Title": "How can I simplify my nom parser?"
}
|
249888
|
<p>I'm a 16-year-old so I never studied programming, although I do try to adopt the best practices I can when given the chance.</p>
<p>I would like to clean up the code posted below by making it comply with SOLID principle, and any other general improvements that are offered.</p>
<p>The class in question is the core entry point of my whole application. Each instance of this application acts as a "worker" for a scraper network.</p>
<pre><code>public class ScraperWorker
{
private readonly ScraperQueue _scraperQueue;
private readonly Dictionary<string, ISocialEventHandler> _eventHandlers;
private readonly ScraperWorkerDao _scraperWorkerDao;
private readonly ScraperQueueDao _scraperQueueDao;
private readonly Client _bugSnagClient;
private readonly ILogger _logger;
private bool _isProcessing;
public ScraperWorker(
ScraperQueue scraperQueue,
Dictionary<string, ISocialEventHandler> eventHandlers,
ScraperWorkerDao scraperWorkerDao,
ScraperQueueDao scraperQueueDao,
Client bugSnagClient,
ILogger logger)
{
_scraperQueue = scraperQueue;
_eventHandlers = eventHandlers;
_scraperWorkerDao = scraperWorkerDao;
_scraperQueueDao = scraperQueueDao;
_bugSnagClient = bugSnagClient;
_logger = logger;
Process();
}
public void Start()
{
_isProcessing = true;
}
public void Stop()
{
_isProcessing = false;
}
private void Process()
{
var ticksSinceStatusUpdate = 0;
new Thread(() =>
{
while (true)
{
ticksSinceStatusUpdate++;
if (ticksSinceStatusUpdate >= 10)
{
RenewWorkerStatus(); // Checks if we have paused the worker via an external service.
ticksSinceStatusUpdate = 0;
}
if (!_isProcessing)
{
_logger.Warning($"The worker is currently paused, sleeping for 30 seconds.");
Thread.Sleep(TimeSpan.FromSeconds(30));
continue;
}
if (!_scraperQueue.TryGetItem(out var item))
{
_logger.Warning($"The queue is currently empty, sleeping for 30 seconds.");
Thread.Sleep(TimeSpan.FromSeconds(30));
continue;
}
_scraperWorkerDao.UpdateWorkerLastSeen(StaticState.WorkerId);
var eventHandler = ResolveEventHandlerFromItem(item.Item);
eventHandler.SetCurrentItem(item.Item);
if (eventHandler.IsLoginNeeded())
{
eventHandler.Login();
}
var result = ProcessQueueItem(item, eventHandler);
if (result.IsSuccess)
{
_logger.Success($"Finished processing {item.Item}");
}
else
{
_logger.Trace($"Finished processing {item.Item}");
}
Console.WriteLine();
_scraperQueueDao.MarkItemAsComplete(item.Id);
_scraperQueueDao.StoreItemResultInDatabase(result);
}
}).Start();
}
private void RenewWorkerStatus()
{
_isProcessing = _scraperWorkerDao.IsWorkerRunning(StaticState.WorkerId);
}
private ScraperQueueItemResult ProcessQueueItem(ScraperQueueItem item, ISocialEventHandler eventHandler)
{
_logger.Trace($"Processing {item.Item}");
try
{
eventHandler.NavigateToProfile();
if (eventHandler.IsProfileVisitsThrottled())
{
eventHandler.SwitchAccount(true);
return ProcessQueueItem(item, eventHandler);
}
if (!eventHandler.TryWaitForProfileToLoad())
{
return new ScraperQueueItemResult(
item.Id, "Method 'TryWaitForProfileToLoad' returned false.", eventHandler.GetPageSource(), false
);
}
var profile = eventHandler.CreateProfile();
if (!profile.ShouldScrape(out var validationResult))
{
return new ScraperQueueItemResult(
item.Id, validationResult.ToString(), eventHandler.GetPageSource(), false
);
}
var connectionsToStore = new List<ProfileConnection>();
if (profile.ShouldCollectConnections())
{
profile.Connections = eventHandler.GetConnections();
connectionsToStore = eventHandler.GetFilteredConnections(profile.Connections);
if (connectionsToStore.Any())
{
_logger.Trace(
$"Collected {profile.Connections.Count} / {profile.FollowerCount}, storing {connectionsToStore.Count} of them in the database.");
}
}
if (profile.ShouldSave(out validationResult))
{
if (!profile.IsPrivate)
{
profile.Posts = eventHandler.GetPosts(profile.Username);
}
profile.Save();
if (connectionsToStore.Any())
{
_scraperQueue.AddItems(eventHandler.ConvertConnectionsToQueueItems(connectionsToStore), profile.Id);
}
return new ScraperQueueItemResult(
item.Id, "success", "", true
);
}
if (connectionsToStore.Any())
{
_scraperQueue.AddItems(eventHandler.ConvertConnectionsToQueueItems(connectionsToStore), profile.Id);
}
return new ScraperQueueItemResult(
item.Id, validationResult.ToString(), eventHandler.GetPageSource(), false
);
}
catch (Exception e)
{
_bugSnagClient.Notify(e, report =>
{
report.Event.Metadata.Add("queue_item", item.Item);
report.Event.Metadata.Add("current_url", eventHandler.GetUrl());
report.Event.Metadata.Add("page_source", eventHandler.GetPageSource());
report.Event.Metadata.Add("created_at", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
});
// TODO: Try and requeue the item?
_logger.Error(e.Message);
return new ScraperQueueItemResult(
item.Id, e.Message, eventHandler.GetPageSource(), false
);
}
}
private ISocialEventHandler ResolveEventHandlerFromItem(string item)
{
var host = new Uri(item).Host.Replace("www.", "");
if (_eventHandlers.ContainsKey(host))
{
return _eventHandlers[host];
}
throw new Exception($"Failed to resolve event handler for host '{host}'");
}
}
</code></pre>
<p>ISocialEventHandler (each site inherits this and has its own implementation on how a site should be scraped)</p>
<pre><code>public interface ISocialEventHandler
{
string GetLoginPageUrl();
string GetLogoutPageUrl();
bool IsLoginNeeded();
void Login();
void Logout();
ISocialProfile CreateProfile();
List<ProfileConnection> GetConnections();
void NavigateToProfile();
bool TryWaitForProfileToLoad();
string GetUrl();
string GetUsername();
string GetName();
string GetProfilePicture();
bool GetIsPrivate();
int GetFollowerCount();
int GetFollowingCount();
List<ProfilePost> GetPosts(string owner);
List<ProfilePostMedia> GetPostMedia(string owner);
void SetCurrentItem(string currentItem);
List<ProfileConnection> GetFilteredConnections(List<ProfileConnection> connections);
string GetPageSource();
List<ScraperQueueItem> ConvertConnectionsToQueueItems(List<ProfileConnection> connections);
bool IsProfileVisitsThrottled();
void SwitchAccount(bool markCurrentAsThrottled);
}
</code></pre>
<p>ScraperQueueItem (just an entity)</p>
<pre><code>public long Id { get; }
public string Item { get; }
public int TypeId { get; } // determines provider
public bool IsPrivate { get; }
public bool Confirmed { get; }
public ScraperQueueItem(long id, string item, int typeId, bool isPrivate, bool confirmed)
{
Id = id;
Item = item;
TypeId = typeId;
IsPrivate = isPrivate;
Confirmed = confirmed;
}
</code></pre>
<p>ScraperQueueItemResult (used to map from and to the database, another entity)</p>
<pre><code>public long ItemId { get; set; }
public string Content { get; set; }
public string PageSource { get; set; }
public bool IsSuccess { get; set; }
public ScraperQueueItemResult(long itemId, string content, string pageSource, bool isSuccess)
{
ItemId = itemId;
Content = content;
PageSource = pageSource.Truncate(1000);
IsSuccess = isSuccess;
}
</code></pre>
<p>ProfileConnection (used to map, another entity)</p>
<pre><code>public class ProfileConnection
{
public string Item { get; set; }
public bool IsPrivate { get; set; }
}
</code></pre>
<p>ProfilePost (another DB mapper to and from, entity):</p>
<pre><code>public class ProfilePost
{
public List<ProfilePostMedia> Media { get; }
public ProfilePost(List<ProfilePostMedia> media)
{
Media = media;
}
}
</code></pre>
<p>ProfileMostMedia (another DB mapper to and from, entity):</p>
<pre><code>public class ProfilePostMedia
{
public string CdnUrl { get; set; }
public string MetaData { get; set; }
public ProfilePostMedia(string cdnUrl, string metaData)
{
CdnUrl = cdnUrl;
MetaData = metaData;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T17:31:31.037",
"Id": "490043",
"Score": "0",
"body": "Tip: If you're not in .NET 3.5, use `Task` and `async/await` instead of manual `Thread` management. [Asynchronous Programming](https://docs.microsoft.com/en-us/dotnet/csharp/async)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T22:35:42.760",
"Id": "490063",
"Score": "0",
"body": "I am on dotnet core 3.1, thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T05:53:33.680",
"Id": "490080",
"Score": "3",
"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 [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask) for examples, and revise the title accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T09:01:21.987",
"Id": "490088",
"Score": "2",
"body": "(There even is a problem with the spelling of the original title: should it read *this C# method's length* or *these C# methods' length* or something else, entirely?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T20:32:41.240",
"Id": "490183",
"Score": "0",
"body": "Thank you everyone, I will revise my question and improve it based on your comments. I have already updated the title and am working on adding code for the missing classes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T11:48:30.063",
"Id": "490233",
"Score": "0",
"body": "I have revised my question, adding a lot more details and a title with a clear intention."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T14:35:19.433",
"Id": "490255",
"Score": "0",
"body": "`ProfileMostMedia` *Most*? There is no code following `ProfilePost (another [mapper]):`. `a title with a clear intention` - not following *State what your code does in your title, not your main concerns about it.*"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T14:44:54.903",
"Id": "490256",
"Score": "0",
"body": "Sorry I was trying to update it late last night on Mobile, I have fixed the typos."
}
] |
[
{
"body": "<p>Thank you for updating your question!</p>\n<p>In your question you mention the SOLID principle, it isn't just one principle, <a href=\"https://en.wikipedia.org/wiki/Open%E2%80%93closed_principle\" rel=\"nofollow noreferrer\">SOLID is 5 object orieneted design principles</a>. SOLID is a mnemonic acronym for five design principles intended to make software designs more understandable, flexible and maintainable. This will help you design your objects and classes better.</p>\n<ol>\n<li>The <a href=\"https://en.wikipedia.org/wiki/Liskov_substitution_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> - A class should only have a single responsibility, that is, only changes to one part of the software's specification should be able to affect the specification of the class.</li>\n<li>The <a href=\"https://en.wikipedia.org/wiki/Interface_segregation_principle\" rel=\"nofollow noreferrer\">Open–closed Principle</a> - states software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.</li>\n<li>The <a href=\"https://en.wikipedia.org/wiki/Dependency_inversion_principle\" rel=\"nofollow noreferrer\">Liskov Substitution Principle</a> - Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.</li>\n<li>The <a href=\"https://en.wikipedia.org/wiki/KISS_principle\" rel=\"nofollow noreferrer\">Interface segregation principle</a> - states that no client should be forced to depend on methods it does not use.</li>\n<li>The <a href=\"https://en.wikipedia.org/wiki/Top-down_and_bottom-up_design\" rel=\"nofollow noreferrer\">Dependency Inversion Principle</a> - is a specific form of decoupling software modules. When following this principle, the conventional dependency relationships established from high-level, policy-setting modules to low-level, dependency modules are reversed, thus rendering high-level modules independent of the low-level module implementation details.</li>\n</ol>\n<p>I'm going to focus on the Single Responsibility Principle (SRP) here because that seems to be the major issue. The single responsibility principle doesn't apply just to classes, it applies to functions, methods and interfaces as well. There are other similar concepts or principles such as the Keep It Simple (KISS - the military has a 4th word in here) principle.</p>\n<p>If at some point in the future you study computer science at a university you may also learn <a href=\"https://en.wikipedia.org/wiki/Top-down_and_bottom-up_design\" rel=\"nofollow noreferrer\">Top Down Design</a> as well. The concept of top down design is that one keeps breaking the problem into smaller and smaller pieces until each piece is a very simple solution. This is a major source of methods and functions, and it can be applied to objects and classes as well. Some of your classes such as <code>ProfilePost</code>, <code>ProfilePostMedia</code>, <code>ProfileConnection</code> and <code>ScraperQueueItemResult</code> already show some application of the SRP, however, <code>ScraperWorker</code> and the interface <code>ISocialEventHandler</code> look like major collections of many separate objects and actions and the names seem to imply the same thing.</p>\n<p>Software engineers also use a visual modeling language called <a href=\"https://en.wikipedia.org/wiki/Unified_Modeling_Language\" rel=\"nofollow noreferrer\">UML (Unified Modeling Language)</a> to diagram objects, object interactions, system interactions and timing sequences. This helps them decide when an object/class is getting too complicated.</p>\n<h2>Simplify the Function ProcessQueueItem</h2>\n<p>I believe your original question was asking how to simplify the following function:</p>\n<pre><code> private ScraperQueueItemResult ProcessQueueItem(ScraperQueueItem item, ISocialEventHandler eventHandler)\n {\n _logger.Trace($"Processing {item.Item}");\n\n try\n {\n eventHandler.NavigateToProfile();\n\n if (eventHandler.IsProfileVisitsThrottled())\n {\n eventHandler.SwitchAccount(true);\n return ProcessQueueItem(item, eventHandler);\n }\n\n if (!eventHandler.TryWaitForProfileToLoad())\n {\n return new ScraperQueueItemResult(\n item.Id, "Method 'TryWaitForProfileToLoad' returned false.", eventHandler.GetPageSource(), false\n );\n }\n\n var profile = eventHandler.CreateProfile();\n\n if (!profile.ShouldScrape(out var validationResult))\n {\n return new ScraperQueueItemResult(\n item.Id, validationResult.ToString(), eventHandler.GetPageSource(), false\n );\n }\n\n var connectionsToStore = new List<ProfileConnection>();\n\n if (profile.ShouldCollectConnections())\n {\n profile.Connections = eventHandler.GetConnections();\n\n connectionsToStore = eventHandler.GetFilteredConnections(profile.Connections);\n\n if (connectionsToStore.Any())\n {\n _logger.Trace(\n $"Collected {profile.Connections.Count} / {profile.FollowerCount}, storing {connectionsToStore.Count} of them in the database.");\n }\n }\n\n if (profile.ShouldSave(out validationResult))\n {\n if (!profile.IsPrivate)\n {\n profile.Posts = eventHandler.GetPosts(profile.Username);\n }\n\n profile.Save();\n\n if (connectionsToStore.Any())\n {\n _scraperQueue.AddItems(eventHandler.ConvertConnectionsToQueueItems(connectionsToStore), profile.Id);\n }\n\n return new ScraperQueueItemResult(item.Id, "success", "", true);\n }\n\n if (connectionsToStore.Any())\n {\n _scraperQueue.AddItems(eventHandler.ConvertConnectionsToQueueItems(connectionsToStore), profile.Id);\n }\n\n return new ScraperQueueItemResult(\n item.Id, validationResult.ToString(), eventHandler.GetPageSource(), false\n );\n }\n catch (Exception e)\n {\n _bugSnagClient.Notify(e, report =>\n {\n report.Event.Metadata.Add("queue_item", item.Item);\n report.Event.Metadata.Add("current_url", eventHandler.GetUrl());\n report.Event.Metadata.Add("page_source", eventHandler.GetPageSource());\n report.Event.Metadata.Add("created_at", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));\n });\n\n // TODO: Try and requeue the item?\n\n _logger.Error(e.Message);\n\n return new ScraperQueueItemResult(\n item.Id, e.Message, eventHandler.GetPageSource(), false\n );\n }\n }\n</code></pre>\n<p>Having <code>try{}</code>/<code>catch{}</code> blocks inherently makes a function larger and more complex and it always a good idea to move parts of that function into private sub-functions, however, one of the first things I notice is repetition of the following code:</p>\n<pre><code> if (connectionsToStore.Any())\n {\n _scraperQueue.AddItems(eventHandler.ConvertConnectionsToQueueItems(connectionsToStore), profile.Id);\n }\n</code></pre>\n<p>Perhaps that code can be moved up in the function so that it is only used once.</p>\n<p>The second thing that stands out is the code in the <code>catch{}</code> block:</p>\n<pre><code> _bugSnagClient.Notify(e, report =>\n {\n report.Event.Metadata.Add("queue_item", item.Item);\n report.Event.Metadata.Add("current_url", eventHandler.GetUrl());\n report.Event.Metadata.Add("page_source", eventHandler.GetPageSource());\n report.Event.Metadata.Add("created_at", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));\n });\n</code></pre>\n<p>I would move that code into a small private function that accepts <code>item</code> and <code>eventHandler</code> as arguments and performs that code in the function, perhaps the function can be called <code>bugReport()</code>.</p>\n<p>This code can be combined into a function, if that function returns a NULL value then continue processing, if the function returns a value then return that value to the calling function:</p>\n<pre><code> if (eventHandler.IsProfileVisitsThrottled())\n {\n eventHandler.SwitchAccount(true);\n return ProcessQueueItem(item, eventHandler);\n }\n\n if (!eventHandler.TryWaitForProfileToLoad())\n {\n return new ScraperQueueItemResult(\n item.Id, "Method 'TryWaitForProfileToLoad' returned false.", eventHandler.GetPageSource(), false\n );\n }\n</code></pre>\n<p>This code should be in a function that returns the list:</p>\n<pre><code> var connectionsToStore = new List<ProfileConnection>();\n\n if (profile.ShouldCollectConnections())\n {\n profile.Connections = eventHandler.GetConnections();\n\n connectionsToStore = eventHandler.GetFilteredConnections(profile.Connections);\n\n if (connectionsToStore.Any())\n {\n _logger.Trace(\n $"Collected {profile.Connections.Count} / {profile.FollowerCount}, storing {connectionsToStore.Count} of them in the database.");\n }\n }\n</code></pre>\n<p>Perhaps that is where you can call the repeated code mentioned above.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T19:38:02.157",
"Id": "490270",
"Score": "0",
"body": "Thank you so much, this is a really good starting point for me to improve. When you say ScraperWorker and ISocialEventHandler have similar methods, can you elaborate? Also do you think studying SOLID on YouTube or something similar will help me in applying your suggestions in practice?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T20:19:33.747",
"Id": "490274",
"Score": "0",
"body": "@user231071 I'm old school (or just old) I prefer written material like I pointed you to. Either You-Tube or some books and articles by the authors quoted on wikipedia. I didn't mean the methods were similar as much as there was too much in the class. `ScraperWorker` isn't that bad but `ISocialEventHandler` just has way too much responsibility, things to do. Think about what Single Responsibility means to a class and try to apply that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T20:22:22.310",
"Id": "490275",
"Score": "0",
"body": "I hope you get a few more reviews, because I may not have covered everything."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T20:29:31.797",
"Id": "490276",
"Score": "0",
"body": "You might also want to read stuff from `Grady Booch`, `James Rumbaugh` and `Ivar Jacobson` who invented UML and Martin Fowler who is responsible for the SRP."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T22:00:52.937",
"Id": "490285",
"Score": "0",
"body": "Thank you, I will take all of this on board. Is it worth mentioning that the entities could be structs instead of classes?"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T18:51:35.793",
"Id": "249966",
"ParentId": "249890",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T15:10:45.900",
"Id": "249890",
"Score": "8",
"Tags": [
"c#",
"object-oriented",
"web-scraping"
],
"Title": "C# Profile Scraper"
}
|
249890
|
<p><strong>Quick disclaimer</strong>. I've programmed Java for years but this is the first Objective C I've ever written.</p>
<p>I've written some code which almost unfortunately works but frankly hurts my eyes with the number of lines of code and quality. Basically looking for the right way to convert the original string:</p>
<pre><code><TUHandle 0x280479f50 type=PhoneNumber, value=07700000000, normalizedValue=(null), isoCountryCode=(null)>
</code></pre>
<p>Into JSON (ignoring the TUHandle 0x280479f50) part which I don't need:</p>
<pre><code>{"value": "07700000000",
"normalizedValue": "(null)",
"type": "PhoneNumber",
"isoCountryCode": "(null)"}
</code></pre>
<p>Line breaks and indents are NOT important, only that this is valid JSON</p>
<pre><code> //Format of string
//<TUHandle 0x280479f50 type=PhoneNumber, value=07700000000, normalizedValue=(null), isoCountryCode=(null)>
NSString *original = [NSString stringWithFormat:@"%@", hand];
//Trim off unused stuff
NSRange startKeyValues = [original rangeOfString:@"type="];
NSRange endKeyValues = [original rangeOfString:@">"];
NSRange rangeOfString = NSMakeRange(startKeyValues.location, endKeyValues.location - startKeyValues.location);
NSString *keysValues = [original substringWithRange:rangeOfString];
//Create a dictionary to hold the key values
NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
//Split the keysValuesstring
NSArray *items = [keysValues componentsSeparatedByString:@","];
for (NSString* o in items)
{
//Create key value pairs
NSArray *item = [o componentsSeparatedByString:@"="];
NSString *key=[item objectAtIndex:0];
NSString *value=[item objectAtIndex:1];
[dict setObject:value forKey:key];
}
[dict setObject:currentUUID forKey:@"uid"];
//Convert to Json Object
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];
</code></pre>
<p>Any tips which would make this look a hell of a lot less clunky?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T18:50:06.030",
"Id": "490046",
"Score": "0",
"body": "A quick question: Where does the string come from, or how is it generated? I have the feeling that there might be a better approach by generating the JSON from some original *object* and not from the string description of that object."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T19:15:42.917",
"Id": "490049",
"Score": "0",
"body": "Thanks a @MartinR it's a hook in a Theos Logos thing I'm working on. So using `%hook TUProxyCall\n-(id)handle { TUHandle *hand = %orig; NSString *original = [NSString stringWithFormat:@\"%@\", hand]; ....}` Thanks in advance"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T19:30:29.830",
"Id": "490050",
"Score": "0",
"body": "I suggest that you add more information to your question, so that it becomes clear in which context the above code is used, and what you are ultimately trying to achieve. – I have no experience with Theos Logos, so I might be completely wrong, but at present this looks a bit like an XY-problem to me: You want to create JSON from some object, but what you ask is how to create JSON from a string description of that object."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T21:24:04.743",
"Id": "490056",
"Score": "0",
"body": "Thanks but if I wanted an answer on Theos Logos I would have asked on a different forum. This question is specifically about String manipulation and formatting Key Value pairs as JSON. In terms of what I am trying to achieve, I already achieved it but I would like to do it with cleaner code."
}
] |
[
{
"body": "<p>In your question, you don't make it clear what needs to be dynamic and what can be static. If the only string you ever have to parse is the one you showed, then don't bother parsing it, just make the json string and use:</p>\n<pre><code>NSData *jsonData = [@"{\\"normalizedValue\\":\\"(null)\\",\\"value\\":\\"07700000000\\",\\"isoCountryCode\\":\\"(null)\\",\\"type\\":\\"PhoneNumber\\",\\"uid\\":\\"uuid\\"}" dataUsingEncoding:NSUTF8StringEncoding];\n</code></pre>\n<p>If you know all the keys will be the same and just the data will be different, then I would go with something like:</p>\n<pre><code>NSString *valueFor(NSString *key, NSString *original) {\n unsigned long startOf = [original rangeOfString:key].location + key.length;\n unsigned long endOfComma = [original rangeOfString:@"," options:NSLiteralSearch range:NSMakeRange(startOf, original.length - startOf)].location;\n return [\n [original substringWithRange:NSMakeRange(startOf, (endOfComma == NSNotFound ? original.length : endOfComma) - startOf)]\n stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@">"]\n ];\n}\n\nNSData *example(NSString *original, NSString *currentUUID) {\n NSString *type = valueFor(@"type=", original);\n NSString *value = valueFor(@"value=", original);\n NSString *normalizedValue = valueFor(@"normalizedValue=", original);\n NSString *isoCountryCode = valueFor(@"isoCountryCode=", original);\n NSDictionary *dict = @{\n @"value": value,\n @"normalizedValue": normalizedValue,\n @"type": type,\n @"isoCountryCode": isoCountryCode,\n @"uid": currentUUID\n };\n\n return [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];\n}\n</code></pre>\n<p>The above is much cleaner and easier to read than what you have currently.</p>\n<p>If even the keys have to be dynamic, then the code you have is about as good as you can get.</p>\n<p>I ended up with this:</p>\n<pre><code>NSData* example(NSString* original, NSString *currentUUID) {\n NSArray<NSString*>* elements =\n [[[original stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]]\n componentsSeparatedByString:@" "]\n filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id _Nullable evaluatedObject, NSDictionary<NSString *,id> * _Nullable bindings) {\n return [evaluatedObject containsString:@"="];\n }]];\n\n NSMutableArray* values = [NSMutableArray new];\n for (NSString* each in elements) {\n NSArray<NSString*>* keyValue = [[each stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@","]]\n componentsSeparatedByString:@"="];\n NSString* value = [NSString stringWithFormat:@"\\"%@\\": \\"%@\\"", keyValue[0], keyValue[1]];\n [values addObject:value];\n };\n [values addObject: [NSString stringWithFormat:@"\\"uid\\": \\"%@\\"", currentUUID]];\n\n NSData* jsonData = [[NSString stringWithFormat:@"{%@}", [values componentsJoinedByString:@", "]] dataUsingEncoding:NSUTF8StringEncoding];\n return jsonData;\n}\n</code></pre>\n<p>Which is maybe a little more generic than the code you have, but I don't think it's any more readable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-14T17:40:23.543",
"Id": "266058",
"ParentId": "249895",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T16:45:32.377",
"Id": "249895",
"Score": "4",
"Tags": [
"json",
"objective-c"
],
"Title": "Objective C String to JSON formatting"
}
|
249895
|
<h2>Summary</h2>
<p>I come from a Java background but I am trying to make a game in C++. This is my attempt at a state management system, which should allow me to easily switch between "states" (menu, game, scoreboard, etc.).</p>
<p>The idea is that:</p>
<ul>
<li>When the program starts, I create an <code>Application</code>.</li>
<li>The Application contains the game loop, which runs until the program exits.</li>
<li>Each frame, the application updates and renders the current state.</li>
<li><code>State</code> is an abstract class, and <code>Rival</code> is a concrete subclass.</li>
</ul>
<h2>Feedback</h2>
<p>I would really love any feedback. Specifically, the areas I am most concerned about are:</p>
<ul>
<li><strong>Inheritance:</strong> I have not really used this before in C++. My understanding is that by using a <code>unique_ptr</code> my state gets stored on the heap, and this avoids the problem of object slicing. My <code>State</code> methods are all pure virtual, and overridden by the subclass. Am I missing anything?</li>
<li><strong>Ownership:</strong> The Application <em>owns</em> the current State; Rival <em>owns</em> the current Scenario. My understanding is that when the Application exits (or changes to a new state), the current state will be destroyed / freed. When Rival gets freed, the current Scenario will subsequently be freed. Have I got that right?</li>
<li><strong>Heap vs Stack:</strong> I understand that the stack is faster to access, but it is quite small and not particularly suitable for long-lived objects (they are freed when they go out of scope), polymorphic objects or variable-size objects. For this reason the State and Scenario live on the heap, but everything else lives on the stack. Does this sound ok?</li>
</ul>
<blockquote>
<p>NOTE: I am not too worried about the technical aspects of the game loop itself at this point (fixed or variable time step, sleep duration, etc.) - I just want to make sure the code is clean, free from bugs / memory leaks, and follows best practices where possible. I would be grateful if you could try to include an explanation along with any suggestions, so that I can learn WHY and not just WHAT.</p>
</blockquote>
<h2>Code</h2>
<p><em>I have tried to omit any details which are not relevant to this particular mechanism, but the full code can be found <a href="https://github.com/Danjb1/open-rival/tree/master/Open-Rival" rel="noreferrer">here</a>.</em></p>
<h3>Main.cpp</h3>
<pre><code>#include "pch.h"
#include <iostream>
#include <stdexcept>
#include "Application.h"
#include "Rival.h"
#include "Scenario.h"
#include "ScenarioBuilder.h"
#include "ScenarioReader.h"
#include "Window.h"
/**
* Entry point for the application.
*/
int main() {
try {
// Create our Window
Rival::Window window(800, 600, "Rival Realms");
window.use();
// Create our Application
Rival::Application app(window);
// Load some scenario
Rival::ScenarioReader reader(Rival::Resources::mapsDir + "example.sco");
Rival::ScenarioBuilder scenarioBuilder(reader.readScenario());
std::unique_ptr<Rival::Scenario> scenario = scenarioBuilder.build();
// Create our initial state
std::unique_ptr<Rival::State> initialState =
std::make_unique<Rival::Rival>(app, std::move(scenario));
// Run the game!
app.start(std::move(initialState));
} catch (const std::runtime_error& e) {
std::cerr << "Unhandled error during initialization or gameplay\n";
std::cerr << e.what() << "\n";
return 1;
}
return 0;
}
</code></pre>
<h3>Application.h</h3>
<pre><code>#ifndef APPLICATION_H
#define APPLICATION_H
#include <memory>
#include "Resources.h"
#include "State.h"
#include "Window.h"
namespace Rival {
class Application {
public:
bool vsyncEnabled;
Application(Window& window);
/**
* Runs the Application until the user exits.
*/
void start(std::unique_ptr<State> state);
/**
* Exits the Application cleanly.
*/
void exit();
Window& getWindow();
Resources& getResources();
private:
Window& window;
Resources res;
std::unique_ptr<State> state;
};
} // namespace Rival
#endif // APPLICATION_H
</code></pre>
<h3>Application.cpp</h3>
<pre><code>#include "pch.h"
#include "Application.h"
#include <SDL.h>
namespace Rival {
bool vsyncEnabled = true;
Application::Application(Window& window)
: window(window) {
// Try to enable vsync
if (SDL_GL_SetSwapInterval(1) < 0) {
printf("Unable to enable vsync! SDL Error: %s\n", SDL_GetError());
vsyncEnabled = false;
}
}
void Application::start(std::unique_ptr<State> initialState) {
// Event handler
SDL_Event e;
state = std::move(initialState);
bool exiting = false;
Uint32 nextUpdateDue = SDL_GetTicks();
// Game loop
while (!exiting) {
Uint32 frameStartTime = SDL_GetTicks();
// Is the next update due?
if (vsyncEnabled || nextUpdateDue <= frameStartTime) {
// Handle events on the queue
while (SDL_PollEvent(&e) != 0) {
if (e.type == SDL_QUIT) {
exiting = true;
} else if (e.type == SDL_KEYDOWN) {
state->keyDown(e.key.keysym.sym);
} else if (e.type == SDL_MOUSEWHEEL) {
state->mouseWheelMoved(e.wheel);
}
}
// Update the game logic, as many times as necessary to keep it
// in-sync with the refresh rate.
//
// For example:
// - For a 30Hz monitor, this will run twice per render.
// - For a 60Hz monitor, this will run once per render.
// - For a 120Hz monitor, this will run every other render.
//
// If vsync is disabled, this should run once per render.
while (nextUpdateDue <= frameStartTime) {
state->update();
nextUpdateDue += TimerUtils::timeStepMs;
}
// Render the game, once per iteration.
// With vsync enabled, this matches the screen's refresh rate.
// Otherwise, this matches our target FPS.
state->render();
// Update the window with our newly-rendered game.
// If vsync is enabled, this will block execution until the
// next swap interval.
window.swapBuffers();
} else {
// Next update is not yet due.
// Sleep for the shortest possible time, so as not to risk
// overshooting!
SDL_Delay(1);
}
}
// Free resources and exit SDL
exit();
}
void Application::exit() {
SDL_Quit();
}
Window& Application::getWindow() {
return window;
}
Resources& Application::getResources() {
return res;
}
} // namespace Rival
</code></pre>
<h3>State.h</h3>
<pre><code>#ifndef STATE_H
#define STATE_H
#include <SDL.h>
namespace Rival {
// Forward declaration to avoid circular reference
class Application;
class State {
public:
/**
* Handles keyDown events.
*/
virtual void keyDown(const SDL_Keycode keyCode) = 0;
/**
* Handles mouse wheel events.
*/
virtual void mouseWheelMoved(const SDL_MouseWheelEvent evt) = 0;
/**
* Updates the logic.
*
* It is assumed that a fixed amount of time has elapsed between calls
* to this method, equal to TimerUtils::timeStepMs.
*/
virtual void update() = 0;
/**
* Renders the current frame.
*/
virtual void render() = 0;
};
} // namespace Rival
#endif // STATE_H
</code></pre>
<h3>Rival.h</h3>
<pre><code>#ifndef RIVAL_H
#define RIVAL_H
#include <SDL.h>
#include <memory>
#include "Application.h"
#include "Scenario.h"
#include "State.h"
#include "Window.h"
namespace Rival {
class Rival : public State {
public:
Rival(Application& app, std::unique_ptr<Scenario> scenario);
// Inherited from State
void keyDown(const SDL_Keycode keyCode) override;
void mouseWheelMoved(const SDL_MouseWheelEvent evt) override;
void render() override;
void update() override;
private:
Application& app;
Window& window;
Resources& res;
std::unique_ptr<Scenario> scenario;
};
} // namespace Rival
#endif // RIVAL_H
</code></pre>
<h3>Rival.cpp</h3>
<pre><code>#include "pch.h"
#include "Rival.h"
namespace Rival {
Rival::Rival(Application& app, std::unique_ptr<Scenario> scenarioToMove)
: app(app),
window(app.getWindow()),
res(app.getResources()),
scenario(std::move(scenarioToMove)) {}
void Rival::update() {
// ...
}
void Rival::render() {
// ...
}
void Rival::keyDown(const SDL_Keycode keyCode) {
// ...
}
void Rival::mouseWheelMoved(const SDL_MouseWheelEvent evt) {
// ...
}
} // namespace Rival
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T09:54:25.273",
"Id": "490089",
"Score": "0",
"body": "A minor point I noticed after writing this, `vsyncEnabled` is not being set on the Application instance."
}
] |
[
{
"body": "<h1>Answers to your questions</h1>\n<blockquote>\n<p>Inheritance: I have not really used this before in C++. My understanding is that by using a <code>unique_ptr</code> my state gets stored on the heap, and this avoids the problem of object slicing. My State methods are all pure virtual, and overridden by the subclass. Am I missing anything?</p>\n</blockquote>\n<p>Object slicing happens when you copy a derived class variable into a base class variable. Using any kind of pointer prevents a copy from being made. However, you probably want to use a pointer (or reference) anyway, even if there was no object slicing.</p>\n<blockquote>\n<p>Ownership: The Application owns the current State; Rival owns the current Scenario. My understanding is that when the Application exits (or changes to a new state), the current state will be destroyed / freed. When Rival gets freed, the current Scenario will subsequently be freed. Have I got that right?</p>\n</blockquote>\n<p>Yes, as soon as a class is destroyed, all its member variables are destroyed as well. If a member variable is a <code>std::unique_ptr</code>, this will ensure <code>delete</code> is called on the pointer.</p>\n<blockquote>\n<p>Heap vs Stack: I understand that the stack is faster to access, but it is quite small and not particularly suitable for long-lived objects (they are freed when they go out of scope), polymorphic objects or variable-size objects. For this reason the State and Scenario live on the heap, but everything else lives on the stack. Does this sound ok?</p>\n</blockquote>\n<p>The main thread of an application typically has megabytes of stack space on a desktop computer, so I wouldn't worry about it that much.\nFor regular variables, even if their type is that of a large class, it will mostly be fine, but if you start allocating arrays on the stack you have to be careful.\nThe lifetime depends on the lifetime of the scope, but that can be very long; for example the variables allocated on the stack frame of <code>main()</code> will basically live for as long as the program lives.</p>\n<p>As for faster access: the only issue with variables on the heap is that they are access via a pointer, so at some point the pointer has to be dereferenced. This may or may not be an issue for performance. I wouldn't worry about it in the early stages of your program, it is something you can worry about later if you are doing performance tuning, and only then if a profiler tells you that this is actually a problem.</p>\n<p>It should be fine to declare a <code>State</code> and <code>Scenario</code> variable on the stack of <code>main()</code>:</p>\n<pre><code>// Load some scenario\nRival::ScenarioReader reader(Rival::Resources::mapsDir + "example.sco");\nRival::ScenarioBuilder scenarioBuilder(reader.readScenario());\nRival::Scenario scenario = scenarioBuilder.build();\n\n// Create our initial state\nRival::Rival initialState(scenario);\n\n// Run the game!\napp.start(initialState);\n</code></pre>\n<p>This requires the constructor of <code>Rival::Rival</code> and <code>Application::start()</code> to take a plain reference as an argument. This means those objects also no longer own the <code>scenario</code> and <code>state</code>. But it should be fine, those variables will now be destroyed when <code>main()</code> exits.</p>\n<h1>Don't catch exceptions if you can't do anything about them</h1>\n<p>In <code>main()</code>, you catch any <code>std::runtime_error()</code>, but the only thing you do is to print an error and exit with a non-zero exit code. This is exactly what will already happen if you don't catch exceptions there, so it is a pointless excercise. Perhaps Java taught you that you have to catch 'm all, but that's not the case in C++. Just let fatal exceptions you can't deal with fall through.</p>\n<p>Aside from that, if you do want to have a generic exception catcher, then you should catch <a href=\"https://en.cppreference.com/w/cpp/error/exception\" rel=\"noreferrer\"><code>std::exception</code></a> instead, it's the base class of <code>std::runtime_error</code> and will also catch other types of exceptions.</p>\n<h1>Not everything needs to be a <code>class</code></h1>\n<p>Again, I think this comes from your background in Java, where all functions must live inside a <code>class</code>. This is not the case in C++. In particular, <code>class Application</code> is just something that you construct once, call <code>start()</code> on, and then it exits and you're done. For such a one-shot operation, you can just use a single function. Since <code>Application</code> primarily implements the main loop of your application, I would just create a single function called <code>main_loop()</code>:</p>\n<pre><code>void main_loop(Window& window, State& initialState) {\n bool vsyncEnabled = SDL_GL_SetSwapInterval(1) == 0;\n\n if (!vsyncEnabled) {\n printf("Unable to enable vsync! SDL Error: %s\\n", SDL_GetError());\n }\n\n SDL_Event e;\n bool exiting = false;\n Uint32 nextUpdateDue = SDL_GetTicks();\n\n // Game loop\n while (!exiting) {\n ...\n }\n}\n</code></pre>\n<p>And then in <code>main()</code>:</p>\n<pre><code>Rival::Window window(800, 600, "Rival Realms");\n...\nRival::State initialState(scenario);\n\n// Run the game!\nmain_loop(window, initialState);\n</code></pre>\n<h1>Do you need inheritance at all?</h1>\n<p>Is there a reason why you have made the pure virtual base classes <code>Rival::State</code>? If you only have one derived class <code>Rival::Rival</code>, it really does not do anything, except you have to now keep the members of the base class and the derived class in sync, which is work for you, and now access to the state will have to go via a vtable, which might impact performance. Even if you think you might need it in the future, the <a href=\"https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it\" rel=\"noreferrer\">YAGNI principle</a> applies here: if you don't need it now, don't write it.</p>\n<h1>Don't call <code>SDL_Quit()</code> too early</h1>\n<p>In your original code, after exitting the main loop, you call <code>Application::exit()</code>, which in turn calls <code>SDL_Quit()</code>. However, as far as I can tell, nothing in <code>class Application</code> ever initialized SDL, so it should also not deinitialize it. In particular, the destructor of the variable <code>window</code> in <code>main()</code> will be called afterwards, so that might still rely on SDL being initialized properly.</p>\n<h1>Consider moving event handling into its own function</h1>\n<p>In the main loop, you have a <code>switch()</code> statement handling all possible SDL events. Consider moving this part into its own function, so that the main loop looks as simple as possible:</p>\n<pre><code>while (!exiting) {\n handle_events(); // or maybe state.handle_events()?\n state.update();\n state.render();\n window.swapBuffers();\n}\n</code></pre>\n<p>This will keep the main loop short, and give you a clear high-level overview of what you are doing for each frame you render.</p>\n<h1>Avoid busy-waiting and arbitrary delays</h1>\n<p>If you want to wait for some time to pass or an event to happen, never implement a busy wait, nor a loop that calls <code>SDL_Delay(1)</code>. That is just going to waste CPU cycles, and while the <code>SDL_Delay(1)</code> statement will certainly use less cycles, waiting for just a millisecond will likely prevent the processor from going into a low power state while you are waiting for the next update. This means it will have a higher temperature, which could cause thermal throttling to kick, and for users on a battery-operated device, they will drain their batteries faster.</p>\n<p>If you know that <code>nextUpdateDue > frameStartTime</code>, just call <code>SDL_Delay(nextUpdateDue - frameStartTime)</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T07:42:26.703",
"Id": "490082",
"Score": "0",
"body": "This is a phenomenal answer with some excellent points, thank you. Some notes: One of the reasons I wanted to use a `unique_ptr` for the State is that when I change states later it won't be from main, so subsequent states need to be created on the heap. I made Application a class so that it can act as a kind of service locator (e.g. for Window / Resources) rather than relying on singletons. I will most certainly add more States later, so inheritance will be required. My concern with a longer sleep is that there is a danger of \"oversleeping\", but I agree that the 1ms sleep needs some attention."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T08:08:28.393",
"Id": "490085",
"Score": "1",
"body": "There's little danger of oversleeping unless you actually give a too high value to `SDL_Delay()`. If you can calculate the correct value there is no reason not to use it, and it seems simple enough to do that in the code you posted."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T18:51:05.100",
"Id": "249897",
"ParentId": "249896",
"Score": "7"
}
},
{
"body": "<blockquote>\n<p>My understanding is that by using a unique_ptr my state gets stored on the heap, and this avoids the problem of object slicing</p>\n</blockquote>\n<p>Well... technically, no. When you have a pointer to a base class pointing to a derived class, non virtual methods still get sliced. However, since we allocate on the heap and pass around a pointer to the base class, that information isn't "lost", just "hidden".</p>\n<blockquote>\n<p>My understanding is that when the Application exits (or changes to a new state), the current state will be destroyed / freed. When Rival gets freed, the current Scenario will subsequently be freed. Have I got that right?</p>\n</blockquote>\n<p>Yes (since you are using a smart pointer), but it's always best practice to define a destructor for your class (even if it is just default destructor). Especially in the State class, you need to define a virtual destructor, otherwise the compiler won't know it has to call the derived class' destructor as well. If your derived class' destructor does something non-trivial, it won't be called when the object is destroyed and that can lead to all sorts of nastiness.</p>\n<blockquote>\n<p>I understand that the stack is faster to access, but it is quite small and not particularly suitable for long-lived objects</p>\n</blockquote>\n<p>Not really. Allocating on the stack is faster than on the heap because it involves a bit more bookkeeping, but unless you're allocating thousands of objects on the heap every frame, it's rarely is an issue.</p>\n<p>Now onto the code:</p>\n<ol>\n<li><p>Why the call to <code>window.use()</code>? Just call it in the constructor. As an aside, <code>window.use</code> is kind of a weird name of what the method is doing, something like <code>window.init</code> might be more suitable.</p>\n</li>\n<li><p>Unlike Java, C++ doesn't require you to use classes for everything. <code>ScenarioReader</code> and <code>ScenarioBuilder</code> can be rewritten as free-standing functions, something like this: <code>auto scenario_desc = readScenario(scenarioPath); auto scenario = buildScenario(scenario_desc); </code>. Even better, you can put them inside a common namespace (something like <code>ScenarioUtils</code> and group them.</p>\n</li>\n<li><p><code>Application::exit</code> should be moved inside the destructor, so it is automatically called on destruction, or if an exception occurred.</p>\n</li>\n<li><p><code>Application::getWindow</code> should return a <code>const Window&</code> if you don't want the calling code to be able to modify <code>Window</code>. Also, make sure to use <code>const</code> modifiers whenever possible.</p>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T11:02:03.383",
"Id": "490216",
"Score": "0",
"body": "Regarding making `ScenarioReader` into a free-standing function: reading the file currently involves numerous invocations of private functions within this class, and these all rely on some shared state which is stored at the class level (e.g. current position within the file). Would you suggest passing this state around to all the functions instead? Is there any disadvantage to the class-based approach?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T19:07:53.287",
"Id": "249898",
"ParentId": "249896",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "249897",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T17:39:16.143",
"Id": "249896",
"Score": "7",
"Tags": [
"c++",
"game"
],
"Title": "App initialisation and simple game loop"
}
|
249896
|
<p>I have a <code>scrollHandler</code> function which contains all of my <code>scroll</code> event-listener logic.</p>
<p>I've used multiple IIFE's inside to separate the logic:</p>
<pre><code>import skills from './json/skills.json';
let capToggle = false;
let triggerCalculateHeight = false;
let scrollEnd = false;
function headingFadeIn(heading) {
if (!heading) return;
const parent = heading.parentNode.parentNode;
const triggerHeight = parent.offsetTop - window.innerHeight / 1.5;
if (window.scrollY > triggerHeight) {
heading.style.opacity = '1';
} else heading.style.opacity = '0';
}
export default function scrollHandler() {
// Headings
(() => {
headingFadeIn(document.getElementById('portfolio-heading'));
headingFadeIn(document.getElementById('skills-heading'));
headingFadeIn(document.getElementById('bio-heading'));
headingFadeIn(document.getElementById('contact-heading'));
})();
// Skills
(() => {
const bars = document.querySelectorAll('.skill-bar');
if (!bars) return;
bars.forEach((i, index) => {
const bottom = i.getBoundingClientRect().bottom;
if (window.scrollY > bottom && !i.dataset.heightCalculated) {
i.style.transform = `scale3d(1, ${skills[index].height / 10}, 1)`;
i.setAttribute('data-height-calculated', true);
capToggle = true;
triggerCalculateHeight = true;
}
});
})();
// Reviews
(() => {
const el = document.getElementById('reviews-inner');
if (!el) return;
const mainBackground = document.getElementById('ul-bg');
const backgrounds = document.querySelectorAll('.blockquote-bg');
const texts = document.querySelectorAll('.reviews-toggle');
const bound = el.getBoundingClientRect().top * 10;
if (window.scrollY > bound) {
mainBackground.style.opacity = '1';
mainBackground.style.transform = 'scale(1) rotate(45deg)';
backgrounds.forEach(i => (i.style.opacity = '1'));
backgrounds[0].style.transform = 'translate(-4%, -9%) skew(45deg)';
backgrounds[1].style.transform = 'translate(-6%, -2%) skew(45deg)';
backgrounds[2].style.transform = 'translate(-5%, 1%) skew(45deg)';
texts.forEach(i => (i.style.opacity = '1'));
}
})();
// Bio
(() => {
const container = document.getElementById('bio-container');
const tabSelected = document.getElementById('tab-selected');
const tabBackground = document.getElementById('tab-background');
const height = document.getElementById('bio').offsetTop;
if (!tabBackground || !container || !tabSelected || !height) return;
if (window.scrollY > height / 1.1) {
// Background tab styling
tabBackground.style.left = `${tabSelected.offsetLeft}px`;
tabBackground.style.maxWidth = `${tabSelected.offsetWidth + 20}px`;
// Container transition
container.style.opacity = '1';
container.style.transform = 'skew(-25deg)';
container.childNodes[0].style.transform = 'skew(25deg)';
}
})();
// Contact
(() => {
const groups = document.querySelectorAll('.form-group');
if (!groups) return;
groups.forEach((i, index) => {
i.childNodes[1].blur();
if (window.scrollY > (i.getBoundingClientRect().top * 10) / 1.5) {
i.style.opacity = '1';
if (index >= groups.length - 1) scrollEnd = true;
}
});
})();
return { capToggle, triggerCalculateHeight, scrollEnd };
}
</code></pre>
<p>Is this considered <em>good</em> practice? Are there any pitfalls that could come from this?</p>
|
[] |
[
{
"body": "<p><strong>Modules</strong> You're already using <code>export</code> syntax, so you're currently in a module. Rather than defining multiple IIFEs, you might consider using separate sub-modules:</p>\n<pre><code>// fadeInHeadings.js\n\n// Renaming from headingFadeIn to fadeInHeading for readability\nfunction fadeInHeading(heading) {\n if (!heading) return;\n const parent = heading.parentNode.parentNode;\n const triggerHeight = parent.offsetTop - window.innerHeight / 1.5;\n\n if (window.scrollY > triggerHeight) {\n heading.style.opacity = '1';\n } else heading.style.opacity = '0';\n}\n\nexport const fadeInHeadings = () => {\n const headingIds = [\n 'portfolio-heading',\n 'skills-heading',\n 'bio-heading',\n 'contact-heading',\n ];\n for (const id of headingIds) {\n fadeInHeading(document.getElementById(id));\n }\n};\n</code></pre>\n<pre><code>// scrollHandler.js\nimport { fadeInHeadings } from './fadeInHeadings';\nimport { transformBars } from './transformBars';\nimport { transformReviews } from './transformReviews';\n\nexport default function scrollHandler() {\n fadeInHeadings();\n\n const { capToggled, newTriggerCalculateHeight } = transformBars();\n capToggle ||= capToggled;\n triggerCalculateHeight ||= newTriggerCalculateHeight;\n\n transformReviews();\n\n // ...\n</code></pre>\n<p>This way, when, for example, a review isn't scaling properly, you can navigate directly to <code>transformReviews</code> to debug and fix the problem, rather than wander around in a significantly larger file looking for where reviews are referenced.</p>\n<p><strong>Variable names and iteration</strong> Your two <code>forEach</code>es are a bit confusing:</p>\n<pre><code>bars.forEach((i, index) => {\n</code></pre>\n<p>When <code>i</code> is used as a variable name, it's almost always used to reference the <em>index</em> of a collection. To have <code>i</code> not only not refer to an index, but to also have an <code>index</code> variable, is confusing. Instead, consider:</p>\n<pre><code>bars.forEach((bar, index) => {\n</code></pre>\n<p>Same sort of thing in <code>Contact</code>:</p>\n<pre><code>const groups = document.querySelectorAll('.form-group');\nif (!groups) return;\ngroups.forEach((i, index) => {\n</code></pre>\n<p><code>i</code> should probably be renamed to <code>formGroup</code> or something similar. Also, <code>querySelectorAll</code> will return an array-like NodeList. Even if it's empty, it'll never be falsey, so you can remove the <code>if (!groups) return;</code> line.</p>\n<p><strong>children</strong> You have</p>\n<pre><code>formGroup.childNodes[1].blur();\n</code></pre>\n<p><code>childNodes</code> returns a collection that <em>includes text nodes</em>. Text nodes can be empty, and including them in a collection can make logic more tedious than it needs to be. Since you want to select an <em>element</em> with that, better to use <code>.children</code> (which only returns element children nodes), so you can do</p>\n<pre><code>formGroup.children[1].blur();\n// or\nformGroup.children[0].blur();\n// or, be more specific and use a CSS selector\nformGroup.querySelector(<some-selector>).blur();\n</code></pre>\n<p><strong>Persistent variables?</strong> The persistent module variables seem a bit odd. If they really need to be in persistent state, it might make sense to expose a function that returns their current values. If they aren't meant to be persistent, initialize them to <code>false</code> inside <code>scrollHandler</code> instead - or, inside the sub-module which reassigns its value, which is returned to <code>scrollHandler</code> and then returned by <code>scrollHandler</code>. For example, it'd be great if you could do this:</p>\n<pre><code>// showFormGroups.js\nexport const showFormGroups = () => {\n const groups = document.querySelectorAll('.form-group');\n let scrollEnd = false;\n groups.forEach((formGroup, index) => {\n formGroup.children[1].blur();\n if (window.scrollY > (formGroup.getBoundingClientRect().top * 10) / 1.5) {\n formGroup.style.opacity = '1';\n if (index >= groups.length - 1) {\n scrollEnd = true;\n }\n }\n });\n return scrollEnd;\n};\n</code></pre>\n<pre><code>// scrollHandler.js\nexport default function scrollHandler() {\n // ...\n const scrollEnd = showFormGroups();\n // ...\n return { capToggle, triggerCalculateHeight, scrollEnd };\n</code></pre>\n<p><strong>Styles into CSS</strong> You have</p>\n<pre><code>if (window.scrollY > bound) {\n mainBackground.style.opacity = '1';\n mainBackground.style.transform = 'scale(1) rotate(45deg)';\n backgrounds.forEach(i => (i.style.opacity = '1'));\n backgrounds[0].style.transform = 'translate(-4%, -9%) skew(45deg)';\n backgrounds[1].style.transform = 'translate(-6%, -2%) skew(45deg)';\n backgrounds[2].style.transform = 'translate(-5%, 1%) skew(45deg)';\n texts.forEach(i => (i.style.opacity = '1'));\n}\n</code></pre>\n<p>To apply this logic, I think it'd make more sense to put the CSS rules in your CSS file, and then just toggle a class. Something like:</p>\n<pre><code>// SCSS for brevity\nbody.showReviews {\n #ul-bg {\n opacity: 1;\n transform: scale(1) rotate(45deg);\n }\n .blockquote-bg {\n opacity: 1;\n }\n .blockquote-bg:nth-of-type(1) {\n transform: translate(-4%, -9%) skew(45deg);\n }\n .blockquote-bg:nth-of-type(2) {\n transform: translate(-6%, -2%) skew(45deg);\n }\n .blockquote-bg:nth-of-type(3) {\n transform: translate(-5%, 1%) skew(45deg);\n }\n .reviews-toggle {\n opacity: 1;\n }\n}\n</code></pre>\n<pre><code>// transformReviews.js\nexport const transformReviews = () => {\n const el = document.getElementById('reviews-inner');\n if (!el) return;\n const bound = el.getBoundingClientRect().top * 10;\n document.body.classList.toggle('showReviews', window.scrollY > bound);\n};\n</code></pre>\n<p><strong>Framework</strong> On a larger scale, all of this careful element selecting, iterating, examining, and manual manipulation of the DOM seems a bit tedious. For a professional project that isn't tiny, I would prefer to look into a framework like React to tie element state directly to their respective DOM elements.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T20:15:22.220",
"Id": "490053",
"Score": "0",
"body": "This is very in-depth! Really appreciate it. When I'm not bleary-eyed I'll give it a full look over"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T20:20:33.953",
"Id": "490054",
"Score": "0",
"body": "Never mind, I couldn't help myself. This is brilliant, lot's of helpful tips. I'll definitely put some of these into practice, thanks again"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T20:12:40.040",
"Id": "249900",
"ParentId": "249899",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249900",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T19:22:04.093",
"Id": "249899",
"Score": "4",
"Tags": [
"javascript"
],
"Title": "Multiple anonymous IIFEs inside outer function"
}
|
249899
|
<p>Trying to learn a new skill at 40 without any prior related experience :-) Bought the book 'Python crash course 2e' and decided to freewheel a bit with after a week with what I've learned so far.. I put everything in a small program to order pizzas and I would love some feedback before I take up bad habits..</p>
<p>first off: although I think I understand the concept of functions and classes, I didn't see the need to use these because it was quite simple.. but now it's getting a bit difficult. I tried to get away with simple lists and dictionaries to store orders and prices.. But trouble emerges when you want to order 2 of the same pizzas with different toppings (you get identical keys). Also, giving the price for a final order was nice, but if you want to delete a pizza from the order, I can't think of a way to delete the items from the list.</p>
<p>Maybe someone can give me some feedback in what direction I should look for a solution?</p>
<pre><code>#making the lists
available_pizzas = ['margarita', 'pollo', '4cheese', 'bolognese', 'vegetarian']
available_toppings = ['mushroom', 'onions', 'green pepper', 'extra cheese']
pizza_prices = {'margarita': 5, 'pollo': 7, '4cheese': 6, 'bolognese': 8, 'vegetarian': 6.5}
topping_prices = {'mushroom':1, 'onions': 2, 'green pepper':3, 'extra cheese':4}
sub_total = []
final_order = {}
customer_adress = {}
#ordering a pizza
print("Hi, welcome to our text based pizza ordering")
order_pizza = True
while order_pizza:
print("Please choose a pizza: ")
print()
for pizzas in available_pizzas:
print(pizzas)
print()
while True:
pizza = input("which pizza would you like to order?")
if pizza in available_pizzas:
print(f"You have ordered a {pizza}.")
sub_total.append(pizza_prices[pizza])
break
if pizza not in available_pizzas:
print(f"I am sorry, we currently do not have {pizza}.")
#asking for extra toppings
order_topping = True
print("This is the list of available extra toppings: ")
for toppings in available_toppings:
print(toppings)
print()
while order_topping:
extra_topping = input("Would you like an extra topping? yes or no?")
if extra_topping == "yes":
topping = input("Which one would you like to add?")
if topping in available_toppings:
final_order.setdefault(pizza, [])
final_order[pizza].append(topping)
print(f"I have added {topping}.")
sub_total.append(topping_prices[topping])
else:
print(f"I am sorry, we don't have {topping} available.")
elif extra_topping == "no":
break
extra_pizza = input("Would you like to order another pizza?")
if extra_pizza == "no":
for key, value in final_order.items():
print(f"\nYou have order a {key} pizza with {value}")
check_order = True
while check_order:
print()
order_correct = input("Is this correct? yes/no ")
if order_correct == "yes":
check_order = False
order_pizza = False
if order_correct == "no":
print(final_order)
add_remove = input("would you like to add or remove? ")
if add_remove == "remove":
remove = input("Which pizza would you like to remove? ")
del final_order[remove]
print(final_order)
if add_remove == "add":
check_order = False
#finalizing the order
print(f"\nYour total order price is: ${sum(sub_total)}")
print("Please provide us with your name, adress and phonenumber")
customer_adress['name'] = input("what is your name?")
customer_adress['street_name'] = input("What is your streetname and housenumber?")
customer_adress['postalcode'] = input("What is the postalcode and cityname?")
customer_adress['phonenumber'] = input("What is your phonenumber?")
print()
print(f"Thank you for your order {customer_adress['name']}.")
print()
print("We will deliver your order to this adres ASAP")
print()
print(customer_adress['street_name'])
print(customer_adress['postalcode'])
print()
print(f"we will contact you on {customer_adress['phonenumber']} if anything comes up.")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T00:30:28.070",
"Id": "490071",
"Score": "0",
"body": "What version of Python are you using? Are you using Python 3.7+?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T05:38:34.543",
"Id": "490079",
"Score": "0",
"body": "@Peilonrayz Thanks. Python 3.8.3."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-08T05:19:38.380",
"Id": "491193",
"Score": "0",
"body": "@OsmanPolat consider accepting one of the answers"
}
] |
[
{
"body": "<p>Welcome to CR community.</p>\n<ol>\n<li><p>Keep constant declarations at the top. Although you follow the PEP8 naming conventions throughout (almost) the whole code base, constant (or globals) are named as <code>UPPER_SNAKE_CASE</code>. So, the <code>pizza_prices</code> would become <code>PIZZA_PRICES</code>.</p>\n</li>\n<li><p>Use triple-quoted strings in python for multiline content. Your print statements would look a lot cleaner (no need for empty <code>print()</code> statements).</p>\n</li>\n<li><p>Put the execution flow of your code inside <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\">the <code>if __name__ == "__main__"</code></a> block.</p>\n</li>\n<li><p>Instead of having separate variables for list of pizza/toppings and their prices, keep only the mapping of pizza/toppings, and you can get list of pizza/toppings using the <code>dict.items()</code> iterator.</p>\n</li>\n<li><p>Since a majority of code execution is dependent on valid input choice from the user; it's better to provide those choices in the input call. For eg:</p>\n<pre><code>extra_pizza = input("Would you like to order another pizza?")\n</code></pre>\n<p>does not make it clear where the user should type "<code>y/Y/Yes/N/n/No/Cancel/Quit</code>". Putting this choice selection in a separate function would be more helpful:</p>\n<pre><code>def get_user_choice(message, *choices):\n prompt = f"{message}\\n\\nChoicese are: {' '.join(choices)}"\n while True:\n choice = input(prompt)\n if choice in choices:\n return choice\n print("Wrong selection")\n</code></pre>\n<p>now call the above as follows:</p>\n<pre><code>add_remove = get_user_choice("would you like to add or remove?", "add", "remove")\n</code></pre>\n</li>\n<li><p>As you're beginning with programming, I'd suggest gathering associated resources into a class, instead of using a dictionary. For eg. a <code>Customer</code> class, with <code>name</code>, <code>phone</code> etc. attributes. Another <code>Pizza</code> class with associated <code>type</code> and <code>toppings</code> etc.</p>\n</li>\n</ol>\n<hr />\n<h3>To expand on point 4:</h3>\n<pre><code>PIZZA_PRICING = {\n "margarita": 5,\n "pollo": 7,\n "4cheese": 6,\n "bolognese": 8,\n "vegetarian": 6.5,\n}\n</code></pre>\n<p>Asking user's preference for pizza:</p>\n<pre><code>pizza_choice = get_user_choice("Please choose a pizza:", *PIZZA_PRICING.keys())\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T14:17:34.853",
"Id": "490117",
"Score": "0",
"body": "thank you for your feedback! I'm still figuring out on when and where to use classes. But I didn't get the dictionary part. How do I store for example the ordered pizza with toppings in a class? It needs to 'remember' somehow I guess, any link with info on this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T15:18:37.780",
"Id": "490138",
"Score": "0",
"body": "@OsmanPolat updated my post above/"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T08:47:48.677",
"Id": "249911",
"ParentId": "249903",
"Score": "7"
}
},
{
"body": "<p>Your code is quite easy to follow. So good job for that. There is still some room for improvement. Not loads of changes.</p>\n<hr />\n<h1>Clear screen</h1>\n<p>Python has certain functions to clear any text printed on the console.\n<a href=\"https://www.geeksforgeeks.org/clear-screen-python/\" rel=\"nofollow noreferrer\">Check this page</a> for all the information.</p>\n<p>if you are on windows, you can <code>pip install os</code>\nand then <code>import os</code> at the top of your program to use these functions.</p>\n<p>For example, <code>os.system('pause')</code> can be used to wait for the user to click any key after you show them a message.</p>\n<h1>Use <code>'\\n'</code></h1>\n<p>I'm not sure why I see many empty <code>print()</code>'s but I think you are trying to print a newline. By default after using the <code>print()</code> function there will always be a newline at the end of the text. But if you want to print more, use <code>'\\n'</code>. For example, After you have printed\nsomething</p>\n<p>Wrong:</p>\n<pre class=\"lang-py prettyprint-override\"><code>print("Hello,World!")\nprint()\nprint("Yay")\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-py prettyprint-override\"><code>Hello World!\n\n\nYay\n</code></pre>\n<p>Correct:</p>\n<pre class=\"lang-py prettyprint-override\"><code>print("Hello,World!\\n")\nprint("Yay")\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-py prettyprint-override\"><code>Hello World!\n\n\nYay\n</code></pre>\n<h1>Use Functions</h1>\n<p>Move the order-taking part into a function this way. You can also make a new function called <em><strong>ShowMenu()</strong></em> to print to the menu each time you call the function.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def ShowMenu():\n os.system('cls')\n print("Available Pizzas:\\n")\n print(*available_pizzas,sep = ', ')\n print("\\n\\nAvailable Topings:\\n")\n print(*available_toppings,sep = ', ')\n print('\\n\\n')\n\ndef TakeOrderInput():\n os.system('cls')\n print("Hi, welcome to our text based pizza ordering")\n ordering = True\n while ordering:\n os.system('cls')\n ShowMenu()\n pizza = input("Please choose a pizza: ")\n if pizza not in available_pizzas:\n print(f"I am sorry, we currently do not have {pizza}\\n.")\n os.system('pause')\n continue\n topping = input("Please choose a topping: ")\n if topping not in available_toppings:\n print(f"I am sorry, we currently do not have {topping}\\n.")\n os.system('pause')\n continue\n\n print(f"Final order: {pizza} with topping {topping}: ")\n ordering = False\n\n return pizza,topping\n</code></pre>\n<p>What do you do now when you want to take a new order?</p>\n<pre class=\"lang-py prettyprint-override\"><code>pizza, topping = TakeOrderInput()\n</code></pre>\n<h1>Object-oriented programming</h1>\n<p>If you don't know what <a href=\"https://searchapparchitecture.techtarget.com/definition/object-oriented-programming-OOP#:%7E:text=Object%2Doriented%20programming%20(OOP)%20is%20a%20computer%20programming%20model,has%20unique%20attributes%20and%20behavior.\" rel=\"nofollow noreferrer\">OOP</a> is, it's time that you learn about it as It helps you make your code much cleaner and moreover HELPS you code better.</p>\n<p>There's no rule that you have to use Object-oriented programming, it is completely up to you as you are the developer and it's your style. But here is a typical implementation of <strong><a href=\"https://www.w3schools.com/python/python_classes.asp\" rel=\"nofollow noreferrer\">classes</a></strong> in context to your program.</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Order:\n def __init__(self):\n taxes = 0 #You can add taxes\n pizza,topping = TakeOrderInput()\n self.type = pizza\n self.topping = topping\n self.PizzaPrice = pizza_prices[pizza]\n self.ToppingPrice = topping_prices[topping]\n self.Total = self.PizzaPrice + self.ToppingPrice\n print(self.Total)\n</code></pre>\n<p>Of course this a just a small implementation of classes, once you learn more you can add more stuff like billing address, taxes et cetera.</p>\n<h1>Take a new order</h1>\n<p>With all that we have done. On its own it does nothing. We need to now use these functions</p>\n<pre class=\"lang-py prettyprint-override\"><code>choice = True\norders = []\norderchoice = input("Welcome! Would you like to order ? (y/n): ")\nif orderchoice == 'n':\n print("Have a nice day!")\nelse:\n while choice:\n neworder = Order()\n orders.append(neworder)\n newchoice = input("Would you like to order again? (y/n): ")\n if (newchoice) == 'n':\n break\n</code></pre>\n<p>This will finally make a list of all the orders the user has given. To access anything iterate through the list and then get the attribute. For example, If you want to get the total cost.</p>\n<pre class=\"lang-py prettyprint-override\"><code>total = 0\nfor order in orders:\n total+=order.Total\n\nprint(total)\n</code></pre>\n<h2>Final</h2>\n<p>Here is what your program would look like with all the changes</p>\n<pre class=\"lang-py prettyprint-override\"><code>import os\n\navailable_pizzas = ['margarita', 'pollo', '4cheese', 'bolognese', 'vegetarian']\navailable_toppings = ['mushroom', 'onions', 'green pepper', 'extra cheese']\npizza_prices = {'margarita': 5, 'pollo': 7, '4cheese': 6, 'bolognese': 8, 'vegetarian': 6.5}\ntopping_prices = {'mushroom':1, 'onions': 2, 'green pepper':3, 'extra cheese':4}\n\ndef ShowMenu():\n os.system('cls')\n print("Available Pizzas:\\n")\n print(*available_pizzas,sep = ', ')\n print("\\n\\nAvailable Topings:\\n")\n print(*available_toppings,sep = ', ')\n print('\\n\\n')\n\ndef TakeOrderInput():\n os.system('cls')\n print("Hi, welcome to our text based pizza ordering")\n ordering = True\n while ordering:\n os.system('cls')\n ShowMenu()\n pizza = input("Please choose a pizza: ")\n if pizza not in available_pizzas:\n print(f"I am sorry, we currently do not have {pizza}\\n.")\n os.system('pause')\n continue\n topping = input("Please choose a topping: ")\n if topping not in available_toppings:\n print(f"I am sorry, we currently do not have {topping}\\n.")\n os.system('pause')\n continue\n\n print(f"Final order: {pizza} with topping {topping}: ")\n ordering = False\n\n return pizza,topping\n\nclass Order:\n def __init__(self):\n taxes = 0 #You can add taxes\n pizza,topping = TakeOrderInput()\n self.type = pizza\n self.topping = topping\n self.PizzaPrice = pizza_prices[pizza]\n self.ToppingPrice = topping_prices[topping]\n self.Total = self.PizzaPrice + self.ToppingPrice\n\n\n\n\n\nchoice = True\norders = []\norderchoice = input("Welcome! Would you like to order ? (y/n): ")\nif orderchoice == 'n':\n print("Have a nice day!")\nelse:\n while choice:\n neworder = Order()\n orders.append(neworder)\n newchoice = input("Would you like to order again? (y/n): ")\n if (newchoice) == 'n':\n break\n\ntotal = 0\nfor order in orders:\n total+=order.Total\n\nprint("Total: ",total, '$')\n</code></pre>\n<p>I haven't done anything to the final part which was the address, Phone number et cetera, you can add those things as you wish.</p>\n<p>I hope you found this review useful </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T11:26:48.037",
"Id": "490093",
"Score": "3",
"body": "function names in python follow `lower_snake_case` naming convention."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T11:27:25.287",
"Id": "490094",
"Score": "0",
"body": "@hjpotter92 As long as the naming convention is clear to you and others reading your code, consistent, not too big, not too small. I believe it is one's choice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T12:57:28.677",
"Id": "490107",
"Score": "3",
"body": "Please do not teach people to call `os.system()` for trivial tasks like clearing the screen or waiting for a keypress. This is a very costly operation (it needs to create a new process, start a shell interpreter, and interpret the command), and it is not portable. To wait for input, you can just `print('Press Enter to continue'); input()`, to clear the screen you can print an ANSI escape code: `print('\\x1b[2J')`. That is way more efficient and while not perfectly portable, still better than `os.system('cls')`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T13:16:15.503",
"Id": "490109",
"Score": "0",
"body": "@G.Sliepen what shall I use to clear the screen?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T13:19:44.670",
"Id": "490110",
"Score": "1",
"body": "See [this answer](https://stackoverflow.com/a/37778152/5481471) for how to clear the screen by just `print()`ing a so-called [ANSI escape code](https://en.wikipedia.org/wiki/ANSI_escape_code)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T14:13:05.680",
"Id": "490113",
"Score": "0",
"body": "Hey, your `Order` class would be much better if you take `pizza` and `topping` in as arguments to `__init__`. Calling `TakeOrderInput()` makes extending and testing harder."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T14:14:02.983",
"Id": "490114",
"Score": "0",
"body": "@AryanParekh Thank you so much! Your explanation is very usefull. I do need figure out how I can tweek your code that i can add multiple toppings and show the whole final order and getting approval to move to the final order step. I wasn't able to install the os module, but I think I can work around that :) Thanks again!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T14:15:19.323",
"Id": "490115",
"Score": "0",
"body": "@G.Sliepen this is gold > print('\\x1b[2J') thanks1"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T14:35:34.090",
"Id": "490121",
"Score": "0",
"body": "@OsmanPolat You don't need to install the `os` module; it comes with Python."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T14:52:30.320",
"Id": "490129",
"Score": "0",
"body": "@wizzwizz4 ah ok.. but I get 'sh: cls: command not found'. I decided to work around it with the mentioned print('\\x1b[2J')"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T18:20:34.350",
"Id": "490172",
"Score": "0",
"body": "@wizzwizz4 Thank you for your suggestion, but when I was working with it I had to install it. Which is why I mentioned it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T18:21:56.670",
"Id": "490173",
"Score": "0",
"body": "@OsmanPolat I am glad you found it useful, but G.Sliepen mentioned, it will be better you use the ANSI escape codes rather than what I had used."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T19:15:57.453",
"Id": "490178",
"Score": "0",
"body": "@AryanParekh how would you solve the multiple topping on pizza? and the showing of the complete final order? I'm trying to enhance my code with your suggestions, but this got me a bit stuck :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T19:18:17.643",
"Id": "490179",
"Score": "0",
"body": "@OsmanPolat If you want multiple toppings make it a list rather than a single string.` Once you have let's say `topping` and `topping2`. Instead of `self.topping = topping` You can use `self.toppings = [topping1,topping]`. For price iterate through the list and add the price"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T19:34:48.190",
"Id": "490180",
"Score": "0",
"body": "@AryanParekh thanks, that makes sense. But does it automatically add values to the list? Like, i don't have to make a topping, topping2, topping3 etc..? Btw, I appreciate the feedback."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T19:36:14.440",
"Id": "490181",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/113451/discussion-between-aryan-parekh-and-osman-polat)."
}
],
"meta_data": {
"CommentCount": "16",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T11:19:58.470",
"Id": "249915",
"ParentId": "249903",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T22:55:17.087",
"Id": "249903",
"Score": "9",
"Tags": [
"python",
"beginner",
"python-3.x",
"hash-map"
],
"Title": "first pizza order program"
}
|
249903
|
<p>The code adds approximately 1,720,000 different combinations of numbers to a file, <code>some_other_file.txt</code>. The numbers range from 2 digits long to 16 digits long.</p>
<p>I add 500 numbers at a time to <code>some_file.txt</code> and upon hitting the 500th I move all the numbers to the end of <code>some_other_file.txt</code>.</p>
<p>My code works. But it takes ages to run and uses a lot of ram. How can I improve on them?</p>
<pre class="lang-py prettyprint-override"><code>while True:
for u in range(1,501):
with open('some_file.txt', "a") as file:
for g in range(1,500):
if (g % 100)==0:# speeds up the code by only running one out of 100 times
os.system("clear")
print("adding to file...")
print ("sections loaded: "+str(u-1)+"/100")
print("total loaded: "+str((g+((u-1)*500))*chunks)+"/"+str(length3))
sleep(0.0000001)
if ((g+((u-1)*500))*chunks)<=length3: # length3 is the length of the list I'm adding to file (1720000 long aprox) and chunks is how many times while True loop has run through
file.write("\n"+update[((g-1)+((u-1)*500))*chunks])
else:
print("error")
break
with open('some_file.txt', "r") as file:
l=file.read()
with open('some_file.txt', "w") as file: # clears file
file.write("")
with open('some_other_file.txt', "a") as file:
file.write("\n"+l)
l=""
if int((g+((u-1)*5))*chunks)>=int(length3): # chunks is how many times the while True loop has run through
break
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T23:38:36.577",
"Id": "490068",
"Score": "7",
"body": "\"I will update this post as I improve the code\" please do not do that, that will make reviewing your code hard as it'll be forever shifting. Additionally upon getting an edit you are no longer allowed to edit the code in the question."
}
] |
[
{
"body": "<ol>\n<li><p>We should remove the file information from the loops. We should interact with the files and the output outside the loop.</p>\n<p><strong>Note</strong>: Code changed to follow a standard Python style</p>\n<pre class=\"lang-py prettyprint-override\"><code>def generate_numbers(update, length):\n chunks = 1\n while True:\n for u in range(1, 501):\n for g in range(1, 500):\n if chunks * (g + (u - 1) * 500) <= length3:\n file.write("\\n"+update[(g - 1 + (u - 1) * 500) * chunks])\n else:\n print("error")\n break\n if int((g + (u - 1) * 5) * chunks) >= int(length3):\n break\n chunks += 1\n</code></pre>\n</li>\n<li><p>We can see that <code>u</code> is always used as <code>u-1</code> so we should change the <code>range</code> to <code>range(500)</code>.</p>\n</li>\n<li><p>We should change <code>file.write</code> to <code>yield</code> and move the <code>"\\n"+</code> outside the function.</p>\n</li>\n<li><p>Your control flow with <code>print("error")</code> is really odd. Let's run a quick whitebox test.</p>\n<pre class=\"lang-py prettyprint-override\"><code>(u = 497, g = 1, length3 = 500, chunks = 1) # Part way through iterating\n> if chunks * (g + u * 500) <= length3:\n> 1 * (1 + 497 * 500) <= 500\n> 248501 <= 500\n> print("error")\n> break\n(u = 498)\n> if chunks * (g + u * 500) <= length3:\n> 1 * (1 + 498 * 500) <= 500\n> 249001 <= 500\n> print("error")\n> break\n(u = 499)\n> if chunks * (g + u * 500) <= length3:\n> 1 * (1 + 499 * 500) <= 500\n> 249501 <= 500\n> print("error")\n> break\n> if int((g + u * 5) * chunks) >= int(500):\n> if int((1 + 499 * 5) * 1) >= int(500):\n> if 2496 >= int(500):\n> break\n</code></pre>\n<p>We should notice that there are 2 oddities here.</p>\n<ul>\n<li>Your last if looks wrong. <code>(g+((u-1)*5))*chunks</code> should probably be <code>(g+((u-1)*500))*chunks</code>.</li>\n<li>You should use a <code>try</code> and remove the <code>if</code> as <code>length3</code> looks like the bound of <code>update</code>.</li>\n</ul>\n</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>def generate_numbers(update):\n chunks = 1\n try:\n while True:\n for u in range(500):\n for g in range(1, 500):\n yield update[(g + u * 500 - 1) * chunks]\n chunks += 1\n except IndexError:\n pass\n</code></pre>\n<ol start=\"5\">\n<li>Since we've removed the file manipulation we can merge the loop to make <code>u</code> and <code>g</code> together.\nThis is because they together make the range <code>500*500</code>.</li>\n<li>We can change the <code>while True</code> to a for that calls <code>itertools.count</code>.</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>import itertools\n\ndef generate_values(update):\n try:\n for chunks in itertools.count(1):\n for index in range(250000):\n yield update[index * chunks]\n except IndexError:\n pass\n</code></pre>\n<hr />\n<p>Let's look at how you interact with the files.</p>\n<pre class=\"lang-py prettyprint-override\"><code>while True:\n for u in range(1,501):\n with open('some_file.txt', "a") as file:\n file.write(...)\n with open('some_file.txt', "r") as file:\n l=file.read()\n with open('some_file.txt', "w") as file:\n file.write("")\n with open('some_other_file.txt', "a") as file:\n file.write("\\n"+l)\n l=""\n</code></pre>\n<p>It doesn't make sense to not just write to <code>some_other_file.txt</code> in append mode.</p>\n<pre class=\"lang-py prettyprint-override\"><code>with open('some_other_file.txt', "a") as file:\n for item in generate_values(update):\n file.write("\\n" + item)\n</code></pre>\n<p>If you want to display the output then you can just use <a href=\"https://docs.python.org/3/library/itertools.html#itertools.islice\" rel=\"nofollow noreferrer\"><code>itertools.islice</code></a>. And you can use <code>enumerate</code> to build the index.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def chunk_iter(it, amount):\n while True:\n chunk = list(itertools.islice(it, amount))\n if not chunk:\n break\n yield chunk\n\n\nwith open('some_other_file.txt', "a") as file:\n for i, chunk in enumerate(chunk_iter(generate_values(update), 100)):\n print("adding to file...")\n print(f"total loaded: {i * 100 + len(chunk)}/{len(update)}")\n for item in chunk:\n file.write("\\n" + item)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T07:16:42.713",
"Id": "490306",
"Score": "0",
"body": "I can't use intertools, I tried getting the code for the intertool functions off the official docs, but that wasn't working either (said num of arguments in generators weren't supported), what would be an alternative to that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T01:58:29.007",
"Id": "490569",
"Score": "0",
"body": "nvm, I'm going to code my own alternative to it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T02:04:53.583",
"Id": "249906",
"ParentId": "249904",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249906",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-26T23:28:17.440",
"Id": "249904",
"Score": "-2",
"Tags": [
"python",
"performance",
"python-3.x",
"memory-optimization"
],
"Title": "Adding 1 million combinations of numbers to a file"
}
|
249904
|
<p>I wrote a simplified versions of Windows' <a href="https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/tracert" rel="nofollow noreferrer"><code>tracert</code></a> command as an exercise and to learn about TTL in packets. It shows the path that your internet traffic will (likely) take on the way to the given destination.</p>
<p>Here's an example (some stuff is redacted out of paranoia):</p>
<p><a href="https://i.stack.imgur.com/3ulzW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3ulzW.png" alt="enter image description here" /></a></p>
<pre><code>python tracert.py google.com -h
usage: tracert.py [-h] [-d] [-o O] [-w W] [-t T] ip
positional arguments:
ip
optional arguments:
-h, --help show this help message and exit
-d Do not resolve addresses to hostnames.
-o O Maximum number of hops to search for target.
-w W Wait timeout milliseconds for each reply.
-t T How many per packets to send per hop.
</code></pre>
<p>Unfortunately, due to using Scapy, the timings seem to be somewhat broken. Sending packets seems to have an inherent overhead, and that overhead dwarfs the actual time. Unless Scapy provides a way to access round-trip times though, I don't think I can fix that without doing away with Scapy and doing the packet construction/sending manually. I mention this since anyone familiar with <code>tracert</code> will likely find the pattern of times odd. They were included mostly as a "semi-functional" placeholder so I could try to implement the incremental behavior of <code>tracert</code>.</p>
<p>I tried to match a lot of <code>tracert</code>s behavior, but I didn't go overboard. I opted to have the target first instead of last for simplicity.</p>
<p>The hardest part was getting displaying incremental as they came in to match <code>tracert</code>. I went through several redesigns of <code>_tracert_hop_row</code> where I tried to return an iterable of results, and the consumer could print results as they were produced. This ended up being a mess though, because I also needed to communicate back whether we had found the destination yet. I ended up printing the result directly instead.</p>
<p>My main concern is <code>_tracert_hop_row</code>. It's a mess, and it's long. Any tips regarding it or anything else would be appreciated.</p>
<p><code>reverse_dns.py</code></p>
<pre><code>from typing import Union
from scapy.layers.inet import UDP, IP
from scapy.layers.dns import DNS, DNSQR, DNSRR
from scapy.sendrecv import sr1
_REVERSE_DOMAIN = ".in-addr.arpa"
_OCTET_DELIMITER = "."
def _reverse_dns_packet(ip: str, dns_server: str) -> DNS:
reversed_ip = _OCTET_DELIMITER.join(reversed(ip.split(_OCTET_DELIMITER)))
question = DNSQR(qname=f"{reversed_ip}{_REVERSE_DOMAIN}", qtype=12)
return IP(dst=dns_server) / UDP(dport=53) / DNS(qd=question)
def reverse_dns_lookup(ip: str, dns_server: str, **sr1_kwargs) -> Union[None, int, str]:
"""
Returns the str host-name if it could be resolved,
or an int response code if there was an error,
or None if the DNS server couldn't be reached.
Unless you know the DNS server will be reachable, setting a timeout via the kwargs is advised.
"""
request = _reverse_dns_packet(ip, dns_server)
resp = sr1(request, **sr1_kwargs)
if resp is None:
return None
resp_code = resp[1][DNS].rcode
if resp_code == 0:
raw = resp[1][DNSRR].rdata
return raw.decode("UTF-8")
else:
return resp_code
</code></pre>
<p><code>tracert.py</code></p>
<pre><code>from typing import Tuple, List, Optional, Callable, TypeVar
from collections import Counter
from time import perf_counter
import argparse as ap
from scapy.config import conf
from scapy.layers.inet import IP, ICMP
from scapy.sendrecv import sr1
from reverse_dns import reverse_dns_lookup
_MAX_TTL = 255
_DEFAULT_TIMEOUT = 5
_DEFAULT_VERBOSITY = False
_DEFAULT_TESTS_PER = 3
_DEFAULT_RESOLVE_HOSTNAMES = True
_TABLE_SPACING = 10
NO_INFO_SYM = "*"
T = TypeVar("T")
def _new_trace_packet(destination_ip: str, hop_n: int) -> ICMP:
return IP(dst=destination_ip, ttl=hop_n) / ICMP()
# Credit: https://stackoverflow.com/a/60845191/3000206
def get_gateway_of(ip: str) -> str:
return conf.route.route(ip)[2]
def _check_hop_n(destination_ip: str, hop_n: int, **sr1_kwargs) -> Optional[Tuple[str, bool]]:
"""
Returns a tuple of (hop_ip, destination_reached?)
"""
sr1_kwargs.setdefault("timeout", _DEFAULT_TIMEOUT)
sr1_kwargs.setdefault("verbose", _DEFAULT_VERBOSITY)
packet = _new_trace_packet(destination_ip, hop_n)
reply = sr1(packet, **sr1_kwargs)
return reply and (reply[IP].src, reply[ICMP].type == 0)
def _find_proper_route(replies: List[ICMP]) -> Optional[Tuple[str, bool]]:
if not replies:
return None
ip_isfin_pairs = [(resp[IP].src, resp[ICMP].type == 0) for resp in replies]
found_destination = next((ip for ip, isfin in ip_isfin_pairs if isfin), None)
selected_ip = found_destination or Counter(ip for ip, _ in ip_isfin_pairs).most_common(1)[0][0]
return selected_ip, bool(found_destination)
def _time_exec(f: Callable[[], T]) -> Tuple[float, T]:
"""
Executes the function and returns a tuple of [exec_seconds, result].
"""
start = perf_counter()
result = f()
end = perf_counter()
return end - start, result
def _cell_print(x: str) -> None:
print(x.ljust(_TABLE_SPACING), end="", flush=True)
def _tracert_hop_row(destination_ip: str,
n_tests: int,
hop_n: int,
resolve_hostname: bool,
**sr_kwargs) -> bool:
sr_kwargs.setdefault("timeout", _DEFAULT_TIMEOUT)
sr_kwargs.setdefault("verbose", _DEFAULT_VERBOSITY)
packet = _new_trace_packet(destination_ip, hop_n)
replies = []
for _ in range(n_tests):
secs, reply = _time_exec(lambda: sr1(packet, **sr_kwargs))
_cell_print(NO_INFO_SYM if reply is None else f"{int(secs * 1000)} ms")
if reply:
replies.append(reply)
if not replies:
_cell_print(NO_INFO_SYM)
return False
best_route, found_destination = _find_proper_route(replies)
if resolve_hostname:
host = reverse_dns_lookup(best_route, get_gateway_of(best_route), **sr_kwargs)
if isinstance(host, str):
_cell_print(f"{host} [{best_route}]")
else:
_cell_print(best_route)
else:
_cell_print(best_route)
return found_destination
def tracert_internal(destination_ip: str,
n_tests_per_hop: int = _DEFAULT_TESTS_PER,
resolve_hostnames: bool = _DEFAULT_RESOLVE_HOSTNAMES,
max_hops: int = _MAX_TTL,
**sr_kwargs) -> None:
for hop_n in range(1, max_hops + 1):
_cell_print(str(hop_n))
found_destination = _tracert_hop_row(destination_ip, n_tests_per_hop, hop_n, resolve_hostnames, **sr_kwargs)
print()
if found_destination:
break
def main():
parser = ap.ArgumentParser()
parser.add_argument("ip")
parser.add_argument("-d", action="store_false", default=True,
help="Do not resolve addresses to hostnames.")
parser.add_argument("-o", type=int, default=_MAX_TTL,
help="Maximum number of hops to search for target.")
parser.add_argument("-w", type=float, default=_DEFAULT_TIMEOUT,
help="Wait timeout milliseconds for each reply.")
parser.add_argument("-t", type=int, default=_DEFAULT_TESTS_PER,
help="How many per packets to send per hop.")
args = parser.parse_args()
try:
tracert_internal(args.ip, args.t, args.d, args.o, timeout=args.w)
except KeyboardInterrupt:
pass
if __name__ == '__main__':
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T00:55:06.433",
"Id": "490074",
"Score": "0",
"body": "Is the Scapy issues acceptable? Are you asking for help with it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T00:57:27.657",
"Id": "490075",
"Score": "0",
"body": "@Peilonrayz The code works, the times are just not very accurate. I only included them to match the incremental behavior of the actual program. They weren't the focus of this program. No, I don't want the timing inflation dealt with here. I just included the comment since anyone who uses `tracert` would probably notice the odd time pattern."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T01:00:03.350",
"Id": "490076",
"Score": "0",
"body": "Ok, that seems fine for me. Our short exchange should keep your question from being closed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-17T15:33:14.933",
"Id": "496903",
"Score": "0",
"body": "Make sure you are using 2.4.4. It fixed most of the issues with packet timestamps"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-17T15:41:10.713",
"Id": "496905",
"Score": "0",
"body": "@Cukic0d Thanks. That's what I'm currently using though. I think it's just the overhead of the library, and other stuff like the fact that I'm wrapping the code in a lambda before timing. Timing the entirety of the `sr1` is probably not great since `sr1` seems to be doing quite a lot behind the scenes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-17T16:03:18.593",
"Id": "496908",
"Score": "0",
"body": "oh wait you're doing it wrong. use `answer.time - request.sent_time` and it will be much more accurate"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-17T16:31:42.207",
"Id": "496912",
"Score": "0",
"body": "@Cukic0d Oh, cool, thanks. I had no idea it provided that information. I wouldn't have guessed that it would mutate `request` with the time. Thanks. That definitely helps."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-17T17:38:51.720",
"Id": "496924",
"Score": "0",
"body": "@Cukic0d You were right. The timings now roughly match what `tracert` reports. Thanks again."
}
] |
[
{
"body": "<pre><code>if resolve_hostname:\n host = reverse_dns_lookup(best_route, get_gateway_of(best_route), **sr_kwargs)\n if isinstance(host, str):\n _cell_print(f"{host} [{best_route}]")\n else:\n _cell_print(best_route)\nelse:\n _cell_print(best_route)\n</code></pre>\n<p>You are doing <code>_cell_print</code> and using <code>best_route</code> in each case, which is also the default value. It might be motivated to use a different structure here, such as</p>\n<pre><code>output = best_route #default value\nif resolve_hostname:\n host = reversee_dns_lookup(best_route, get_gateway_of(best_route), **sr_kwargs)\n if isinstance(host, str):\n output = f"{host} [{best_route}]"\n\n_cell_print(output)\n\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T13:31:54.443",
"Id": "490245",
"Score": "0",
"body": "Thanks, I had a thinking freeze while trying to figure out a better way to write that."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T10:58:32.337",
"Id": "249953",
"ParentId": "249905",
"Score": "3"
}
},
{
"body": "<p>Thanks to @Cukic0d's suggestion, the timing can be easily improved by making use of the <code>.time</code> and <code>.sent_time</code> attributes of the packets.</p>\n<p>I removed <code>_time_exec</code>, and rejigged the <code>for</code> loop to be just:</p>\n<pre><code>for _ in range(n_tests):\n reply = sr1(packet, **sr_kwargs)\n if reply is None:\n _cell_print(NO_INFO_SYM)\n else:\n _cell_print(f"{int((reply.time - packet.sent_time) * 1000)} ms")\n replies.append(reply)\n</code></pre>\n<p>The timings now roughly match that of <code>tracert</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-17T17:38:20.443",
"Id": "252260",
"ParentId": "249905",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249953",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T00:38:46.253",
"Id": "249905",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"networking"
],
"Title": "Simplified Windows' tracert command"
}
|
249905
|
<p>My experience is more general architecture and software design not code snippets like this. See any improvement to my code?</p>
<pre><code>var message = @"This is a test message
012345678901234567890123";
var output = Split(message, 20);
</code></pre>
<p>output</p>
<pre><code>"This is a test",
"message",
"01234567890123456789",
"0123"
</code></pre>
<p>Max length of a line is 20 chars and it does not split words if not needed</p>
<p>code:</p>
<pre><code>private IEnumerable<string> Split(string text, int maxLength)
{
var n = '\n';
var whiteSpaces = new HashSet<char> { ' ', '\t', n };
text = text.Replace(Environment.NewLine, n.ToString());
if (!text.EndsWith(n)) text += n;
var whiteSpaceIndices = text
.Select((c, i) => (i, c))
.Where(t => whiteSpaces.Contains(t.c))
.ToList();
var index = 0;
var line = string.Empty;
char? last = null;
foreach (var white in whiteSpaceIndices)
{
do
{
var wordLength = white.i - index;
var wordTrimmed = text.Substring(index, Math.Min(maxLength, wordLength));
var wordWasTrimmed = wordLength > maxLength;
var trimmedTotalLength = wordTrimmed.Length + (wordWasTrimmed ? 0 : 1);
if (line.Length + trimmedTotalLength > maxLength || last == n)
{
if (line != string.Empty)
yield return line;
last = null;
line = string.Empty;
}
line += last;
line += wordTrimmed;
index += trimmedTotalLength;
} while (index < white.i);
last = white.c;
}
if (line != string.Empty)
yield return line;
}
</code></pre>
<p><a href="https://dotnetfiddle.net/gpT5UY" rel="noreferrer">https://dotnetfiddle.net/gpT5UY</a></p>
<p>Target framework is Core 3.1</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T11:58:29.843",
"Id": "490096",
"Score": "1",
"body": "Before I comment, what improvements are you hoping for, or rather what is you criticism of this logic. There are slightly simpler ways to achieve the same outcome but apart from some code comments this is not too bad. Also what environments are you expecting to execute this code and with what sort of frequency?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T13:16:01.543",
"Id": "490108",
"Score": "1",
"body": "I was looking for a more elegant way of solving the same thing basicly. It will be executed in azure service fabric, core 3.1 performance isn't super critical a few thousand calls to the method and the texts are not longer than 50 to 200 chars. It's a backend process"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T16:55:08.023",
"Id": "490161",
"Score": "0",
"body": "Could you please add the expected environment to the question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T17:19:22.757",
"Id": "490169",
"Score": "0",
"body": "Done target framework is Core 3.1"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T03:02:36.217",
"Id": "490196",
"Score": "0",
"body": "And you want to allow lines that have more than `maxLength` characters if there are no whitespace characters to split on? (so an individual word with more than `maxLength` characters) or should these _words_ be split and an optional hyphen or continuation character/string be injected?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T08:14:00.213",
"Id": "490208",
"Score": "0",
"body": "Yeah if the word is longer than maxLengh it needs to be split at maxLengh and continue on next"
}
] |
[
{
"body": "<p>I'm not sure if i can review this in details. But I suggest to consider my own implementation of the same.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>private static IEnumerable<string> Split(string text, int maxLength)\n{\n char[] whiteSpaces = new[] { ' ', '\\t' };\n string[] lines = text.Replace(Environment.NewLine, "\\n").Split('\\n');\n\n foreach (string line in lines)\n {\n int i = 0;\n string s = line;\n while (true)\n {\n s = s.Substring(i);\n string t = s.Trim();\n if (t.Length > maxLength)\n {\n int diff = s.Length - t.Length;\n i = t.LastIndexOfAny(whiteSpaces, maxLength);\n if (i < 0)\n i = maxLength;\n yield return t.Remove(i);\n i += diff;\n }\n else\n {\n yield return t;\n break;\n }\n }\n }\n}\n</code></pre>\n<p>Probably this code isn't absolutely accurate but it's ~5 times faster than original one.<br />\nI suggest you to test behavior and compare the performance.</p>\n<p>The main slow points in your code are <code>string</code> concatenation operations.</p>\n<hr />\n<p><strong>Edit:</strong> Ok, the encrypted version for <code>var</code> lovers.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>private static IEnumerable<string> Split(string text, int maxLength)\n{\n var whiteSpaces = new[] { ' ', '\\t' };\n var lines = text.Replace(Environment.NewLine, "\\n").Split('\\n');\n\n foreach (var line in lines)\n {\n var i = 0;\n var s = line;\n while (true)\n {\n s = s.Substring(i);\n var t = s.Trim();\n if (t.Length > maxLength)\n {\n var diff = s.Length - t.Length;\n i = t.LastIndexOfAny(whiteSpaces, maxLength);\n if (i < 0)\n i = maxLength;\n yield return t.Remove(i);\n i += diff;\n }\n else\n {\n yield return t;\n break;\n }\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T23:25:31.370",
"Id": "490289",
"Score": "2",
"body": "A good solution, I disagree on the `var` statements though. In cases where the type is immediately obvious to the reviewing developer, I will usually accept `var` in a code review, and for logic processing will usually prefer it. In that way the code is transferrable and resilient to other contexts and type changes. So if the variable is created only to make the code more readable (instead of inlining) then IMO `var` is superior"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T08:38:37.987",
"Id": "490317",
"Score": "0",
"body": "@ChrisSchaller ok, removed that from the answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T11:02:29.603",
"Id": "490325",
"Score": "1",
"body": "Looks good, full score if using var ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T12:51:45.520",
"Id": "490332",
"Score": "1",
"body": "@Anders fixed. :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T23:07:35.610",
"Id": "249974",
"ParentId": "249912",
"Score": "3"
}
},
{
"body": "<p>Overall this is not a bad technique, there is a code smell though in the number of string concatenations, I'm not going to profile it, but I prefer solutions in string processing that write to string variables as little as possible.</p>\n<p>What are you missing:</p>\n<ol>\n<li>There is no support or checking for null values</li>\n<li>There is no support or checking for a <code>maxLength</code> that is zero or less.</li>\n</ol>\n<p>This achieves the same outcome, but assigns less string variables along the way.</p>\n<pre><code>private IEnumerable<string> Split(string text, int maxLength)\n{\n if (String.IsNullOrWhiteSpace(text) || maxLength <= 0)\n yield return text;\n else\n {\n var whiteSpaces = new char[] { ' ', '\\t', '\\n' };\n text = text.Replace(Environment.NewLine, "\\n");\n\n int index = 0;\n int totalLength = text.Length;\n string max = "";\n do\n {\n // skip any whitespaces, handles case or multiple consecutive whitespaces\n for (; index < totalLength; index++)\n {\n if (!whiteSpaces.Contains(text[index]))\n break;\n }\n\n if (index + maxLength < totalLength)\n max = text.Substring(index, maxLength);\n else\n max = text.Substring(index);\n\n int maxBreak = max.LastIndexOfAny(whiteSpaces);\n if (maxBreak > 0)\n {\n yield return text.Substring(index, maxBreak);\n index += maxBreak;\n }\n else\n {\n yield return max;\n index += maxLength;\n }\n\n } while (index < totalLength);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T10:47:40.560",
"Id": "490324",
"Score": "0",
"body": "Thanks for taking time to answer. It does not work exactly the same though. For example it forgets the original new lines :P"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T00:46:12.333",
"Id": "490368",
"Score": "0",
"body": "@Anders fair enough, I was not aware that was a requirement, in fact you can see I deliberately remove the extra lines"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T23:31:53.747",
"Id": "249975",
"ParentId": "249912",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249974",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T09:08:25.053",
"Id": "249912",
"Score": "7",
"Tags": [
"c#"
],
"Title": "String line limiter"
}
|
249912
|
<p>The idea is to represent a hand as a list of cards and create a frequency mapping, which can then be used to identify what rank of hand you have and arrange your hand in a way that allows the Ord type class to compare hands of the same rank.</p>
<p>My solution feels a little cumbersome, however this is a lot nicer than anything I could have written imperatively, as poker hand evaluation is a little awkward in general.</p>
<p>card.hs</p>
<pre><code>module Card
(Card(..), Suit(..), Rank(..), rankVal) where
data Card = Card Suit Rank
data Suit =
Spades
| Hearts
| Clubs
| Diamonds
deriving (Show, Eq, Enum, Bounded)
data Rank =
Two
| Three
| Four
| Five
| Six
| Seven
| Eight
| Nine
| Ten
| Jack
| Queen
| King
| Ace
deriving (Show, Eq, Ord, Enum, Bounded)
instance Eq Card where
Card _ rank1 == Card _ rank2 = rank1 == rank2
instance Ord Card where
Card _ rank1 `compare` Card _ rank2 = rank1 `compare` rank2
instance Show Card where
show (Card suit rank) = "(" ++ (show suit) ++ ", " ++ (show rank) ++ ")"
rankVal :: Rank -> Int
rankVal Two = 2
rankVal Three = 3
rankVal Four = 4
rankVal Five = 5
rankVal Six = 6
rankVal Seven = 7
rankVal Eight = 8
rankVal Nine = 9
rankVal Ten = 10
rankVal Jack = 10
rankVal Queen = 10
rankVal King = 10
rankVal Ace = 11
</code></pre>
<p>solver.hs</p>
<pre><code>module Hand
(Card(..), Suit(..), Rank(..), compareHands) where
import Card
import Data.List
--TODO Add tests for every function
type Hand = [Card]
-- Cards arranged such that `compare` will return which hand is better
type RelativeRank = [Card]
-- A mapping between an element in a list and it's frequency
-- For example, [1, 2, 2, 2, 2] is [(1,1),(2,4),(2,4),(2,4),(2,4)]
type FreqMapping a = [(a, Int)]
data HandRank =
HighCard
| Pair
| TwoPairs
| ThreeOfKind
| Straight
| Flush
| FullHouse
| FourOfKind
| StraightFlush
| RoyalFlush
deriving (Show, Eq, Ord, Enum, Bounded)
compareHands :: Hand -> Hand -> Ordering
compareHands hand1 hand2 = (handRank1, relativeRank1) `compare` (handRank2, relativeRank2)
where relativeRank1 = computeRelativeRank hand1 handRank1
relativeRank2 = computeRelativeRank hand2 handRank2
handRank1 = computeHandRank hand1
handRank2 = computeHandRank hand2
maxVal :: Hand -> Int
maxVal = foldr (\(Card _ rank) acc -> max acc $ rankVal rank) 0
isStraight :: Hand -> Bool
isStraight = isStraightHelper . sort
isStraightHelper :: Hand -> Bool
isStraightHelper [] = True
isStraightHelper [x] = True
isStraightHelper (card1:card2:xs) = isValidStep && isStraightHelper (card2:xs)
where isValidStep = 1 + rankVal rank1 == rankVal rank2
(Card _ rank1) = card1
(Card _ rank2) = card2
isFlush :: Hand -> Bool
isFlush (x:xs) = (replicate len $ suit x) == (map suit (x:xs))
where suit = (\(Card suit _) -> suit)
len = length (x:xs)
computeHandRank :: Hand -> HandRank
computeHandRank xs
| flush && straight && maxVal xs == 12 = RoyalFlush
| flush && straight = StraightFlush
| freqList == [1, 4, 4, 4, 4] = FourOfKind
| freqList == [2, 2, 3, 3, 3] = FullHouse
| flush = Flush
| straight = Straight
| freqList == [1, 1, 3, 3, 3] = ThreeOfKind
| freqList == [1, 2, 2, 2, 2] = TwoPairs
| freqList == [1, 1, 1, 2, 2] = Pair
| otherwise = HighCard
where straight = isStraight xs
flush = isFlush xs
freqList = sort $ map snd $ computeFreqMapping xs
-- Used to compare hands of the same rank
computeRelativeRank :: Hand -> HandRank -> RelativeRank
computeRelativeRank xs handRank
| handRank == RoyalFlush = []
| handRank == StraightFlush = revSort xs
| handRank == FourOfKind = valsAtFreq 4 freqs ++ valsAtFreq 1 freqs
| handRank == FullHouse = valsAtFreq 3 freqs ++ valsAtFreq 2 freqs
| handRank == Flush = revSort xs
| handRank == Straight = revSort xs
| handRank == ThreeOfKind = valsAtFreq 3 freqs ++ (revSort $ valsAtFreq 1 freqs)
| handRank == TwoPairs = (maximum $ valsAtFreq 2 freqs) : (minimum $ valsAtFreq 2 freqs) : (valsAtFreq 1 freqs)
| handRank == Pair = valsAtFreq 2 freqs ++ (revSort $ valsAtFreq 1 freqs)
| handRank == HighCard = revSort xs
where freqs = computeFreqMapping xs
computeFreqMapping :: (Eq a) => [a] -> FreqMapping a
computeFreqMapping xs = map (\elem -> (elem, elemCount elem xs)) xs
-- Return number of times an element appears in a list
elemCount :: (Eq a) => a -> [a] -> Int
elemCount elem = length . filter (elem==)
--Return set of all values that appear at a given frequency in the freqency mapping
valsAtFreq :: (Ord a) => Int -> FreqMapping a -> [a]
valsAtFreq freq xs = [fst x | x <- xs, snd x == freq]
revSort :: (Ord a) => [a] -> [a]
revSort = reverse . sort
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>Just a few ideas - successfully compiled, not tested further.</p>\n<p>Using record syntax yields the functions <code>suit</code>, <code>rank</code> for "free", i.e.</p>\n<pre class=\"lang-hs prettyprint-override\"><code>data Card = Card { suit :: Suit\n , rank :: Rank }\n</code></pre>\n<p>allows for shorter definitions:</p>\n<pre class=\"lang-hs prettyprint-override\"><code>instance Eq Card where \n c1 == c2 = rank c1 == rank c2\n\ninstance Ord Card where \n c1 `compare` c2 = rank c1 `compare` rank c2\n</code></pre>\n<p>Similarly the following three functions become clearer.</p>\n<pre><code>maxVal :: Hand -> Int\nmaxVal = maximum . map (rankVal . rank)\n\nisStraight :: Hand -> Bool\nisStraight hand = [head sortedRanks .. last sortedRanks] == sortedRanks\n where sortedRanks = sort . map rank $ hand\n\nisFlush :: Hand -> Bool\nisFlush = (1==) . length . nub . map suit\n</code></pre>\n<p>To me <code>computeRelativeRank</code> calls for a <code>case expression</code>.</p>\n<pre><code>computeRelativeRank :: Hand -> HandRank -> RelativeRank\ncomputeRelativeRank xs handRank = case handRank of\n RoyalFlush -> []\n StraightFlush -> revSort xs\n FourOfKind -> valsAtFreq 4 freqs ++ valsAtFreq 1 freqs\n FullHouse -> valsAtFreq 3 freqs ++ valsAtFreq 2 freqs\n Flush -> revSort xs\n Straight -> revSort xs\n ThreeOfKind -> valsAtFreq 3 freqs ++ (revSort $ valsAtFreq 1 freqs)\n TwoPairs -> (maximum $ valsAtFreq 2 freqs) : (minimum $ valsAtFreq 2 freqs) : (valsAtFreq 1 freqs)\n Pair -> valsAtFreq 2 freqs ++ (revSort $ valsAtFreq 1 freqs)\n HighCard -> revSort xs\n where freqs = computeFreqMapping xs \n</code></pre>\n<p>I'd count the number of elements using a <code>Map</code>.</p>\n<pre><code>import qualified Data.Map.Strict as M\n\ncomputeFreqMapping :: (Ord a) => [a] -> FreqMapping a\ncomputeFreqMapping = M.toList . foldl incrementCounter M.empty\n where incrementCounter m k = M.insertWith (+) k 1 m\n</code></pre>\n<p>In fact, the whole frequency mapping could be handled using such maps - sorting is automatic that way. If you are so inclined, take a look at the <a href=\"https://hackage.haskell.org/package/containers-0.4.0.0/docs/Data-Map.html\" rel=\"nofollow noreferrer\">documentation</a> - particularly the functions <code>keys</code>, <code>elems</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T13:54:06.370",
"Id": "249920",
"ParentId": "249913",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249920",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T09:46:41.623",
"Id": "249913",
"Score": "1",
"Tags": [
"beginner",
"haskell",
"functional-programming"
],
"Title": "Poker Hand Evaluator in Haskell"
}
|
249913
|
<pre><code> using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
namespace WebApplication1.App_Code
{
public class SqlHelper
{
public string connstring;
public SqlConnection con;
public SqlCommand cmd;
public SqlHelper(){}
public SqlHelper(string sp)
{
connstring = ConfigurationManager.AppSettings["constr"];
con = new SqlConnection(connstring);
cmd = new SqlCommand(sp, con);
cmd.CommandType = CommandType.StoredProcedure;
}
}
public class Result : SqlHelper
{
public Result(string sp) : base(sp)
{
}
public bool ExecuteResultWithParameter(Dictionary<string, string> parameter)
{
bool result = true;
try
{
foreach (var item in parameter)
{
cmd.Parameters.AddWithValue("@" + item.Key, item.Value);
}
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception Ex)
{
result = false;
}
finally
{
cmd.Dispose();
con.Close();
con.Dispose();
}
return result;
}
public DataSet ReturnResultWithParameter(string sp, Dictionary<string, string> parameter)
{
DataSet dt = new DataSet();
try
{
foreach (var item in parameter)
{
cmd.Parameters.AddWithValue("@" + item.Key, item.Value);
}
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(dt);
}
}
catch (Exception Ex)
{
}
finally
{
cmd.Dispose();
con.Close();
con.Dispose();
}
return dt;
}
public DataSet ReturnResultWithoutParameter()
{
DataSet dt = new DataSet();
try
{
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(dt);
}
}
catch (Exception Ex)
{
}
finally
{
cmd.Dispose();
con.Close();
con.Dispose();
}
return dt;
}
}
}
</code></pre>
<p>I have written SQL helper class for my project and I want to improve the above code.also can someone suggest a suitable design pattern for the same.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T18:38:55.703",
"Id": "490177",
"Score": "1",
"body": "Use [Dapper](https://dapper-tutorial.net/) instead of writing your own ORM."
}
] |
[
{
"body": "<p>Don't use public fields. Instead, make them public properties.</p>\n<p>Use proper naming.<br />\nWhat is <code>sp</code>? <code>storedProcedureName</code> will be better.</p>\n<p><code>Dictionary</code> is a collection of parameters. Therefore, use the plural name: <code>parameters</code>.</p>\n<p>Using the <code>AddWithValue</code> method may result in poor query performance. Use the <code>Add</code> method with the exact <code>SqlDbType</code> type specified.</p>\n<p>The <code>ExecuteNonQuery</code> method returns the number of rows affected. Therefore, your <code>ExecuteResultWithParameter</code> method should return this value.<br />\nYou can get rid of the <code>bool result</code> variable. The failure of the method should be signaled by an exception that is re-thrown in the catch block: <code>throw ex;</code> (please note: the name starts with a small letter).</p>\n<p>The <code>ReturnResultWithParameter</code> method has an unused <code>sp</code> parameter. Remove it.</p>\n<p>You swallow exceptions with empty <code>catch</code> blocks. Therefore, there is no way to find out about query errors.</p>\n<p>In all methods, you dispose of the connection and the command in the <code>finally</code> blocks. After that, the methods cannot be called again without re-instantiating the class.</p>\n<p>There are extra empty lines in your code - this is also an error.</p>\n<p>Many of the errors I described will catch Visual Studio extensions like FxCop, StyleCop, and others. They will not only find them, but also suggest ways to fix them. Start using these extensions.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T00:05:52.680",
"Id": "249977",
"ParentId": "249916",
"Score": "3"
}
},
{
"body": "<p>Try to abstract away from helper name, when class is properly named - the whole picture become clear.</p>\n<p>Low level <code>helper</code> logic shouldn't be visible, instead we just need such usage</p>\n<pre><code>using (var connection = GetConnection())\n{\n connection.Execute("procedureName", new {A = "A", B = "B" });\n connection.CommitChanges();\n}\n</code></pre>\n<p>Parameters passing is the feature of language,</p>\n<pre><code> public abstract void Execute(string sp, params object[] parameters);\n</code></pre>\n<p><code>Execute</code> method will use converter inside, like</p>\n<pre><code> public IDictionary<string, object> GetObjectValues(object obj)\n {\n IDictionary<string, object> result = new Dictionary<string, object>();\n if (obj == null)\n {\n return result;\n }\n\n foreach (var propertyInfo in obj.GetType().GetProperties())\n {\n string name = propertyInfo.Name;\n object value = propertyInfo.GetValue(obj, null);\n result[name] = value;\n }\n\n return result;\n }\n</code></pre>\n<p>Inherit from IDisposable, move the contents of <code>finally</code> blocks into Dispose() method implementation.</p>\n<p>Check Dapper.</p>\n<p><a href=\"https://solrevdev.com/2011/04/10/dapper-dot-net-simple-sql-object-mapper.html\" rel=\"nofollow noreferrer\">https://solrevdev.com/2011/04/10/dapper-dot-net-simple-sql-object-mapper.html</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T09:42:26.137",
"Id": "249989",
"ParentId": "249916",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T12:42:20.310",
"Id": "249916",
"Score": "2",
"Tags": [
"c#",
"object-oriented"
],
"Title": "created a sql helper class using c#"
}
|
249916
|
<p>I've started Go for the last couple of months and I decided to challenging small projects, so I created this proxy requests script.</p>
<p>It works well (in my opinion at least) but I'm looking for different ways of improving this further like being able to target all servers, or making this more concise and compact. To be honest I think it is readable but again that's my opinion. I'm looking for it to be peer reviewed with no holds barred critism of my code. Why? to learn new ways of improving my coding techniques and making it much more efficient.</p>
<p>If anyone wants to view the code feel free:</p>
<pre><code>package main
import (
"context"
"fmt"
"math/rand"
"time"
)
type frame struct {
context.Context
resp chan<- string
}
type frames chan frame
func main() {
var serverConns []frames
const totalServers = 10
for i := 0; i < 10; i++ {
serverID := i
conn := make(frames)
defer close(conn)
serverConns = append(serverConns, conn)
go func() {
// the server
for frame := range conn {
resps := []string{"banana", "apple", "guava"}
time.Sleep(50*time.Millisecond + time.Duration(rand.Intn(500))*time.Millisecond)
r := fmt.Sprint("server ", serverID, ": ", resps[rand.Intn(len(resps))])
select {
case <-frame.Done():
case frame.resp <- r:
}
}
}()
}
// the proxy
const maxFanout = 3
var conns []frames
connIDs := rand.Perm(len(serverConns))[:totalServers/2]
for _, connID := range connIDs {
fmt.Println("selected server:", connID)
conns = append(conns, serverConns[connID])
}
fanoutConn := make(frames)
go func() {
for p := range fanoutConn {
ctx, cancel := context.WithCancel(p.Context)
firstResp := make(chan string)
for _, serverConn := range conns {
serverConn := serverConn
fwdframe := frame{
Context: ctx,
resp: firstResp,
}
go func() {
serverConn <- fwdframe
}()
}
response := <-firstResp
cancel()
p.resp <- response
}
}()
// the client
for {
r := make(chan string)
p := frame{
Context: context.Background(),
resp: r,
}
fanoutConn <- p
fmt.Println(<-r)
}
}
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n<p>I'm looking for it to be peer reviewed with no holds barred critism of\nmy code. Why? to learn new ways of improving my coding techniques and\nmaking it much more efficient. <a href=\"https://codereview.stackexchange.com/users/231106/judas-is-back\">Judas Is Back</a></p>\n</blockquote>\n<hr />\n<p>The evaluation criteria for a code review:</p>\n<p>Code should be correct, maintainable, robust, reasonably efficient, and, most importantly, readable. Code should be useful and have real value.</p>\n<hr />\n<p>I tried to read your <a href=\"https://play.golang.org/p/ixzAn6JgEDL\" rel=\"nofollow noreferrer\">code</a>. I found it to be an unreadable, sprawling, blob of code. Sorry!</p>\n<p>The first step is to give the code some structure. For example,</p>\n<blockquote>\n<p>On the Criteria To Be Used in Decomposing Systems into Modules, D.L.\nParnas, Carnegie-Mellon University, Communications of the ACM, December\n1972, Volume 15, Number 12.</p>\n</blockquote>\n<p>Parnas quotes Gouthier and Pont:</p>\n<blockquote>\n<p>A well-defined segmentation of the project effort ensures system\nmodularity. Each task forms a separate, distinct program module. At\nimplementation time each module and its inputs and outputs are\nwell-defined, there is no confusion in the intended interface with\nother system modules. At checkout time the in- tegrity of the module\nis tested independently; there are few sche- duling problems in\nsynchronizing the completion of several tasks before checkout can\nbegin. Finally, the system is maintained in modular fashion; system\nerrors and deficiencies can be traced to specific system modules, thus\nlimiting the scope of detailed error searching.</p>\n</blockquote>\n<hr />\n<p>After spending ten minutes on basic cleanup, this is what I have:</p>\n<p>Playground: <a href=\"https://play.golang.org/p/tsPqSe0urdv\" rel=\"nofollow noreferrer\">https://play.golang.org/p/tsPqSe0urdv</a></p>\n<p>The <code>main</code> function summarizes the program.</p>\n<pre><code>func main() {\n // the servers\n serverConns := servers()\n // the proxies\n fanoutConn := proxies(serverConns)\n // the client\n client(fanoutConn)\n}\n</code></pre>\n<p>The <code>server</code> and <code>servers</code> functions encapsulate the server related processing, promoting information hiding. I did a lot of basic cleanup.</p>\n<pre><code>// the server\nfunc server(id int, conn frames) {\n defer close(conn)\n\n server := fmt.Sprint("server ", id, ": ")\n resps := []string{"banana", "apple", "guava"}\n\n for frame := range conn {\n time.Sleep(time.Duration(50+rand.Intn(500)) * time.Millisecond)\n\n resp := server + resps[rand.Intn(len(resps))]\n\n select {\n case <-frame.Done():\n case frame.resp <- resp:\n }\n }\n}\n\n// the servers\nfunc servers() []frames {\n const totalServers = 10\n serverConns := make([]frames, totalServers)\n for id := range serverConns {\n conn := make(frames)\n serverConns[id] = conn\n go server(id, conn)\n }\n return serverConns\n}\n</code></pre>\n<p>There is more cleanup to be done on these and other functions.</p>\n<p>As the code gets more readable, we move closer to other code review goals like correctness and maintainability.</p>\n<p><code>proxy.go</code>:</p>\n<pre><code>package main\n\nimport (\n "context"\n "fmt"\n "math/rand"\n "time"\n)\n\ntype frame struct {\n context.Context\n resp chan<- string\n}\n\ntype frames chan frame\n\n// the server\nfunc server(id int, conn frames) {\n defer close(conn)\n\n server := fmt.Sprint("server ", id, ": ")\n resps := []string{"banana", "apple", "guava"}\n\n for frame := range conn {\n time.Sleep(time.Duration(50+rand.Intn(500)) * time.Millisecond)\n\n resp := server + resps[rand.Intn(len(resps))]\n\n select {\n case <-frame.Done():\n case frame.resp <- resp:\n }\n }\n}\n\n// the servers\nfunc servers() []frames {\n const totalServers = 10\n serverConns := make([]frames, totalServers)\n for id := range serverConns {\n conn := make(frames)\n serverConns[id] = conn\n go server(id, conn)\n }\n return serverConns\n}\n\n// the proxy\nfunc proxy(conns []frames, fanoutConn frames) {\n for p := range fanoutConn {\n ctx, cancel := context.WithCancel(p.Context)\n firstResp := make(chan string)\n for _, serverConn := range conns {\n serverConn := serverConn\n fwdframe := frame{\n Context: ctx,\n resp: firstResp,\n }\n go func() {\n serverConn <- fwdframe\n }()\n }\n response := <-firstResp\n cancel()\n p.resp <- response\n }\n}\n\n// the proxies\nfunc proxies(serverConns []frames) frames {\n connIDs := rand.Perm(len(serverConns))[:len(serverConns)/2]\n var conns []frames = make([]frames, 0, len(connIDs))\n for _, connID := range connIDs {\n fmt.Println("selected server:", connID)\n conns = append(conns, serverConns[connID])\n }\n fanoutConn := make(frames)\n go proxy(conns, fanoutConn)\n return fanoutConn\n}\n\n// the client\nfunc client(fanoutConn frames) {\n for {\n resp := make(chan string)\n p := frame{\n Context: context.Background(),\n resp: resp,\n }\n fanoutConn <- p\n fmt.Println(<-resp)\n }\n}\n\nfunc main() {\n // the servers\n serverConns := servers()\n // the proxies\n fanoutConn := proxies(serverConns)\n // the client\n client(fanoutConn)\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T15:02:26.030",
"Id": "249962",
"ParentId": "249917",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T13:24:45.240",
"Id": "249917",
"Score": "3",
"Tags": [
"go"
],
"Title": "Coded a Go Script that Sends proxy requests to backend servers"
}
|
249917
|
<p>I have solved the following Leetcode problem.</p>
<blockquote>
<p>Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). For example, this binary tree [1,2,2,3,4,4,3] is symmetric.</p>
</blockquote>
<p>Link: <a href="https://leetcode.com/problems/symmetric-tree/" rel="nofollow noreferrer">https://leetcode.com/problems/symmetric-tree/</a></p>
<p>I have made a simple iterative solution that takes <span class="math-container">\$O(n)\$</span> time and <span class="math-container">\$O(n)\$</span> space since we have to parse through each node, which is initialized as a class and each class contains the node's values, and pointers to the left and right child of the node. We compare if the node values at each level form a palindromic list (we store all the node values in a running list) or not. Here <span class="math-container">\$n\$</span> denotes the number of nodes in the tree. I have assumed the binary tree is complete and any missing node is initialized with a <code>NONE</code> variable. The code terminates when I have reached a level in the tree where each node is a <code>NONE</code>, meaning nothing has to be analyzed at this level, and if an error isn't found in one of the previous nodes (an error is raised when the nodes at each level don't form a palindromic list), we return True.</p>
<p>The code takes a whopping 1500 ms to run on Leetcode and uses around 150 MB of storage! I think about ~200 test cases are run in the background. Running the code on a single tree (of different sizes) makes the code run in about ~30-40ms.</p>
<p>Should I be concerned? Are the other significant ways to optimize the code/approach? I think even if the approach is correct, the implementation may be throwing off the time, and I'm not the most savvy coder. I'm new to learning algorithms and their implementation as well, so I'd appreciate some feedback.</p>
<p><strong>Edit:</strong></p>
<p>Here's my analysis of the run time of the algorithm. Assume the tree is a complete binary tree since each missing node can be thought of a node with a <code>NONE</code> class associated to it. Assume the tree has <span class="math-container">\$k\$</span> (starting from level 0) levels and a total of <span class="math-container">\$n = 2^{k+1} - 1\$</span> nodes. For example, the tree <code>[1|2,2|3,4,4,3]</code>, where a <code>|</code> indicates a level has changed, has <span class="math-container">\$2\$</span> levels with <span class="math-container">\$ 2^{3} - 1 = 7 \$</span> nodes.</p>
<p>The outer while loop terminates when we check the condition of the while loop when we have reached level <span class="math-container">\$k + 1\$</span> where this level can be thought as being comprised of all <code>NONE</code> nodes, meaning the tree doesn't extend till this level. So it runs only when the running variable <span class="math-container">\$l\$</span> ranges from <span class="math-container">\$0\$</span> to <span class="math-container">\$k\$</span>, or a total of <span class="math-container">\$k + 1\$</span> times which is <span class="math-container">\$\Theta ( \lg (n+1)) = \Theta ( \lg n)\$</span>, where <span class="math-container">\$\lg\$</span> is log base 2. In the while loop, we have that for each value of <span class="math-container">\$l\$</span>, the first for loop runs for a total of <span class="math-container">\$2^{l}\$</span> times since each level has (at most) <span class="math-container">\$2^{l}\$</span> nodes. The additional for loop runs for only <span class="math-container">\$2\$</span> times so all in all, for each value of <span class="math-container">\$l\$</span> there are <span class="math-container">\$O(2^{l})\$</span> iterations. All other operations take constant time, so the running cost of the algorithm is,</p>
<p><span class="math-container">$$
\begin{align}
O\big(\sum_{l = 0}^{k + 1} 2^{l} \big) &= O\big(\sum_{l = 0}^{\Theta (\lg n)} 2^{l} \big) \\
&= O\big(2^{\Theta (\lg n) + 1 } - 1 \big ) \\
&= O\big(2^{\Theta (\lg n) + 1 } \big) \\
&= O\big(2^{\Theta (\lg n) } \big) \\
&= \Theta (n) \\
&= O(n)
\end{align}
$$</span></p>
<pre><code>def isSymmetric(root):
if root == None:
return True
else:
t = [root]
l = 0
d = {None:-1}
while d[None] < 2**l:
d[None] = 0
n = []
v = []
for node in t:
if node == None:
d[None] = d[None] + 2
v.append(None)
v.append(None)
n.append(None)
n.append(None)
else:
for child in [node.left,node.right]:
n.append(child)
if child == None:
d[None] = d[None] + 1
v.append(None)
else:
v.append(child.val)
l = l + 1
if d[None] == 2**l:
return True
else:
a = v[0:2**(l-1)]
b = v[2**(l-1):2**l]
b.reverse()
if a != b:
return False
t = n
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T01:44:58.327",
"Id": "490195",
"Score": "0",
"body": "Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/113460/discussion-on-question-by-user82261-check-if-a-binary-tree-is-symmetric-in-pytho)."
}
] |
[
{
"body": "<p>It would also be easier if we follow TDD - <a href=\"https://en.wikipedia.org/wiki/Test-driven_development\" rel=\"nofollow noreferrer\">Test Driven Development</a>.</p>\n<ol>\n<li><p>We build the boiler plate that LeetCode is building for you.</p>\n<pre class=\"lang-py prettyprint-override\"><code>from __future__ import annotations\n\nimport dataclasses\nfrom typing import Any, Optional\n\n\n@dataclasses.dataclass\nclass Node:\n val: Any\n left: Optional[Node] = None\n right: Optional[Node] = None\n</code></pre>\n</li>\n<li><p>We get a tree with only one node working.\nFrom this we can expand on the tests and code to get more working.</p>\n<p>This is simple we just check if both left and right are None.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def is_symmetric(node):\n return node.left is None and node.right is None\n\n\nassert is_symmetric(Node(None))\n</code></pre>\n</li>\n<li><p>We get a tree with 3 nodes working.</p>\n<p>The simplest way to do this is to just check if left and right's value are the same <em>ignoring</em> if either are None.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def is_symmetric(node):\n return (\n (node.left is None and node.right is None)\n or (node.left.val == node.right.val)\n )\n\n\nassert is_symmetric(Node(None))\nassert is_symmetric(Node(None, Node(1), Node(1)))\nassert not is_symmetric(Node(None, Node(1), Node(2)))\n</code></pre>\n</li>\n<li><p>We get a tree of size 1, 2 and 3 working.</p>\n<p>This makes the code a little more complicated as we now have to handle <code>None</code> for both <code>left</code> and <code>right</code>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def is_symmetric(node):\n if node.left is None:\n return node.right is None\n if node.right is None:\n return False\n return node.left.val == node.right.val\n\n\nassert is_symmetric(Node(None))\nassert is_symmetric(Node(None, Node(1), Node(1)))\nassert not is_symmetric(Node(None, Node(1), Node(2)))\nassert not is_symmetric(Node(None, left=Node(1)))\nassert not is_symmetric(Node(None, right=Node(1)))\n</code></pre>\n</li>\n<li><p>To get a easier to understand stepping stone we can temporarally solve a different problem.\nRather than checking if it's a mirror arround the root we just check the mirror around each node.</p>\n<p><strong>Note</strong>: This is only to make this step easier to digest.</p>\n<p>Since we already have a function to check if a node is symmetric we can just call that to check if each of left and right are symmetric. This is called recursion.</p>\n<p>To return True the current <code>is_symmetric</code> needs to be true, and both the left and right have to be symmetric.</p>\n<p>To make the code a little easier to read we can:</p>\n<ol>\n<li>Move the current code into another function.</li>\n<li>Add a condition to return True if <code>node</code> is None.</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>def _is_symmetric(node):\n if node.left is None:\n return node.right is None\n if node.right is None:\n return False\n return node.left.val == node.right.val\n\n\ndef is_symmetric(node):\n if node is None:\n return True\n return _is_symmetric(node) and is_symmetric(node.left) and is_symmetric(node.right)\n\n\nassert is_symmetric(Node(None))\nassert is_symmetric(Node(None, Node(1), Node(1)))\nassert not is_symmetric(Node(None, Node(1), Node(2)))\nassert not is_symmetric(Node(None, left=Node(1)))\nassert not is_symmetric(Node(None, right=Node(1)))\n\nassert is_symmetric(None)\nassert is_symmetric(Node(\n None,\n Node(1, Node(2), Node(2)),\n Node(1, Node(3), Node(3)),\n))\nassert not is_symmetric(Node(\n None,\n Node(1, Node(2), Node(1)),\n Node(1, Node(3), Node(3)),\n))\n</code></pre>\n</li>\n<li><p>We can now go back to solving the original problem. By swapping two grand-child nodes we can change the above to work down the middle of the tree.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def _is_symmetric(node):\n if node.left is None:\n return node.right is None\n if node.right is None:\n return False\n return node.left.val == node.right.val\n\n\ndef is_symmetric(node):\n if node is None:\n return True\n if not _is_symmetric(node):\n return False\n if node.left is not None:\n (node.left.left, node.right.left) = (node.right.left, node.left.left)\n return is_symmetric(node.left) and is_symmetric(node.right)\n\n\nassert is_symmetric(Node(None))\nassert is_symmetric(Node(None, Node(1), Node(1)))\nassert not is_symmetric(Node(None, Node(1), Node(2)))\nassert not is_symmetric(Node(None, left=Node(1)))\nassert not is_symmetric(Node(None, right=Node(1)))\n\nassert is_symmetric(None)\nassert is_symmetric(Node(\n None,\n Node(1, Node(2), Node(3)),\n Node(1, Node(3), Node(2)),\n))\nassert not is_symmetric(Node(\n None,\n Node(1, Node(2), Node(3)),\n Node(1, Node(3), Node(1)),\n))\n</code></pre>\n</li>\n</ol>\n<p>This runs in <span class=\"math-container\">\\$O(n)\\$</span> time and <span class=\"math-container\">\\$O(d)\\$</span> space, where <span class=\"math-container\">\\$d\\$</span> is the depth of the tree. This is because we make <span class=\"math-container\">\\$d\\$</span> stack frames because we have used recursion. On a complete tree <span class=\"math-container\">\\$d\\$</span> is <span class=\"math-container\">\\$\\log n\\$</span> but can be as bad as <span class=\"math-container\">\\$n\\$</span> on a tree that is more line like.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T14:58:21.467",
"Id": "249922",
"ParentId": "249919",
"Score": "3"
}
},
{
"body": "<p>Your solution isn't <span class=\"math-container\">\\$O(n)\\$</span> but <span class=\"math-container\">\\$O(2^n)\\$</span>. Your assumption that the tree is complete and thus your analysis is incorrect. Already LeetCode's second example tree isn't complete. And consider this tree:</p>\n<p><a href=\"https://i.stack.imgur.com/PL8Ns.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/PL8Ns.png\" alt=\"enter image description here\" /></a></p>\n<p>That tree only has 25 nodes, but your solution creates <em>thousands</em> of <code>None</code>s for subtrees that aren't there. (That is, your actual code presumably does that, not the one that you posted here and refuse to fix.) If I made it ten levels deeper (45 nodes total), you'd create <em>millions</em> of <code>None</code>s.</p>\n<p>The above tree btw can be denoted at LeetCode by this:</p>\n<pre><code>[1,1,1,null,1,1,null,null,1,1,null,null,1,1,null,null,1,1,null,\n null,1,1,null,null,1,1,null,null,1,1,null,null,1,1,null,\n null,1,1,null,null,1,1,null,null,1,1,null]\n</code></pre>\n<p>Just another solution, in which I tuplify the tree and then compare it to a mirrored version of it. It's recursive, which for binary tree problems is often simpler:</p>\n<pre><code> def isSymmetric(self, root: TreeNode) -> bool:\n def t(r):\n return r and (r.val, t(r.left), t(r.right))\n def m(r):\n return r and (r[0], m(r[2]), m(r[1]))\n r = t(root)\n return r == m(r)\n</code></pre>\n<p>Got accepted in 16 ms. Note that the abbreviated function/variable names are bad in real life. But for a contest it can save time, so I kinda wanted to show that, as writing speed has been mentioned in comments elsewhere. Similarly, I waste space on a mirrored copy because that way I pretty much don't have to think, again saving writing time :-)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T17:04:14.947",
"Id": "490162",
"Score": "0",
"body": "Isn't this discrepancy because you have different definitions of \\$n\\$? The OP has defined \\$n\\$ to be a complete tree where you have defined \\$n\\$ to be the amount of nodes in the tree. It's not really nonsensical to have different definitions just as long as you're up-front about them which IIRC the OP was."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T17:06:14.390",
"Id": "490163",
"Score": "0",
"body": "@Peilonrayz Quote from their question: \"Here n denotes the number of nodes in the tree\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T17:06:39.100",
"Id": "490164",
"Score": "0",
"body": "\"I have assumed the binary tree is complete and any missing node is initialized with a NONE variable.\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T17:06:57.283",
"Id": "490165",
"Score": "0",
"body": "@Peilonrayz And it's nonsensical to assume that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T17:08:20.313",
"Id": "490166",
"Score": "3",
"body": "Certainly is abnormal, but not nonsensical as we can make sense of it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T17:23:09.423",
"Id": "490170",
"Score": "0",
"body": "Thank you for your suggestion. Yes, why initial approach/implementation only worked when the tree was complete. I didn't think it through I guess. I have now come up with a new solution that works around this detail, and I'm trying to implement it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T17:29:11.540",
"Id": "490171",
"Score": "0",
"body": "@Peilonrayz In my opinion it makes no sense to make such an assumption without having any reason for it. And already LeetCode's second example isn't even a complete tree, showing that it should *not* be assumed."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T16:50:05.127",
"Id": "249926",
"ParentId": "249919",
"Score": "4"
}
},
{
"body": "<p>Thank you for the suggestions everyone. I was able to figure out the lapse in my initial judgement, and I was able to think of a solution that works, and I was able to implement it as well (after some hiccups and minor modifications along the way). Here's what I got:</p>\n<pre><code>def isSymmetric(self,root):\n\n if root == None:\n\n return True \n \n else:\n \n t = [root]\n l = 0\n \n while len(t) > 0:\n \n l = l + 1\n v = []\n n = []\n \n for node in t:\n \n if node.left != None:\n \n n.append(node.left)\n v.append(node.left.val)\n \n else:\n \n v.append(None)\n \n \n if node.right != None:\n \n n.append(node.right)\n v.append(node.right.val)\n \n else:\n \n v.append(None) \n \n a = v[::-1]\n \n if a != v:\n\n return False\n \n t = n\n \n return True\n</code></pre>\n<p>It now runs in around 26ms, which is faster than 96.67% of submissions, but it still uses about 13 MB of storage, which is less than 5.09% of submissions. I can live with that since I'm probably not the slickest of coders, but I'll try and see if I can optimize and/or learn new ways for better implementation.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T17:40:47.983",
"Id": "249927",
"ParentId": "249919",
"Score": "1"
}
},
{
"body": "<p><strong>O(1) space, O(n) time</strong></p>\n<p>As kinda pointed out already, your lists of nodes/values of the current level are up to <span class=\"math-container\">\\$O(2^n)\\$</span> large. So your large memory usage of 150 MB is no wonder. It could easily be <em>much</em> more. LeetCode must have only very shallow trees (Yeah just checked, max height is only 22. Sigh). Here's somewhat the other extreme, taking only O(1) extra space. And it can handle any tree height, unlike recursive solutions which would at some point exceed the recursion limit and crash.</p>\n<p>I'm using Morris traversal for a preorder left-to-right traversal of the root's left subtree and a right-to-left one of the right subtree. I yield not just the node values but also the <code>None</code> references. That provides not just the values but also the structure of the two subtrees, so then I just need to compare the left traversal with the right traversal one by one.</p>\n<p>At LeetCode it still takes about 14.3 MB, as LeetCode doesn't isolate the solution's memory usage but includes the Python/judge overhead. I also took a solution from the memory distribution graph that had a very low memory usage (13628 kB) and resubmitted it. It took 14.3 MB now as well. So as with times, LeetCode isn't stable and accurate with memory, and the baseline (minimum) seems to be about 14.3 MB right now.</p>\n<pre><code>class Solution:\n def isSymmetric(self, root: TreeNode) -> bool:\n if not root:\n return True\n left = preorder_left_right(root.left)\n right = preorder_right_left(root.right)\n result = all(map(operator.eq, left, right))\n for _ in left: pass\n for _ in right: pass\n return result\n\ndef preorder_left_right(root):\n while root:\n if not root.left:\n yield root.val\n yield None\n root = root.right\n continue\n prev = root.left\n while prev.right and prev.right is not root:\n prev = prev.right\n if not prev.right:\n yield root.val\n prev.right = root\n root = root.left\n else:\n yield None\n prev.right = None\n root = root.right\n yield None\n \ndef preorder_right_left(root):\n while root:\n if not root.right:\n yield root.val\n yield None\n root = root.left\n continue\n prev = root.right\n while prev.left and prev.left is not root:\n prev = prev.left\n if not prev.left:\n yield root.val\n prev.left = root\n root = root.right\n else:\n yield None\n prev.left = None\n root = root.left\n yield None\n</code></pre>\n<p>Draining <code>left</code> and <code>right</code> isn't necessary at LeetCode to get accepted, <code>return all(map(operator.eq, left, right))</code> works there as well. But I do it to finish the Morris traversals and thus restore the trees to their original states.</p>\n<p>I considered replacing the two traversal functions with one that takes functions <code>kid1</code>, <code>kid2</code> and <code>setkid2</code> (getting/setting the left or right kid of a node) to remove the code duplication, but I think it's clearer the way it is. Edit: Oh well, actually did it now:</p>\n<pre><code>class Solution:\n def isSymmetric(self, root: TreeNode) -> bool:\n if not root:\n return True\n left = preorder(root.left, leftkid, rightkid, setright)\n right = preorder(root.right, rightkid, leftkid, setleft)\n result = all(map(operator.eq, left, right))\n for _ in left: pass\n for _ in right: pass\n return result\n\ndef leftkid(node):\n return node.left\ndef rightkid(node):\n return node.right\ndef setleft(node, kid):\n node.left = kid\ndef setright(node, kid):\n node.right = kid\n\ndef preorder(root, kid1, kid2, setkid2):\n while root:\n if not kid1(root):\n yield root.val\n yield None\n root = kid2(root)\n continue\n prev = kid1(root)\n while kid2(prev) and kid2(prev) is not root:\n prev = kid2(prev)\n if not kid2(prev):\n yield root.val\n setkid2(prev, root)\n root = kid1(root)\n else:\n yield None\n setkid2(prev, None)\n root = kid2(root)\n yield None\n</code></pre>\n<p>Yet another version, using <code>getattr</code> and <code>setattr</code>, inspired by <a href=\"https://leetcode.com/problems/symmetric-tree/discuss/752079/Python-O(1)-space-solution\" rel=\"nofollow noreferrer\">this attempt</a>:</p>\n<pre><code>class Solution:\n def isSymmetric(self, root: TreeNode) -> bool:\n if not root:\n return True\n left = preorder(root.left, 'left', 'right')\n right = preorder(root.right, 'right', 'left')\n result = all(map(operator.eq, left, right))\n for _ in left: pass\n for _ in right: pass\n return result\n\ndef preorder(root, kid1, kid2):\n get, set = getattr, setattr\n while root:\n if not get(root, kid1):\n yield root.val\n yield None\n root = get(root, kid2)\n continue\n prev = get(root, kid1)\n while get(prev, kid2) and get(prev, kid2) is not root:\n prev = get(prev, kid2)\n if not get(prev, kid2):\n yield root.val\n set(prev, kid2, root)\n root = get(root, kid1)\n else:\n yield None\n set(prev, kid2, None)\n root = get(root, kid2)\n yield None\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T00:08:09.213",
"Id": "249936",
"ParentId": "249919",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249926",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T13:49:39.397",
"Id": "249919",
"Score": "4",
"Tags": [
"python",
"programming-challenge",
"tree",
"palindrome"
],
"Title": "Check if a binary tree is symmetric in Python"
}
|
249919
|
<p>I made <strong>Password Generator</strong> on C#.
<br></p>
<p>It prompts the user for the <em>length of the password</em>, whether it <em>contains numbers</em>, <em>lowercase letters</em>, <em>uppercase letters</em> or <em>symbols</em>, and generates a strong password from randomly added numbers, letters, or symbols.</p>
<p>There's the code:</p>
<pre><code>using System;
namespace Password_Generator
{
class Program
{
static string Randomize(string Str)
{
Random Rand = new Random();
string Randomized = "";
while (Randomized.Length < Str.Length)
{
Randomized += Str[Rand.Next(0, Str.Length)];
}
return Randomized;
}
static void Main(string[] args)
{
while (true)
{
Console.ForegroundColor = ConsoleColor.White;
Console.Write("\nDo Yout Want a New Password [True], [False]? ");
Console.ForegroundColor = ConsoleColor.Yellow;
string NewPasswordStr = Console.ReadLine();
bool NewPassword;
while (bool.TryParse(NewPasswordStr, out NewPassword) == false)
{
Console.Clear();
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("The Given Output is Unconvertable Or it's Value is Unacceptable. Try Again!");
Console.ForegroundColor = ConsoleColor.White;
Console.Write("\nDo Yout Want a New Password [True], [False]? ");
Console.ForegroundColor = ConsoleColor.Yellow;
NewPasswordStr = Console.ReadLine();
Console.ForegroundColor = ConsoleColor.White;
}
Console.ForegroundColor = ConsoleColor.White;
if (NewPassword == true)
{
Console.Clear();
Console.Write("Password Length: ");
Console.ForegroundColor = ConsoleColor.Yellow;
string LenghtStr = Console.ReadLine();
int Lenght;
while (int.TryParse(LenghtStr, out Lenght) == false || int.Parse(LenghtStr) <= 0)
{
Console.Clear();
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("The Given Output is Unconvertable Or it's Value is Unacceptable. Try Again!");
Console.ForegroundColor = ConsoleColor.White;
Console.Write("\nPassword Length: ");
Console.ForegroundColor = ConsoleColor.Yellow;
LenghtStr = Console.ReadLine();
Console.ForegroundColor = ConsoleColor.White;
}
Console.ForegroundColor = ConsoleColor.White;
Console.Write("\n\nInclude Numbers (0 - 9) [True], [False]: ");
Console.ForegroundColor = ConsoleColor.Yellow;
string IncludeNumbersStr = Console.ReadLine();
bool IncludeNumbers;
while (bool.TryParse(IncludeNumbersStr, out IncludeNumbers) == false)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\nThe Given Output is Unconvertable. Try Again!");
Console.ForegroundColor = ConsoleColor.White;
Console.Write("\nInclude Numbers (0 - 9) [True], [False]: ");
Console.ForegroundColor = ConsoleColor.Yellow;
IncludeNumbersStr = Console.ReadLine();
Console.ForegroundColor = ConsoleColor.White;
}
Console.Write("\n\nInclude Lowercase Letters (a - z) [True], [False]: ");
Console.ForegroundColor = ConsoleColor.Yellow;
string IncludeLowercaseStr = Console.ReadLine();
bool IncludeLowercase;
while (bool.TryParse(IncludeLowercaseStr, out IncludeLowercase) == false)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\nThe Given Output is Unconvertable. Try Again!");
Console.ForegroundColor = ConsoleColor.White;
Console.Write("\nInclude Lowercase Letters (a - z) [True], [False]: ");
Console.ForegroundColor = ConsoleColor.Yellow;
IncludeLowercaseStr = Console.ReadLine();
Console.ForegroundColor = ConsoleColor.White;
}
Console.ForegroundColor = ConsoleColor.White;
Console.Write("\n\nInclude Uppercase Letters (A - Z) [True], [False]: ");
Console.ForegroundColor = ConsoleColor.Yellow;
string IncludeUppercaseStr = Console.ReadLine();
bool IncludeUppercase;
while (bool.TryParse(IncludeUppercaseStr, out IncludeUppercase) == false)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\nThe Given Output is Unconvertable. Try Again!");
Console.ForegroundColor = ConsoleColor.White;
Console.Write("\nInclude Uppercase Letters (A - X) [True], [False]: ");
Console.ForegroundColor = ConsoleColor.Yellow;
IncludeUppercaseStr = Console.ReadLine();
Console.ForegroundColor = ConsoleColor.White;
}
Console.ForegroundColor = ConsoleColor.White;
Console.Write("\n\nInclude Symbols [True], [False]: ");
Console.ForegroundColor = ConsoleColor.Yellow;
string IncludeSymbolsStr = Console.ReadLine();
bool IncludeSymbols;
while (bool.TryParse(IncludeSymbolsStr, out IncludeSymbols) == false)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\nThe Given Output is Unconvertable. Try Again!");
Console.ForegroundColor = ConsoleColor.White;
Console.Write("\nInclude Symbols [True], [False]: ");
Console.ForegroundColor = ConsoleColor.Yellow;
IncludeSymbolsStr = Console.ReadLine();
Console.ForegroundColor = ConsoleColor.White;
}
Console.ForegroundColor = ConsoleColor.White;
string Password = "";
while (Password.Length < Lenght)
{
Random Rand = new Random();
if (IncludeNumbers == true)
{
Password += ((char)Rand.Next(48, 58)).ToString();
}
if (Password.Length == Lenght)
{
break;
}
if (IncludeLowercase == true)
{
Password += ((char)Rand.Next(97, 123)).ToString();
}
if (Password.Length == Lenght)
{
break;
}
if (IncludeUppercase == true)
{
Password += ((char)Rand.Next(97, 123)).ToString().ToUpper();
}
if (Password.Length == Lenght)
{
break;
}
if (IncludeSymbols == true)
{
Password += ((char)Rand.Next(33, 48)).ToString().ToUpper();
}
if (Password.Length == Lenght)
{
break;
}
}
Password = Randomize(Password);
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.DarkGreen;
Console.WriteLine(Password);
Console.ForegroundColor = ConsoleColor.White;
}
else
{
Environment.Exit(-1);
}
}
}
}
}
</code></pre>
<p>Are <strong>221</strong> line too much for this? How to impove it? Is this a "crapcode"? How do not write crapcode?
....Thanks!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T07:49:44.137",
"Id": "525382",
"Score": "2",
"body": "Please roll back you change. If you want you python code reviewed ask a new question."
}
] |
[
{
"body": "<p>From <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.random?view=netcore-3.1#remarks\" rel=\"nofollow noreferrer\">MSDN Random class documentation</a></p>\n<blockquote>\n<p>To generate a cryptographically secure random number, such as one that's suitable for creating a random password, use the RNGCryptoServiceProvider class or derive a class from System.Security.Cryptography.RandomNumberGenerator.</p>\n</blockquote>\n<hr />\n<p><strong>Random Rand = new Random();</strong></p>\n<p><strong>Edit</strong>\nCorrection: Using a snapshot of the system clock, the no-parameter constructor ends up using different seed values; <em>unless</em> the Random objects are created so close in time that the same clock time is used. Given the same argument (parameter seed value), different Randoms generate the same random sequence.\n<strong>end Edit</strong></p>\n<p><strike>Every <code>Random</code> object created with the parameterless constructor will generate the same sequence of random numbers because the same "default seed" value is used every time. This is perfect for development and testing but not in production code. Reading the system time in milliseconds is a common way to generate different "seed" values for each constructor call.</p>\n<hr />\n<p><strong>crapcode</strike> Code Smell</strong></p>\n<p>The fuzzy doubts you have about the code is technically called a "code smell", meaning it looks suspicious for some reason - the length "feels" longish for what it is doing, in this case. There may be something wrong, maybe not; a "code smell" requires closer scrutinization to determine if anything is in fact wrong.</p>\n<p>A code smell I see is the multiple similar looking <code>while</code> loops, each looking for different required characters. I don't want to write hard to understand code for the sake of fewer lines. "Fewer lines of code" alone is not a reason to change things. Here is an idea, maybe it is an improvement or maybe not:</p>\n<p>Tell the user the required characters up front when prompting for the password.</p>\n<p>A string is iterable, you can "forEach". A <code>String</code> is in fact an array of <code>Char</code>, technically.</p>\n<pre><code>forEach (char character in enteredPassword) { ... }\n</code></pre>\n<p>Examine each character for its type. Keep a separate count for each character type.</p>\n<p>After the <code>forEach</code> test each counter for the required minimum. If <code>symbols</code> is zero, for example, append "at least one symbol character is required" to an error message.</p>\n<hr />\n<p><strong>FYI</strong></p>\n<p>There's an old saying with a core of truth: <a href=\"https://blog.codinghorror.com/regular-expressions-now-you-have-two-problems/\" rel=\"nofollow noreferrer\"><em>If you solve a problem with a regular expression, now you have two problems</em></a></p>\n<hr />\n<blockquote>\n<p>Are 221 line too much for this</p>\n</blockquote>\n<p>There are many guidelines, principles, "isms", etc. for evaluating code quality. The line count is not one of them.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T13:32:24.663",
"Id": "490246",
"Score": "1",
"body": "Your comments about the behaviour of the parameterless `Random` constructor are incorrect. On the full framework, it uses the system clock to get a seed. That means you can have trouble if you create 2 instances at the same time. The behaviour on .Net Core is different again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T20:59:19.000",
"Id": "490280",
"Score": "0",
"body": "OOps! corrected in answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T07:38:55.877",
"Id": "490311",
"Score": "0",
"body": "Good edit, I can +1 now :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T03:52:05.567",
"Id": "249939",
"ParentId": "249921",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T14:27:33.113",
"Id": "249921",
"Score": "4",
"Tags": [
"c#",
"console",
"generator"
],
"Title": "Password Generator \"Crapcode\""
}
|
249921
|
<p>How to flatten the nested try-catch block in F# for the following code? I am using <strong>EF Core</strong> with F#. <strong>The nested is required because I need to Rollback the transaction if there are errors in saving or committing the transaction!</strong></p>
<pre><code>let createTenant (ctx: AppContext) (tenant: Db.Tenant) (firstUser: Db.User) =
async {
try
let! db = ctx.Aquire()
use! transaction = db.Database.BeginTransactionAsync(IsolationLevel.Serializable) |> Async.AwaitTask
db.Tenant.Add tenant |> ignore
db.User.Add firstUser |> ignore
let! result =
async {
try
let! _ = db.SaveChangesAsync() |> Async.AwaitTask
do! transaction.CommitAsync() |> Async.AwaitTask
return Ok tenant.Id
with
| _ ->
do! transaction.RollbackAsync() |> Async.AwaitTask
return Error "internal error"
}
ctx.Release()
return result
with
| _ -> return Error "internal error"
}
</code></pre>
<p>On a side note, is this the clean/idiomatic way to handle exceptions in F#? Is there a better way to do this?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T18:36:25.737",
"Id": "490175",
"Score": "0",
"body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T06:38:27.510",
"Id": "490302",
"Score": "0",
"body": "You don't need the inner `try/catch`. If `SaveChangesAsync()` errors then the transaction will be rolled back anyway and you jump into the outer `try/catch`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T07:34:53.833",
"Id": "490308",
"Score": "0",
"body": "@GertArnold I am new to EF Core. Does it automatically rollback the transaction if there are errors in `SaveChangesAsync()` or `CommitAsync()` method?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T07:38:11.733",
"Id": "490310",
"Score": "1",
"body": "Yep. It's all or nothing with these methods."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T07:51:49.370",
"Id": "490313",
"Score": "0",
"body": "@GertArnold. Thanks. That explains it very well and makes complete sense."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T05:49:25.543",
"Id": "507664",
"Score": "1",
"body": "Not related to question, but since you're working mostly with TPL and `Task` class, it would be better to use [Ply](https://github.com/crowded/ply) or [TaskBuilder](https://github.com/rspeele/TaskBuilder.fs) to avoid usage of `Async.AwaitTask` which might be slow and gives better interop experience when your library is called from other languages"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T15:26:52.843",
"Id": "249923",
"Score": "1",
"Tags": [
"f#",
"entity-framework-core"
],
"Title": "How to flatten the nested try-catch block in F#?"
}
|
249923
|
<p>I was looking to this exercise: <a href="http://www.partow.net/testdome/testdome_binarysearchtree.cpp" rel="nofollow noreferrer">Is Valid Binary Search Tree</a></p>
<p>I tried to do the exercise by myself without looking to the solution and my code is "much simpler" than the code I found at the previous link. Is there anyone that can review this code or provide me some test cases for this problem? Generating test cases is way more time consuming than coding.</p>
<pre><code> /*
Question: TestDome - BinarySearchTree
Solution by Antonio Di Bacco 2020
Write a function that checks if a given binary tree is a valid
binary search tree. A binary search tree (BST) is a binary tree
where the value of each node is larger or equal to the values in
all the nodes in that node's left subtree and is smaller than the
values in all the nodes in that node's right subtree.
For example, for the following tree:
n1 (Value: 1, Left: null, Right: null)
n2 (Value: 2, Left: n1, Right: n3)
n3 (Value: 3, Left: null, Right: null)
Call to isValidBST(n2) should return true since a tree with root at
n2 is a valid binary search tree.
Explanation: Subtrees rooted at nodes n1 and n3 are valid binary
search trees as they have no children. A tree rooted at node n2 is
a valid binary search tree since its value (2) is larger or equal
to the largest value in its left subtree (1, rooted at n1) and is
smaller than the smallest value in its right subtree (3 rooted at
n3).
*/
#include <stdexcept>
#include <string>
#include <iostream>
#include <algorithm>
class Node
{
public:
Node(int value, Node* left, Node* right)
{
this->value = value;
this->left = left;
this->right = right;
}
int getValue() const
{
return value;
}
Node* getLeft() const
{
return left;
}
Node* getRight() const
{
return right;
}
private:
int value;
Node* left;
Node* right;
};
class BinarySearchTree
{
public:
static bool isValidBST(const Node& root)
{
if (root.getRight() == nullptr) {
if (root.getLeft() == nullptr) {
return true;
}
else {
if (root.getLeft()->getValue() < root.getValue())
return isValidBST(*(root.getLeft()));
else
return false;
}
}
else {
if (root.getLeft() == nullptr) {
if (root.getRight()->getValue() > root.getValue())
return isValidBST(*(root.getRight()));
else
return false;
}
else {
if ((root.getRight()->getValue() > root.getValue()) && (root.getLeft()->getValue() < root.getValue()))
return isValidBST(*(root.getLeft())) && isValidBST(*(root.getRight()));
else
return false;
}
}
}
private:
};
#ifndef RunTests
int main(int argc, const char* argv[])
{
Node n1(1, NULL, NULL);
Node n3(3, NULL, NULL);
Node N(2, &n1, &n3);
std::cout << BinarySearchTree::isValidBST(N) << std::endl;
Node m1(1, NULL, NULL);
Node m3(3, NULL, NULL);
Node M(2, &m3, &m1);
std::cout << BinarySearchTree::isValidBST(M) << std::endl;
Node p4(5, NULL, NULL);
Node p1(1, NULL, NULL);
Node p3(3, &p4, NULL);
Node P(2, &p1, &p3);
std::cout << BinarySearchTree::isValidBST(P) << std::endl;
return 0;
}
#endif
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T15:46:36.820",
"Id": "490142",
"Score": "0",
"body": "If you replace the `5` in your third test with `-5`, you incorrectly report the tree to be a valid BST."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T16:16:37.907",
"Id": "490150",
"Score": "1",
"body": "The solution is not correct. It is not enough to test the root agains its immediate children. In a valid BST _all the values_ in the _entire left subtree_ must be less than the root value. Consider a tree `(3, (2, (1), (5)), (...))`. It is not valid (`5` in the left subtree is greater than `3` at the root)."
}
] |
[
{
"body": "<p>To validate a BST tree you need to validate a sub tree is between two values.</p>\n<p>Remember that all nodes to the left must be less than the current node and everything to the right is larger. So after a left then a right you have a set of bounds (min and max).</p>\n<p>So when you are doing the validation I would expect to see you pass the bounds as you move down the sub-tree (now for the root you pass -MinInt +MaxInt as the bounds).</p>\n<pre><code>bool isValid(Node* root)\n{\n return isBound(root,\n std::numeric_limits<int>::min,\n std::numeric_limits<int>::max);\n}\nbool isBound(Node* node, int min, int max)\n{\n if (node == nullptr) {\n return true;\n }\n if (node->value < min || node->value > max) {\n return false;\n }\n return isBound(node->left, min, node->value)\n && isBound(node->right, node->value, max);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T16:31:45.547",
"Id": "249925",
"ParentId": "249924",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T15:27:13.693",
"Id": "249924",
"Score": "-2",
"Tags": [
"c++",
"validation",
"binary-search-tree"
],
"Title": "Validate Search Binary Tree"
}
|
249924
|
<p>This program might seem lazy, I also tried iterating through the vector but performance was poor so I used this lazy approach that has more performance</p>
<pre><code>#ifndef BINARY_HH
#define BINARY_HH
/**************************************************************************
* Name: Binary.hh
* Author: Samuel Oseh
* Date: 27/09/2020
* File Info: This file contains class method-function prototypes
* Purpose: Binary Converter is a program that converts a decimal
* to its binary equivalents and also performs other calculations
**************************************************************************/
#include <vector>
#include <string>
class Binary {
public:
Binary( const int &, const char & );
~Binary() {}
Binary( const Binary & );
void printBinary() const;
void toBinary();
char getType() const;
int getDecimal() const;
Binary &operator+=( const Binary &binaryToAdd );
Binary &operator-=( const Binary &binaryToSub );
Binary &operator*=( const Binary &binaryToMul );
Binary &operator/=( const Binary &binaryToDiv );
bool operator==( const Binary &binaryToCompare ) const;
inline bool operator!=( const Binary &binaryToCompare ) const {
return !( *this == binaryToCompare );
}
const Binary &operator=( const Binary &binaryToCopy );
private:
char type;
int decimal;
std::vector< int > binary{};
};
#endif
/**************************************************************************
* Name: Binary.cc
* Author: Samuel Oseh
* Date: 27/09/2020
* File Info: This file contains class method-function definitions
* Purpose: Binary Converter is a program that converts a decimal
* to its binary equivalents and also performs other calculations
**************************************************************************/
#include <iostream>
#include <stdexcept>
#include "Binary.hh"
Binary::Binary( const int &d, const char &t ) {
if ( tolower( t ) == 'd' )
type = t;
else
throw std::invalid_argument( "type must be 'd' only." );
if ( d < 0 )
throw std::invalid_argument( "decimal value must be greater than 0." );
decimal = d;
}
Binary::Binary( const Binary &binaryToCopy ) {
decimal = binaryToCopy.decimal;
type = binaryToCopy.type;
for ( unsigned int counter = 0; counter < binaryToCopy.binary.size(); ++ counter ) {
binary.push_back( binaryToCopy.binary[ counter ] );
}
}
void Binary::toBinary() {
if ( type == 'd' ) {
int val = decimal;
while ( val != 0 ) {
binary.insert( binary.begin(), val % 2 );
val /= 2;
}
}
else {
throw std::invalid_argument( "Invalid type conversion" );
}
}
void Binary::printBinary() const {
if ( binary.size() == 0 )
throw std::invalid_argument( "Cannot print binary object without converting it" );
for ( int number : binary ) {
std::cout << number << "";
}
}
char Binary::getType() const {
return type;
}
int Binary::getDecimal() const {
return decimal;
}
Binary &Binary::operator+=( const Binary &binaryToAdd ) {
if ( binary.size() == 0 )
throw std::invalid_argument( "Cannot add binary object without converting it" );
if ( binaryToAdd.binary.size() == 0 )
throw std::invalid_argument( "Cannot add binary object without converting it" );
int decimalSum = decimal + binaryToAdd.decimal;
Binary *b = new Binary( decimalSum, 'd' );
b->toBinary();
*this = *b;
delete b;
return *this;
}
Binary &Binary::operator-=( const Binary &binaryToAdd ) {
if ( binary.size() == 0 )
throw std::invalid_argument( "Cannot add binary object without converting it" );
if ( binaryToAdd.binary.size() == 0 )
throw std::invalid_argument( "Cannot add binary object without converting it" );
int decimalSum = decimal - binaryToAdd.decimal;
if ( decimalSum < 0 ) {
throw std::invalid_argument( "Can not perform subtraction from a lesser binary" );
}
Binary *b = new Binary( decimalSum, 'd' );
b->toBinary();
*this = *b;
delete b;
return *this;
}
Binary &Binary::operator*=( const Binary &binaryToMul ) {
if ( binary.size() == 0 )
throw std::invalid_argument( "Cannot add binary object without converting it" );
if ( binaryToMul.binary.size() == 0 )
throw std::invalid_argument( "Cannot add binary object without converting it" );
int decimalSum = decimal * binaryToMul.decimal;
Binary *b = new Binary( decimalSum, 'd' );
b->toBinary();
*this = *b;
delete b;
return *this;
}
Binary &Binary::operator/=( const Binary &binaryToDiv ) {
if ( binary.size() == 0 )
throw std::invalid_argument( "Cannot add binary object without converting it" );
if ( binaryToDiv.binary.size() == 0 )
throw std::invalid_argument( "Cannot add binary object without converting it" );
int decimalSum = decimal / binaryToDiv.decimal;
Binary *b = new Binary( decimalSum, 'd' );
b->toBinary();
*this = *b;
delete b;
return *this;
}
bool Binary::operator==( const Binary &binaryToCompare ) const {
if ( decimal == binaryToCompare.decimal )
return true;
return false;
}
const Binary &Binary::operator=( const Binary &binaryToCopy ) {
decimal = binaryToCopy.decimal;
type = binaryToCopy.type;
binary.clear();
for ( unsigned int counter = 0; counter < binaryToCopy.binary.size(); ++ counter ) {
binary.push_back( binaryToCopy.binary[ counter ] );
}
return *this;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T22:51:57.687",
"Id": "490188",
"Score": "0",
"body": "You are aware about [`std::bitset`](https://en.cppreference.com/w/cpp/utility/bitset) and [`std::vector<bool>`](https://en.cppreference.com/w/cpp/container/vector_bool), aren't you?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T22:54:49.450",
"Id": "490189",
"Score": "1",
"body": "I am not aware of std::bitset"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T22:56:50.547",
"Id": "490190",
"Score": "0",
"body": "Then it's probably worth to read the references I linked, and decide if you need that class at all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T23:01:54.107",
"Id": "490192",
"Score": "0",
"body": "Am confused how std::bool and std::bitset relates to my code.... Please explain"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T23:08:38.457",
"Id": "490193",
"Score": "4",
"body": "`std::bitset` already supports all those `operator` functions you need, including a `to_string()` function to get a printable output, and `to_long()` to provide conversion to a _\"normal decimal\"_. Ah, and a constructor that takes a string consisting of `'0'` and `'1'` characters. Simila for `std::vector<bool>`, which is a space optimized implementation of `std::vector<T>`, probably the better choice than a `std::vector<int>`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T07:26:06.070",
"Id": "490207",
"Score": "0",
"body": "A number is just a number (no matter the base). Its base is only important when you want to display it. We already have a representation of a number. All you need to implement is how that number is displayed."
}
] |
[
{
"body": "<h2>Overview</h2>\n<p>I think the most telling part is this:</p>\n<pre><code> int decimal;\n</code></pre>\n<p>That's probably not a decimal number. In most modern computer this is stored as a binary number (though in some exceedingly old computers they did use decimals but they gave up on decimal computers in favor of binary very quickly).</p>\n<p>The problem with your code is that a number is a number. Its base is only important when you visualize it, parse it or store it. Storing the number is an abstraction that the hardware layer has taken care of (the hardware knows how to store/and perform basic operation on integers). So the only thing to you is the presentation layer (printing and parsing).</p>\n<pre><code>Decimal 10:\nBinary 1010\nHex 0xA\n</code></pre>\n<p>These are all simply the visual representation of the same concept. We already have the concept of an integer number provided by the language <code>int</code> represents a value.</p>\n<hr />\n<h2>Code Review</h2>\n<p>The type <code>t</code> parameter is superfluous here.</p>\n<p>Binary::Binary( const int &d, const char &t ) {</p>\n<p>The value <code>d</code> is a number already. You only need the type if you are converting from a visual representation (i.e. a string). Otherwise it is always a number.</p>\n<hr />\n<p>Not sure why you don't support negative values:</p>\n<pre><code> if ( d < 0 )\n throw std::invalid_argument( "decimal value must be greater than 0." \n</code></pre>\n<p>Its not that hard?</p>\n<hr />\n<p>This could be simlified:</p>\n<pre><code> for ( unsigned int counter = 0; counter < binaryToCopy.binary.size(); ++ counter ) {\n binary.push_back( binaryToCopy.binary[ counter ] );\n }\n\n // Simpler to write:\n\n binary = binaryToCopy.binary;\n</code></pre>\n<hr />\n<p>If you want to store locally an easy to convert to text representation you could use <code>std::bitset<32></code>.</p>\n<pre><code>std::bitset<32> binary;\nvoid Binary::toBinary() {\n binary = decimal; // converts it into a bitset.\n // bitsset when put on a stream will show 1/0\n // Note internally it is just an int.\n}\n</code></pre>\n<hr />\n<p>Sure it is nice to have a print function.</p>\n<pre><code>void Binary::printBinary() const {\n</code></pre>\n<p>But in C++ we normally use <code>operator<<</code> to place data on an output stream. So it is nice to write the appropriate function that does that. Not it can simply call the <code>printBinary()</code> function. <strong>But</strong> you will need to modify your print function to accept a stream (you can default it to <code>std::out</code> for backwards compatability.</p>\n<pre><code> void Binary::printBinary(std::ostream& str = std::cout) const {\n binary.toBinary(); // You can convert see next section.\n out << binary; // Assuming you used std::bitset.\n }\n friend std::ostream& operator<<(std::ostream& str, Binary const& b)\n {\n b.printBinary(str);\n return str;\n }\n</code></pre>\n<hr />\n<p>You can convert the number in a const method.</p>\n<pre><code> if ( binary.size() == 0 ) \n throw std::invalid_argument( "Cannot print binary object without converting it" );\n</code></pre>\n<p>The <code>binary</code> object is storing temporary state (i.e it does not represent the state of the object. It represents an easy printable value of the current state. So this is a perfect place to mark a member as mutable.</p>\n<pre><code> mutable std::bitset<32> binary;\n</code></pre>\n<p>Now you can update the state in a const function:</p>\n<hr />\n<p>Once the value has been converted to a number its type is irelavant.</p>\n<pre><code>char Binary::getType() const {\n return type;\n}\n</code></pre>\n<hr />\n<p>You are not returning a decimal. You are returning a number.</p>\n<pre><code>int Binary::getDecimal() const {\n return decimal;\n}\n</code></pre>\n<p>Its actually stored as binary you know.</p>\n<hr />\n<p>Wow this seems like a lot of work.</p>\n<pre><code>Binary &Binary::operator+=( const Binary &binaryToAdd ) { \n if ( binary.size() == 0 ) \n throw std::invalid_argument( "Cannot add binary object without converting it" );\n if ( binaryToAdd.binary.size() == 0 ) \n throw std::invalid_argument( "Cannot add binary object without converting it" );\n\n int decimalSum = decimal + binaryToAdd.decimal;\n Binary *b = new Binary( decimalSum, 'd' );\n b->toBinary();\n *this = *b;\n delete b;\n return *this;\n}\n</code></pre>\n<p>First lets not create dynamic types:</p>\n<pre><code> Binary *b = new Binary( decimalSum, 'd' );\n b->toBinary();\n *this = *b;\n delete b;\n</code></pre>\n<p>This can be simplifies to:</p>\n<pre><code> Binary b( decimalSum, 'd' );\n b.toBinary();\n *this = b;\n</code></pre>\n<p>But why do all that why not simplify one more step and remove the intermediate object.</p>\n<pre><code> decimal += binaryToAdd.decimal;\n binary.clear(); // Not sure if you need this but probably.\n toBinary();\n</code></pre>\n<p>Not sure why they need to be already converted?</p>\n<pre><code> if ( binary.size() == 0 ) \n throw std::invalid_argument( "Cannot add binary object without converting it" );\n if ( binaryToAdd.binary.size() == 0 ) \n throw std::invalid_argument( "Cannot add binary object without converting it" );\n</code></pre>\n<p>Just get rid of that.</p>\n<hr />\n<p>Same thing applies here:</p>\n<pre><code>Binary &Binary::operator-=( const Binary &binaryToAdd ) { \nBinary &Binary::operator*=( const Binary &binaryToMul ) { \nBinary &Binary::operator/=( const Binary &binaryToDiv ) { \n // ^ Note in C++ (unlike C) the & and * go with the type (traditionally).\n</code></pre>\n<hr />\n<p>You implemented the += family of operators. This makes the next step so simply. I am surprised you did not implement the + family of operators.</p>\n<pre><code>Binary Binary::operator+(Binary const& rhs) const { \n Binary newValue(*this); // copy;\n return newValue += rhs; // Add to the copy and return.\n}\n</code></pre>\n<hr />\n<p>This can be simplified:</p>\n<pre><code> if ( decimal == binaryToCompare.decimal )\n return true;\n return false;\n</code></pre>\n<p>To</p>\n<pre><code> return decimal == binaryToCompare.decimal;\n</code></pre>\n<p>If you find your self doing:</p>\n<pre><code> if (test) {\n return true;\n }\n else {\n return false;\n }\n\n This is the same as\n\n return test; // as test must be a boolean value (or convertible to cone).\n</code></pre>\n<hr />\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T13:51:28.280",
"Id": "490252",
"Score": "0",
"body": "Re: negative numbers, perhaps the poster doesn't understand one's complement or two's complement or can't make a choice between the two."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T20:46:31.070",
"Id": "490277",
"Score": "0",
"body": "I thought a binary representation of a negative int would be irrelevant"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T07:57:14.673",
"Id": "249943",
"ParentId": "249935",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "249943",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T22:43:32.510",
"Id": "249935",
"Score": "3",
"Tags": [
"c++",
"performance"
],
"Title": "Decimal to Binary converter"
}
|
249935
|
<ol>
<li><p>Required to know the performance overhead associated with DataSet
and DataTable.</p>
</li>
<li><p>When it comes choosing which data structure might be good and performance oriented</p>
<ul>
<li>what if single Result Set is returned from Stored Procedure</li>
<li>what if more than one Result Set is returned from Stored Procedure</li>
</ul>
</li>
</ol>
<p>Question may arise choosing whether which one should we need to go for?</p>
<p>Here is the coding snippet from Business Access Layer:</p>
<pre><code>// Method 1: Using DataTable
public static ArrayList GetProctorsDetails(LoginUser sessionDetails)
{
List<ProctorUserDetails> proctorUserDetailsList = new List<ProctorUserDetails>();
DataTable dsProctorUserDetails = PasswordGeneratorDAL.GetProctorsDetails(sessionDetails);
if (dtProctorUserDetails != null && dtProctorUserDetails.Rows.Count > 0)
{
for (int i = 0; i < dtProctorUserDetails.Rows.Count; i++)
{
ProctorUserDetails proctorUserDetails = new ProctorUserDetails();
if (dtProctorUserDetails.Rows[i].Table.Columns.Contains("UserID") && dtProctorUserDetails.Rows[i]["UserID"] != DBNull.Value)
proctorUserDetails.UserID = Convert.ToString(dtProctorUserDetails.Rows[i]["UserID"]);
if (dtProctorUserDetails.Rows[i].Table.Columns.Contains("LoginName") && dtProctorUserDetails.Rows[i]["LoginName"] != DBNull.Value)
proctorUserDetails.LoginName = Convert.ToString(dtProctorUserDetails.Rows[i]["LoginName"]);
if (dtProctorUserDetails.Rows[i].Table.Columns.Contains("FirstName") && dtProctorUserDetails.Rows[i]["FirstName"] != DBNull.Value)
proctorUserDetails.FirstName = Convert.ToString(dtProctorUserDetails.Rows[i]["FirstName"]);
if (dtProctorUserDetails.Rows[i].Table.Columns.Contains("LastName") && dtProctorUserDetails.Rows[i]["LastName"] != DBNull.Value)
proctorUserDetails.LastName = Convert.ToString(dtProctorUserDetails.Rows[i]["LastName"]);
proctorUserDetailsList.Add(proctorUserDetails);
}
}
return proctorUserDetailsList;
}
</code></pre>
<hr />
<pre><code>// Method 2: Using DataSet
public static ArrayList GetProctorsDetails(LoginUser sessionDetails)
{
List<ProctorUserDetails> proctorUserDetailsList = new List<ProctorUserDetails>();
DataSet dsProctorUserDetails = PasswordGeneratorDAL.GetProctorsDetails(sessionDetails);
if (dsProctorUserDetails != null && dsProctorUserDetails.Tables.Count > 0 && dsProctorUserDetails.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < dsProctorUserDetails.Tables[0].Rows.Count; i++)
{
ProctorUserDetails proctorUserDetails = new ProctorUserDetails();
if (dsProctorUserDetails.Tables[0].Columns.Contains("UserID") && dsProctorUserDetails.Tables[0].Rows[i]["UserID"] != DBNull.Value)
proctorUserDetails.UserID = AESCrypto.Encrypt(Convert.ToString(dsProctorUserDetails.Tables[0].Rows[i]["UserID"]));
if (dsProctorUserDetails.Tables[0].Columns.Contains("LoginName") && dsProctorUserDetails.Tables[0].Rows[i]["LoginName"] != DBNull.Value)
proctorUserDetails.LoginName = Convert.ToString(dsProctorUserDetails.Tables[0].Rows[i]["LoginName"]);
if (dsProctorUserDetails.Tables[0].Columns.Contains("FirstName") && dsProctorUserDetails.Tables[0].Rows[i]["FirstName"] != DBNull.Value)
proctorUserDetails.FirstName = Convert.ToString(dsProctorUserDetails.Tables[0].Rows[i]["FirstName"]);
if (dsProctorUserDetails.Tables[0].Columns.Contains("LastName") && dsProctorUserDetails.Tables[0].Rows[i]["LastName"] != DBNull.Value)
proctorUserDetails.LastName = Convert.ToString(dsProctorUserDetails.Tables[0].Rows[i]["LastName"]);
proctorUserDetailsList.Add(proctorUserDetails);
}
}
return proctorUserDetailsList;
}
</code></pre>
<hr />
<pre><code>// To call SP to whichever prototype/return type
public static <String/DataSet/DataTable> GetProctorsDetails(LoginUser sessionDetails)
{
List<object> parameter = new List<object>();
parameter.Add(SqlHelper.BuildSqlParameter("OrganizationID", SqlDbType.BigInt, sizeof(Int64), sessionDetails.OrganizationID));
parameters.Add(SqlHelper.BuildSqlParameter("Status", SqlDbType.VarChar, 5, "Status", string.Empty, ParameterDirection.Output));
using (DataTable dt = SqlHelper.ExecuteDataTable(CommandType.StoredProcedure, "UspGetUserOrgDetails", parameters.ToArray(), false))
{
statusCode = Convert.ToString(SqlHelper.GetParameterValue(parameters[1]));
}
using (DataSet ds = SqlHelper.ExecuteDataset(CommandType.StoredProcedure, "UspGetUserOrgDetails", parameters.ToArray(), false))
{
statusCode = Convert.ToString(SqlHelper.GetParameterValue(parameters[1]));
}
return <statusCode/ds/dt>;
}
</code></pre>
<p>How should be our choice of selection? Especially for .NET Framework or Core or some other programming language</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T12:42:07.147",
"Id": "490244",
"Score": "2",
"body": "`DataSet` is a collection of `DataTable`. Whenever you need to process multiple different `DataTable`s for one database, you can use `DataSet` to take advantage of its capabilities like `DataRelation`, Data Integrity and Data Serialization. But if you just need only work on one table to process its data (like using `DataRow`) then DataTable would be enough."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T05:08:42.823",
"Id": "490296",
"Score": "0",
"body": "I assume that the `DataSet` example should be returning `dsProctorUserDetails` not an `ArrayList`? For that matter neither of your example methods is actually returning a value at all. Can you please fix these examples so that they should compile."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T05:43:51.553",
"Id": "490298",
"Score": "0",
"body": "Updated the semantic syntax!... The above shown was a partial coding snippets. There were other packages inherited to this class with `try`, `catch`, `finally`. As it would grow huge.. @ChrisSchaller"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T05:52:16.143",
"Id": "490299",
"Score": "0",
"body": "I appreciate that but it is important that you write a complete snippet if you want a code review, otherwise the first response in the review is that the code does not compile... If you are not going to include the return statement, don't include the method prototype."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T05:53:42.267",
"Id": "490300",
"Score": "0",
"body": "From these two examples, there is only negligible performance losses in dataset, your question should actually be about the _implementation_ or _definition_ of `GetProctorsDetails`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T08:08:51.797",
"Id": "490315",
"Score": "1",
"body": "Don't write your own ORM, use Dapper -- https://dapper-tutorial.net/ ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T12:28:04.043",
"Id": "490329",
"Score": "3",
"body": "Please do not update the code in your question after receiving answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] |
[
{
"body": "<p>As pointed out by @iSR5's comment, A <code>DataSet</code> is basically a wrapper around a <em>collection</em> or <code>DataTable</code> objects. It has some other helpful utility methods, but from a performance point of view the only performance issue with your logic is that in the <code>DataSet</code> solution you need to access the table to read from through the indexer that has <em>assumed</em> that there is a table at index <code>0</code>.</p>\n<ul>\n<li><strong>So there is not really a performance argument to choose one over the other.</strong></li>\n<li>Given that both solutions for your <em>Business layer</em> <code>GetProctorsDetails</code> do not return either of the <code>DataSet</code> or <code>DataTable</code> objects, your <em><strong>ONLY</strong></em> consideration is actually the implementation of <code>PasswordGeneratorDAL.GetProctorsDetails(sessionDetails);</code>\n<ul>\n<li>Your code examples already demonstrate that you can manage both types of results from this method.</li>\n</ul>\n</li>\n</ul>\n<h3>Focusing on the DAL Implementation</h3>\n<blockquote>\n<p>Specifically for <code>SqlHelper</code> there is no measurable difference between <code>ExecuteDataTable</code> and <code>ExecuteDataSet</code>, in fact if you have a look at the source code, most implementations or <code>ExecuteDataTable</code> use a <code>DataSet</code> internally:</p>\n<pre><code>var ds = new DataSet();\nusing (var dataAdapter = new SqlDataAdapter(command))\n{\n dataAdapter.Fill(ds);\n}\nreturn ds.Tables[0];\n</code></pre>\n<blockquote>\n<p><strong>DO NOT</strong> make the assumption that using <code>DataSet</code> is therefore more performant!</p>\n</blockquote>\n</blockquote>\n<p>The <em>only</em> reason you should consider a <code>DataSet</code> over a <code>DataTable</code> is because you want to return multiple tables of records. If you are only going to return a single table of results, <code>DataTable</code> is the better choice because it simplifies the code, but also conveys the correct expectation to callers that there is only a single table of records in this result set.</p>\n<h3>Back to the Business layer mapping</h3>\n<p>The <em>code smell</em> to watch out for is when you have lots of code that is accessing an item in an array at index zero, in your second code example the following indexer is evaluated 5 times for every record:</p>\n<pre><code>dsProctorUserDetails.Tables[0]\n</code></pre>\n<p>It's not a big deal at runtime, but the use of <code>DataSet</code> in this scenario has added an unnecessary level of complexity and uncertainty into this code.</p>\n<p>If we refactor your 1st two examples to reduce the repetitive column validations, (do you really expect or want to support the condition of only some if these columns being present in the result set?) you will see there is even less difference in the usage between <code>DataTable</code> and <code>DataSet</code>:</p>\n<pre><code>// Method 1: Using DataTable\npublic static ArrayList GetProctorsDetails(LoginUser sessionDetails)\n{\n List<ProctorUserDetails> proctorUserDetailsList = new List<ProctorUserDetails>();\n DataTable dtProctorUserDetails = PasswordGeneratorDAL.GetProctorsDetails(sessionDetails);\n\n if (dtProctorUserDetails != null && dtProctorUserDetails.Rows.Count > 0)\n {\n var userIdOrd = dtProctorUserDetails.Columns.Contains("UserID") ? dtProctorUserDetails.Columns["UserID"].Ordinal : -1;\n var loginOrd = dtProctorUserDetails.Columns.Contains("LoginName") ? dtProctorUserDetails.Columns["LoginName"].Ordinal : -1;\n var firstNameOrd = dtProctorUserDetails.Columns.Contains("FirstName") ? dtProctorUserDetails.Columns["FirstName"].Ordinal : -1;\n var lastNameOrd = dtProctorUserDetails.Columns.Contains("LastName") ? dtProctorUserDetails.Columns["LastName"].Ordinal : -1;\n for (int i = 0; i < dtProctorUserDetails.Rows.Count; i++)\n {\n var row = dtProctorUserDetails.Rows[i];\n ProctorUserDetails proctorUserDetails = new ProctorUserDetails();\n if (userIdOrd > 0 && !row.IsNull(userIdOrd))\n proctorUserDetails.UserID = AESCrypto.Encrypt(Convert.ToString(row[userIdOrd]));\n if (loginOrd > 0 && !row.IsNull(loginOrd))\n proctorUserDetails.LoginName = Convert.ToString(row[loginOrd]);\n if (firstNameOrd > 0 && !row.IsNull(firstNameOrd))\n proctorUserDetails.FirstName = Convert.ToString(row[firstNameOrd]);\n if (lastNameOrd > 0 && !row.IsNull(lastNameOrd))\n proctorUserDetails.LastName = Convert.ToString(row[lastNameOrd]);\n\n proctorUserDetailsList.Add(proctorUserDetails);\n }\n }\n return proctorUserDetailsList;\n}\n</code></pre>\n<p>For performance reasons, I have moved the column exists check out of the row indexer (all rows in the table will have the same columns), by storing and using the column <em>ordinal</em> we can squeeze out some additional CPU ticks by not having to compare strings.</p>\n<p>See if you can spot the main difference between Method 1 and Method 2:</p>\n<pre><code>// Method 2: Using DataSet\npublic static ArrayList GetProctorsDetails(LoginUser sessionDetails)\n{\n List<ProctorUserDetails> proctorUserDetailsList = new List<ProctorUserDetails>();\n DataSet dsProctorUserDetails = PasswordGeneratorDAL.GetProctorsDetails(sessionDetails);\n if (dsProctorUserDetails != null && dsProctorUserDetails.Tables.Count > 0 && dsProctorUserDetails.Tables[0].Rows.Count > 0)\n {\n DataTable dtProctorUserDetails = dsProctorUserDetails.Tables[0];\n\n var userIdOrd = dtProctorUserDetails.Columns.Contains("UserID") ? dtProctorUserDetails.Columns["UserID"].Ordinal : -1;\n var loginOrd = dtProctorUserDetails.Columns.Contains("LoginName") ? dtProctorUserDetails.Columns["LoginName"].Ordinal : -1;\n var firstNameOrd = dtProctorUserDetails.Columns.Contains("FirstName") ? dtProctorUserDetails.Columns["FirstName"].Ordinal : -1;\n var lastNameOrd = dtProctorUserDetails.Columns.Contains("LastName") ? dtProctorUserDetails.Columns["LastName"].Ordinal : -1;\n for (int i = 0; i < dtProctorUserDetails.Rows.Count; i++)\n {\n var row = dtProctorUserDetails.Rows[i];\n ProctorUserDetails proctorUserDetails = new ProctorUserDetails();\n if (userIdOrd > 0 && !row.IsNull(userIdOrd))\n proctorUserDetails.UserID = AESCrypto.Encrypt(Convert.ToString(row[userIdOrd]));\n if (loginOrd > 0 && !row.IsNull(loginOrd))\n proctorUserDetails.LoginName = Convert.ToString(row[loginOrd]);\n if (firstNameOrd > 0 && !row.IsNull(firstNameOrd))\n proctorUserDetails.FirstName = Convert.ToString(row[firstNameOrd]);\n if (lastNameOrd > 0 && !row.IsNull(lastNameOrd))\n proctorUserDetails.LastName = Convert.ToString(row[lastNameOrd]);\n\n proctorUserDetailsList.Add(proctorUserDetails);\n }\n }\n return proctorUserDetailsList;\n}\n</code></pre>\n<p>If you missed it, in the second example we get the table at index 0 from the dataset, from then on the processing is identical:</p>\n<pre><code>DataSet dsProctorUserDetails = PasswordGeneratorDAL.GetProctorsDetails(sessionDetails);\nDataTable dtProctorUserDetails = dsProctorUserDetails.Tables[0];\n</code></pre>\n<p>Remember my point above:</p>\n<blockquote>\n<p>DO NOT make the assumption that using DataSet is therefore more performant!</p>\n</blockquote>\n<p>There is <em>zero</em> net difference between 1 and 2 in the refactored versions, in 1 the <code>.Tables[0]</code> is executed once inside the <code>SqlHelper</code> routine, in 2 it is executed in our code.</p>\n<hr />\n<h3>Additional Considerations</h3>\n<p>In General, using the DataTable solution is likely to have less long term maintenance issues <em>especially</em> when you want to support a stored procedure that might return multiple tables of result sets.</p>\n<ul>\n<li>When there are multiple tables in the response, only the calling context (the context that provides the SQL) is likely to know <em>which</em> one of the tables in the result set is the table that this method needs to interact with, unless you can <em>guarantee</em> that the proctor details table that you want to inspect is always the first table in the <code>DataSet</code>.\n<ul>\n<li>So <code>DataTable</code> is better than trying to blindly support <code>DataSet</code>, to properly support <code>DataSet</code> you should be iterating the <em>Tables</em> within it to identify which table matches the columns that you are expecting to read from.</li>\n</ul>\n</li>\n</ul>\n<blockquote>\n<p>How should be our choice of selection? Especially for .NET Framework or Core or some other programming languge</p>\n</blockquote>\n<p>From a performance and maintenance perspective I would not advocate using <code>DataTable</code> <em>or</em> <code>DataSet</code> in a new project or any .Net Core projects moving forward. Instead I would recommend moving towards a typed data access layer using an ORM framework or tool (Entity Framework/nHibernate). To keep your DAL and DTO classes decoupled you can use <em>Interfaces</em> instead of <em>DataSets/DataTables</em>. There are also tools like <em>AutoMapper</em> that replace your first two code examples to map between your DAL and business layer or DTOs.</p>\n<p>In legacy or simple .Net FX applications <code>DataSet</code> or <code>DataTable</code> can work, even moving forward, however there have been other significant advances in the IDE <em>tooling</em> and syntax and language runtimes that mean it is often easier and less error prone to work in <em>typed</em> data models, so avoiding <code>DataTable</code> and <code>DataSet</code> altogether.</p>\n<p>The issue with DataTable and DataSets, from a performance perspective, is that code like this must search for and pre-validate every property on demand. When you move to a <em>typed</em> interface the property resolution and type validation is performed in an efficient manner when the data is loaded from the database, or when it is deserialized.</p>\n<ul>\n<li>Note, as you flagged performance as a driving factor, implementing an ORM and or a DTO mapper like <em>AutoMapper</em> itself is not likely to be more performant, in fact it can be perceived to be slower in some cases, especially for loading data records, however your code becomes more reliable saving you development time and they can award you performance and maintenance gains throughout the rest of your application to offset or trade off any losses you might be able to measure at data load.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T12:28:41.203",
"Id": "490330",
"Score": "2",
"body": "If the latest edits have invalidated (part of) your answer, please notify me and we'll rollback the edits on the question. We take answer invalidation seriously here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T23:14:31.830",
"Id": "490361",
"Score": "1",
"body": "thanks @Mast the edits don't really change a lot, just confirmed what I thought was going on, I'll tldr my answer i guess"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T05:35:48.027",
"Id": "249979",
"ParentId": "249946",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T10:00:01.917",
"Id": "249946",
"Score": "1",
"Tags": [
"c#",
"performance",
".net-datatable"
],
"Title": "Ideal ways for Choosing DataSet or DataTable"
}
|
249946
|
<p>I currently working on CS50. There is a problem where we need to recreate half-pyramids using hashes (#). The hashes are to substitute blocks like in Mario.</p>
<p>This is also the first time I'm using Python. I don't really know Python. So I just try to calculate myself based on my experience from C language.</p>
<pre><code>from sys import exit
from cs50 import get_int
def main():
while True:
num = get_int("Height: ")
if num >= 1 and num <= 8:
break
print_pyramid(num)
exit(0)
def print_pyramid(n):
for i in range(n):
print_spaces(i, n) # calling two function that print spaces and hash
print_hash(i) # after print every spaces and hash in each row,
print() # print new line for new row
def print_spaces(i, n):
for j in range(n-(i+1)): # those calculation means that we print space one less than the height ......# (seven spaces)
print(" ", end="") # if height = 8 8-(i+1) 'i' is increment from above function .....## (six spaces)
def print_hash(i):
for l in range(i+1): # print the hash by increasing it (i+1)
print("#", end="") # i = 0 # / i = 1 ##
l = 1 # there's two spaces between two pyramid. at the print_spaces function range(n - i+1)
n = 4 # so initialize l = 1 and n = 4, would always give (4-(1+1)) = 2
print_spaces(l, n)
for l in range(i+1): # print rigth hash 'pyramid'
print("#", end="")
main()
</code></pre>
<p>I always love to work with complicated idea using a lot of function for their different purpose.</p>
<p>I also got a 98% score from CS50.</p>
<p>What do you think of my code? Since this is my first time using Python, are there any Pythonic ways to simplify my program? (especially using function like I did).</p>
<pre><code>Height: 4
# #
## ##
### ###
#### ####
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T11:15:01.493",
"Id": "490224",
"Score": "4",
"body": "for those (like me) who don't know: __what is CS50__?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T11:24:28.770",
"Id": "490228",
"Score": "1",
"body": "@hjpotter92 [It's a course Harvard University provides](https://en.wikipedia.org/wiki/CS50). The website is https://cs50.harvard.edu"
}
] |
[
{
"body": "<p>Your code is quite nice. Your use of functions seem quite reasonable. And your style is nice too. Good job!</p>\n<ul>\n<li><p>Calling <code>print</code> is expensive. To improve performance we can build the strings without using the for loop. For example to build <span class=\"math-container\">\\$n-(i + 1)\\$</span> spaces we can use:</p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> n = 12; i = 1\n>>> " " * (n - (i + 1))\n' '\n</code></pre>\n</li>\n<li><p>To build the pyramid you can delegate the creation of the spaces to Python by using <code>str.ljust</code> and <code>str.rjust</code>.\nThese functions allow an easy to use way to build the pyramid.</p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> 'abc'.ljust(10)\n'abc '\n>>> 'abc'.rjust(10)\n' abc'\n</code></pre>\n</li>\n<li><p>Using <code>print_spaces(l, n)</code> is harder to understand than <code>print(" ")</code>.</p>\n</li>\n<li><p>Your use of comments are not great. Most of them can be understood by just reading the code.</p>\n<p>I only found one of your comments to help.\nBecause it explains something that isn't particuarly clear in clear English.</p>\n<pre class=\"lang-py prettyprint-override\"><code># there's two spaces between two pyramid. at the print_spaces function range(n - i+1)\n# so initialize l = 1 and n = 4, would always give (4-(1+1)) = 2\n</code></pre>\n<p>However this is a sign that your code is complicated.\nWhich if you fix will make your comment redundent.</p>\n</li>\n</ul>\n<p>If we put these together we can greatly simplify your code.</p>\n<pre class=\"lang-py prettyprint-override\"><code>from sys import exit\nfrom cs50 import get_int\n\ndef main():\n while True:\n num = get_int("Height: ")\n if num >= 1 and num <= 8:\n break\n\n print_pyramid(num)\n exit(0)\n\ndef print_pyramid(n):\n for i in range(n):\n hashes = "#" * (i + 1)\n print(hashes.rjust(n) + " " + hashes)\n\nmain()\n</code></pre>\n<p>There are still some more improvements that can be made.</p>\n<ul>\n<li><p>Using <code>sys.exit(0)</code> is abnormal. It is normally best to just let Python handle that for you.</p>\n</li>\n<li><p>We can add an <code>if __name__ == "__main__"</code> guard to prevent your code from running if you import it accidentally.</p>\n<p>This is because if you use <code>import filename</code> you can import this program by accident and we don't want to run the <code>main</code> function if that happens.</p>\n</li>\n<li><p>I personally am a fan of always using the <code><</code> operator.\nIt just feels natural to see numbers ordered from smallest to largest, left to right.</p>\n</li>\n<li><p>We can Pythonify the print in <code>print_pyramid</code> by using the <a href=\"https://docs.python.org/3/library/string.html#format-specification-mini-language\" rel=\"noreferrer\">Format Specification Mini-Language</a>.</p>\n<p>There are three parts to this.</p>\n<ol>\n<li><p>By using a <a href=\"https://docs.python.org/3/reference/lexical_analysis.html#f-strings\" rel=\"noreferrer\">format string</a> we can enter values where we want them in a formatted string.</p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> a = 1; b = 2; c = 3\n>>> f"{b}:{a} -> {c}"\n'2:1 -> 3'\n>>> "{b}:{a} -> {c}" # Not a format string\n'{b}:{a} -> {c}'\n>>> "{b}:{a} -> {c}".format(a=a, b=b, c=c) # Old style format strings\n'2:1 -> 3'\n</code></pre>\n</li>\n<li><p>We can use the alignment option to align the values where we want them to.</p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> a = 1; b = 2; c = 3\n>>> f"{b:>3}:{a:<3} -> {c:^3}"\n' 2:1 -> 3 '\n</code></pre>\n</li>\n<li><p>We can enter the width using the same <code>{}</code> syntax as the values.</p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> a = 1; b = 2; c = 3; width = 3\n>>> f"{b:>{width}}:{a:<{width}} -> {c:^{width}}"\n' 2:1 -> 3 '\n</code></pre>\n</li>\n</ol>\n</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>from sys import exit\nfrom cs50 import get_int\n\n\ndef main():\n while True:\n num = get_int("Height: ")\n if 1 <= num and num <= 8:\n break\n print_pyramid(num)\n\n\ndef print_pyramid(n):\n for i in range(n):\n hashes = "#" * (i + 1)\n print(f"{hashes:>{n}} {hashes}")\n\n\nif __name__ == "__main__":\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T17:55:36.470",
"Id": "490527",
"Score": "0",
"body": "Thank you so much. Your code is so simple. I'll try to understand it more deeply."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T10:37:41.887",
"Id": "249949",
"ParentId": "249948",
"Score": "6"
}
},
{
"body": "<ul>\n<li>You use three different names for the same thing. You ask for <code>Height</code>, then call it <code>num</code>, then call it <code>n</code>. I'd just call the variables <code>height</code>, both to be consistent and to be meaningful. At least in <code>main</code> and <code>print_pyramid</code>, as there it really means height. In <code>print_spaces</code> it's perhaps better to keep calling the parameter <code>n</code>, as that function doesn't need to know about pyramids and heights.</li>\n<li><code>num >= 1 and num <= 8</code> can be the nicer <code>1 <= num <= 8</code> (or rather <code>1 <= height <= 8</code>).</li>\n<li>Your actual output does not match the claimed/desired(?) output you showed. You do <em>not</em> have those extra spaces at the start of each line to fill up the left pyramid half to width 8. Which I guess you should, as that would match the <code><= 8</code> condition, so that seems intended.</li>\n<li>You use <code>i</code> at three places, and every single time you add <code>1</code> to it. Probably clearer to do that in the range right away, i.e., <code>for i in range(1, n+1):</code> instead of <code>for i in range(n):</code>.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T11:54:01.353",
"Id": "249954",
"ParentId": "249948",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T10:24:11.053",
"Id": "249948",
"Score": "6",
"Tags": [
"python",
"beginner",
"python-3.x",
"programming-challenge",
"ascii-art"
],
"Title": "Recreate Mario's half-pyramids using hashes (#) from CS50"
}
|
249948
|
<p>Input:</p>
<pre><code>Enter an integer number: 123456 [Any number of digits are allowed]
</code></pre>
<p>Output:</p>
<pre><code>Completed integer number : 654321
</code></pre>
<p>I have solved this problem by following this strategy:</p>
<pre><code>#include <stdio.h>
int main(void){
//put variables for further proceed
int number=get_input_validation();
int value=find_out_the_number_of_digit(number);
find_out_the_reverse_order_and_transform_digits_as_a_complete_integer(number,value);
}
int get_input_validation(){
int number=0;
while(1){
//Taking input from the user
printf("Enter an integer number: ");
scanf("%d",&number);
if(number<=0){
printf("Zero and negative numbers are not allowed here\n");
}
else{
break;
}
}
return number;
}
int find_out_the_number_of_digit(int number){
int count=0;
int value=1;
//Getting total digits of a given integer number
while(number!=0){
number=number/10;
count++;
if(count==1){
value=1;
}
else{
value=value*10;
}
}
return value;
}
int find_out_the_reverse_order_and_transform_digits_as_a_complete_integer(int number,int value){
int complete_integer=0;
while(number!=0){
int last_digit=0;
//get the last digit
last_digit=number%10;
//get the quotient
number=number/10;
complete_integer=complete_integer+last_digit*value;
value=value/10;
}
printf("Completed integer number : %d",complete_integer);
}
</code></pre>
<p>I am here for:
What about my indentation and comments? Will I face any problem for some conditions? How can I simplify my solution by reducing too much line of codes in an efficient way?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T13:47:25.020",
"Id": "490251",
"Score": "4",
"body": "\"What about my indentation\" - What indentation? I almost don't see any."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T15:04:36.973",
"Id": "490261",
"Score": "0",
"body": "Thank you for your response. How can I improve on this segment?"
}
] |
[
{
"body": "<h1>Indentation</h1>\n<p>The indentation of your post is very bad, mainly because it is very inconsistent. It doesn't really matter what <a href=\"https://en.wikipedia.org/wiki/Indentation_style\" rel=\"nofollow noreferrer\">indentation style</a> you choose, as long as you consistently follow the style. However I strongly recommend the following things:</p>\n<ul>\n<li>Use spaces around binary operators, after keywords, after comma's.</li>\n<li>Use a single empty line around functions and <code>if</code>, <code>case</code>, <code>do</code> and <code>while</code> blocks.</li>\n<li>Prefer <code>foo += bar</code> instead of <code>foo = foo + bar</code> to avoid repeating yourself.</li>\n</ul>\n<p>So for example:</p>\n<pre><code>int find_out_the_number_of_digit(int number) {\n int count = 0;\n int value = 1;\n\n // Getting total digits of a given integer number\n while (number != 0) {\n number /= 10;\n count++;\n\n if (count == 1) {\n value = 1;\n } else {\n value *= 10;\n }\n }\n\n return value;\n}\n</code></pre>\n<p>Try to write correctly formatted code at all times, it helps both yourself and others reading your code. If possible, configure your editor to automatically indent code for you. Be aware though that editors are usually a bit dumb and might not always produce correct indentation, in which case you should correct it yourself. You can also run your code through a program that indents the code for you, like <a href=\"https://en.wikipedia.org/wiki/Indent_(Unix)\" rel=\"nofollow noreferrer\"><code>indent</code></a> or <a href=\"https://clang.llvm.org/docs/ClangFormat.html\" rel=\"nofollow noreferrer\">ClangFormat</a>.</p>\n<h1>Comments</h1>\n<p>Use comments to clarify things that are not already clear from the code itself. Most of the comments you wrote are superfluous, because they repeat exactly what the code below does, or because it is already clear from the context. Let's look at your comments:</p>\n<pre><code>//put variables for further proceed\nint number=get_input_validation();\nint value=find_out_the_number_of_digit(number);\n</code></pre>\n<p>The sentence is not completely correct English, but it's clear that you mean you are storing information in variables for further processing. But that's just something that is done all the time when programming, it doesn't clarify anything here.</p>\n<pre><code>int get_input_validation(){\n ...\n //Taking input from the user\n printf("Enter an integer number: ");\n scanf("%d",&number);\n</code></pre>\n<p>It is already clear from both the name of the function and the two lines below that you are indeed reading input from the user. So in this case I would say the comment is superfluous. A comment like this might be useful however if you have a longer function that does multiple things, and where the comments then separate the various parts of the function, although in that case it is probably better to split such a function up into several smaller ones, which you already did here.</p>\n<pre><code>int find_out_the_number_of_digit(int number){\n ...\n //Getting total digits of a given integer number\n</code></pre>\n<p>Here the comment is just repeating what is already in the name of the function.</p>\n<pre><code>//get the last digit\nlast_digit=number%10;\n\n//get the quotient\nnumber=number/10;\n</code></pre>\n<p>Here each comment basically repeats exactly what the line below does. What would be better is to write a comment that explains what is happening at a higher level:</p>\n<pre><code>// Pop the last digit from number\nlast_digit = number % 10;\nnumber /= 10;\n</code></pre>\n<h1>Simplifying the solution</h1>\n<p>There is a simpler solution that is also more efficient, by avoiding the first pass over all the digits to find the length of the number. The solution could be a single loop that does this:</p>\n<pre><code>while (number != 0) {\n // Step 1: pop last digit from number\n ...\n\n // Step 2: push the digit to the back of complete_integer\n ...\n}\n</code></pre>\n<p>Doing this will result in the order of the digits to be reversed. You already implemented popping the last digit from a number, now try to implement the reverse operation of pushing something to the back of a number, without having to know the exact length of that number.</p>\n<h1>About input validation</h1>\n<p>I wonder why you don't allow the number <code>0</code> to be reversed. It seems that this has a clear answer. You should be able to handle that case without having to write any additional code.</p>\n<p>For negative numbers, you could indeed disallow them, or instead define how a negative number will be reversed. For example, you could say that the reverse of the number <code>-123</code> will be <code>-321</code>, and then ensure your code implements this case. If the requirements for this project don't say anything about negative numbers, it is up to you.</p>\n<h1>Naming things</h1>\n<p>It is good to have descriptive names for functions and variables. One-letter names are usually bad, unless it's for very commonly used things such as <code>i</code> for a loop iterator, or <code>x</code> and <code>y</code> for coordinates. But too long names can be bad as well; they require more typing, and they are distracting. Not only try to be clear, also be <em>concise</em>. For example:</p>\n<pre><code>int find_out_the_reverse_order_and_transform_digits_as_a_complete_integer(int number,int value){\n ...\n}\n</code></pre>\n<p>That's a lot of text! Now compare the following:</p>\n<pre><code>int reverse_digits(int number) {\n ...\n}\n</code></pre>\n<p>The name of this function, along with the type of the input parameters and return value, are still very descriptive; it tells you that if you give it a number as a parameter, the function will reverse the digits, and returns the result as an interger. The name is much more concise though.</p>\n<p>Similarly, even though you shouldn't need this function, <code>find_out_the_number_of_digit()</code> could be shortened to <code>count_digits()</code>.</p>\n<p>On the other hand, also be aware of using too similar names. For example:</p>\n<pre><code>int number=get_input_validation();\nint value=find_out_the_number_of_digit(number);\n</code></pre>\n<p>Now you have two variables, <code>number</code> and <code>value</code>. Now I have to look at what function was called to find out that <code>value</code> is actually the number of digits in <code>number</code>. Here is a suggestion for renaming it:</p>\n<pre><code>int input = get_input();\nint digits_in_input = count_digits(input);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T07:37:18.833",
"Id": "490309",
"Score": "1",
"body": "\"Run your code through a program that indents the code for you\" I disagree. Adopt a consistent coding style and minimum of discipline when writing code, don't rely on some tool to do that for you. Discipline is perhaps the most single-most important programmer trait of all, more so than brains and tech skills even."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T09:23:48.383",
"Id": "490318",
"Score": "0",
"body": "I agree with you. Please give me some tips about how can I improve my coding format and styles as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T15:24:48.577",
"Id": "490343",
"Score": "0",
"body": "I improved the section about indentation, and also added one about comments."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T10:01:21.890",
"Id": "490584",
"Score": "0",
"body": "Sir, I checked and I learned a lot from your information. Thank you, sir. May allah bless you. Keep up the good work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T21:25:31.223",
"Id": "490680",
"Score": "0",
"body": "Thank you, @AshifulIslamPrince, and I wish you well in your future coding projects! Consider marking the answer that was most helpful to you as the [accepted answer](https://codereview.stackexchange.com/help/accepted-answer). Note that you can always change the accepted answer if a better answer is added later."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T11:57:13.480",
"Id": "249956",
"ParentId": "249951",
"Score": "10"
}
},
{
"body": "<p>You say "Any number of digits are allowed" but then try to read into an <code>int</code>, which can hold only very few digits. So at that point you already lost. Also, even if the entered number fits into an int, the reverse might not:</p>\n<pre><code>Enter an integer number: 1000000003\nCompleted integer number : -1294967295\n</code></pre>\n<p>Better use a string instead of an <code>int</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T15:01:34.260",
"Id": "490259",
"Score": "0",
"body": "That's a good point and very helpful. Thank you."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T13:56:01.007",
"Id": "249960",
"ParentId": "249951",
"Score": "8"
}
},
{
"body": "<blockquote>\n<p>How can I simplify my solution by reducing too much line of codes in an efficient way?</p>\n</blockquote>\n<p>Simplify and drop <code>value</code>. Not needed and as used may overflow. Perhaps use a wider type to reverse <code>int</code> values like 1000000009.</p>\n<pre><code> long long complete_integer = 0;\n while(number) {\n complete_integer = complete_integer*10 + number%10;\n number=number/10;\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T20:04:07.380",
"Id": "250015",
"ParentId": "249951",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "249956",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T10:51:06.810",
"Id": "249951",
"Score": "4",
"Tags": [
"c"
],
"Title": "Transformed and stored reversed order digits of an integer to a complete integer number"
}
|
249951
|
<p>Just as a learning exercise, I am implementing a poker game simulator. I am purposefully not searching for ready made tutorials showing how to do this, relying mostly on the python docs - that way I hope to learn in a more memorable, albeit slower, way. I'm looking for advice on how to code the comparison between cards, so that e.g. Five beats Four.</p>
<p>My current implementation works, but I feel it is a little hacky and very inefficient in one particular detail and there must be a better way. In the Card class <strong>init</strong>, I am setting an attribute order which is just a list of the members of the CardValue enum, in the order they are declared.</p>
<p>While I could just use enum.auto(), or manually set the values as integers and hence simply use those for comparisons (still with <strong>eq</strong> etc), that would lose me the ability to make use of the enum values to form the human readable card value names.</p>
<p>Is there a better way to go about this than the below code? I feel like the comparison operators should be in the enum itself, but so far have not worked out how to get that to work with my meaningful values for the members of the enum.</p>
<pre><code>from enum import Enum
from functools import total_ordering
class CardValue(Enum):
TWO = "2"
THREE = "3"
...
...
KING = "King"
ACE = "Ace"
@total_ordering
class Card:
def __init__(self, value, suit):
self.value = value
self.suit = suit
self.order = [en for en in CardValue] ### This seems wrong and very inefficient!
def __eq__(self, other):
if self.__class__ is other.__class__:
return self.order.index(self.value) == self.order.index(other.value)
def __lt__(self, other):
if self.__class__ is other.__class__:
return self.order.index(self.value) < self.order.index(other.value)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T11:13:28.583",
"Id": "490222",
"Score": "1",
"body": "`type(self) is type(other)` =)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T03:54:23.127",
"Id": "490294",
"Score": "1",
"body": "Actually, the comparison of cards varies across different card games. Therefore it might be more logical to separate cards from their ordering in different classes."
}
] |
[
{
"body": "<p>There are a couple choices, but the best is to record the <code>value</code>'s index on <code>Card</code> creation:</p>\n<pre><code>self.order = value._member_names_.index(value.name)\n</code></pre>\n<p>Then your comparison can use <code>self.order</code> directly:</p>\n<pre><code>return self.order < other.order\n</code></pre>\n<p><code>_member_names_</code> is a supported attribute and won't be going away.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T13:43:22.203",
"Id": "490249",
"Score": "1",
"body": "Nice answer. To expand on the answer; if, for some reason, `value` is mutable then you'd want to make `value` a [property](https://docs.python.org/3/library/functions.html#property). Putting the assignment to `order` in the setter instead of the `__init__`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T00:46:11.177",
"Id": "490367",
"Score": "0",
"body": "Nope, sorry -- I forgot my answer was not in the Enum, and thought you were speaking about the Enum. You're first comment is perfectly correct; deleting my erroneous comment."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T13:27:05.517",
"Id": "249959",
"ParentId": "249952",
"Score": "5"
}
},
{
"body": "<p>You can define an <code>__init__</code> method for an Enum. It gets passed the value of each enum member. Use it to define an <code>order</code> attribute for each enum member. For example, the Enum member <code>Ace = "Ace"</code> calls <code>__init__</code> with <code>value = "Ace"</code>, and <code>CardValue.ACE.order</code> will be set to <code>'__23456789TJQKA'.index(value[0])</code>, which is 14.</p>\n<p>Also, define <code>__eq__</code> and <code>__lt__</code> for comparing CardValues.</p>\n<p>I changed the Enum to CardRank, because I found it clearer.</p>\n<pre><code>@total_ordering\nclass CardRank(Enum):\n TWO = "2"\n THREE = "3"\n KING = "King"\n ACE = "Ace" \n \n def __init__(self, value):\n # the '__' are so "2" has an order of 2 and so on.\n self.order = '__23456789TJQKA'.index(value[0])\n \n def __eq__(self, other):\n if self.__class__ is other.__class__:\n return self.order == other.order\n raise NotImplemented\n \n def __lt__(self, other):\n if self.__class__ is other.__class__:\n return self.order < other.order\n raise NotImplemented\n \n\n@total_ordering\nclass Card:\n def __init__(self, rank, suit):\n self.rank = rank\n self.suit = suit\n\n def __eq__(self, other):\n return self.rank == other.rank\n\n def __lt__(self, other):\n return self.rank < other.rank\n</code></pre>\n<p>Try to choose data types/structures/values that are going to make programming the core of your application easier. If needed, provide methods to translate internal values for the user. In this case, using an IntEnum would let you compare CardRanks without needing extra code (<code>__lt__</code>, <code>total_ordering</code>, etc). Just add a <code>__str__()</code> method to get the text for the rank.</p>\n<pre><code>class CardRank(IntEnum):\n Two = 2\n Three = 3\n Four = 4\n Five = 5\n Six = 6\n Seven = 7\n Eight = 8\n Nine = 9\n Ten = 10\n Jack = 11\n Queen = 12\n King = 13\n Ace = 14\n \n def __str__(self):\n if self.value <= 10:\n return str(self.value)\n else:\n return ['Jack', 'Queen', 'King', 'Ace'][self.value - 11]\n</code></pre>\n<p>Test it:</p>\n<pre><code>>>> print(CardRank.King, str(CardRank.Two), CardRank.Four < CardRank.Ten)\nKing 2 True\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T22:54:10.120",
"Id": "490288",
"Score": "1",
"body": "`['Jack', 'Queen', 'King', 'Ace'][self.value - 11]` can be replaced with `self.name`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T21:16:58.507",
"Id": "490359",
"Score": "0",
"body": "Using `IntEnum` also means your enum members can be compared to completely different integer-based enums, which is almost always a bad idea."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T22:47:17.217",
"Id": "249973",
"ParentId": "249952",
"Score": "2"
}
},
{
"body": "<p>In the end I have decided to use IntEnum. Also, a little trick to create it I found on other posts (fine for now, I can refactor as need arises if I need something more complex later).</p>\n<pre><code>from enum import IntEnum\ncards = ['LowAce', 'Two', 'King', 'Ace']\nCardRank = IntEnum('CardRank', cards)\n</code></pre>\n<p>Check:</p>\n<pre><code>_ = [print(card.name, card.value) for card in CardRank]\nCardRank.Two < CardRank.King\n</code></pre>\n<p>Result:</p>\n<pre><code>LowAce 1\nTwo 2\nKing 3\nAce 4\nTrue\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T11:12:29.613",
"Id": "249990",
"ParentId": "249952",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "249973",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T10:54:18.797",
"Id": "249952",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"enum"
],
"Title": "Efficient implementation of comparison operators for cards in a poker simulation"
}
|
249952
|
<p>The following is the web exercise 3.2.12. from the book <em>Computer Science An Interdisciplinary Approach</em> by Sedgewick & Wayne:</p>
<blockquote>
<p>Write a program that draws a <a href="https://en.wikipedia.org/wiki/Vector_field" rel="nofollow noreferrer">vector field</a>. A vector field associates a vector with every point in a Euclidean
space. Widely used in physics to model speed and direction of a moving
object or strength and direction of a Newtonian force.</p>
</blockquote>
<p>Here is my program:</p>
<pre><code>public class Vector {
private final double[] coordinates;
public Vector(double[] coordinates) {
this.coordinates = coordinates;
}
private int getCoordinatesLength() {
return coordinates.length;
}
public double getCoordinate(int index) {
return coordinates[index - 1];
}
public double getLength() {
double sumOfCoordinatesSquared = 0;
for (int i = 0; i < getCoordinatesLength(); i++) {
sumOfCoordinatesSquared += getCoordinate(i + 1) * getCoordinate(i + 1);
}
return Math.sqrt(sumOfCoordinatesSquared);
}
private double getDirection2D() {
return Math.atan(getCoordinate(2) / getCoordinate(1));
}
public double[] getDirection() {
if (getCoordinatesLength() != 2 && getCoordinatesLength() != 3) {
throw new IllegalArgumentException("dimention of the vector must be either 2 or 3");
}
int dimention = 0;
if (getCoordinatesLength() == 2) dimention = 1;
else if (getCoordinatesLength() == 3) dimention = 2;
double[] angles = new double[dimention];
if (getCoordinatesLength() == 2) {
angles[0] = Math.atan(getCoordinate(2) / getCoordinate(1));
} else if (getCoordinatesLength() == 3) {
double vectorLength = getLength();
double azimuth = Math.atan(getCoordinate(2) / getCoordinate(1));
double zenith = Math.acos(getCoordinate(3) / vectorLength);
angles[0] = azimuth;
angles[1] = zenith;
}
return angles;
}
public Vector add(Vector otherVector) {
if (getCoordinatesLength() != otherVector.getCoordinatesLength()) {
throw new IllegalArgumentException("length of the vectors must be equal");
}
double[] newCoordinates = new double[getCoordinatesLength()];
for (int i = 0; i < getCoordinatesLength(); i++) {
newCoordinates[i] = getCoordinate(i + 1) + otherVector.getCoordinate(i + 1);
}
return new Vector(newCoordinates);
}
public Vector multiplyByScalar(double scalar) {
double[] newCoordinates = new double[getCoordinatesLength()];
for (int i = 0; i < getCoordinatesLength(); i++) {
newCoordinates[i] = getCoordinate(i + 1) * scalar;
}
return new Vector(newCoordinates);
}
public Vector subtract(Vector otherVector) {
return add(otherVector.multiplyByScalar(-1.0));
}
public boolean isEqual(Vector otherVector) {
if (getCoordinatesLength() != otherVector.getCoordinatesLength()) return false;
for (int i = 0; i < getCoordinatesLength(); i++) {
if (getCoordinate(i + 1) != otherVector.getCoordinate(i + 1)) return false;
}
return true;
}
public double applyDotProduct(Vector otherVector) {
if (getCoordinatesLength() != otherVector.getCoordinatesLength()) {
throw new IllegalArgumentException("length of the vectors must be equal");
}
double dotProduct = 0;
for (int i = 0; i < getCoordinatesLength(); i++) {
dotProduct += getCoordinate(i + 1) * otherVector.getCoordinate(i + 1);
}
return dotProduct;
}
public Vector applyCrossProduct(Vector otherVector) {
if (getCoordinatesLength() != otherVector.getCoordinatesLength()) {
throw new IllegalArgumentException("length of the vectors must be equal");
}
if (getCoordinatesLength() != 3) {
throw new IllegalArgumentException("dimention of the vector must be 3");
}
int x = 1;
int y = 2;
int z = 3;
double newXCoordinate = getCoordinate(y) * otherVector.getCoordinate(z) - getCoordinate(z) * otherVector.getCoordinate(y);
double newYCoordinate = getCoordinate(z) * otherVector.getCoordinate(x) - getCoordinate(x) * otherVector.getCoordinate(z);
double newZCoordinate = getCoordinate(x) * otherVector.getCoordinate(y) - getCoordinate(y) * otherVector.getCoordinate(x);
double[] newCoordinates = {
newXCoordinate,
newYCoordinate,
newZCoordinate
};
return new Vector(newCoordinates);
}
public boolean isPerpendicular(Vector otherVector) {
if (applyDotProduct(otherVector) == 0) return true;
else return false;
}
public boolean isParallel(Vector otherVector) {
double scalingFactor = 0;
for (int i = 0; i < getCoordinatesLength(); i++) {
if (getCoordinate(i + 1) != 0 && otherVector.getCoordinate(i + 1) != 0) {
scalingFactor = getCoordinate(i + 1) / otherVector.getCoordinate(i + 1);
break;
}
}
double[] newCoordinates = new double[getCoordinatesLength()];
for (int i = 0; i < getCoordinatesLength(); i++) {
newCoordinates[i] = getCoordinate(i + 1) / scalingFactor;
}
Vector newVector = new Vector(newCoordinates);
if (otherVector.isEqual(newVector)) return true;
else return false;
}
public String toString() {
String printedCoordinates = "";
for (int i = 0; i < getCoordinatesLength() - 1; i++) {
printedCoordinates += (getCoordinate(i + 1) + ", ");
}
return "[" + printedCoordinates + getCoordinate(getCoordinatesLength()) + "]";
}
public void draw(double originX, double originY, double scaleDownFactor, double arrowHeadSize) {
if (getCoordinatesLength() != 2) {
throw new IllegalArgumentException("dimention of the vector must be 3");
}
double newX = getCoordinate(1) * scaleDownFactor;
double newY = getCoordinate(2) * scaleDownFactor;
double arrowHeadPointX = originX + newX;
double arrowHeadPointY = originY + newY;
StdDraw.line(originX, originY, arrowHeadPointX, arrowHeadPointY);
double arrowHeadBaseX = arrowHeadSize * Math.sin(getDirection2D());
double arrowHeadBaseY = arrowHeadSize * Math.cos(getDirection2D());
double[] arrowHeadXCoordinates = {-arrowHeadBaseX + (originX + 0.95 * newX),
arrowHeadBaseX + (originX + 0.95 * newX),
arrowHeadPointX
};
double[] arrowHeadYCoordinates = {
arrowHeadBaseY + (originY + 0.95 * newY),
-arrowHeadBaseY + (originY + 0.95 * newY),
arrowHeadPointY
};
StdDraw.filledPolygon(arrowHeadXCoordinates, arrowHeadYCoordinates);
}
public static void main(String[] args) {
/*
double[] coordinatesOfVectorA = {1,2};
double[] coordinatesOfVectorB = {0,1};
Vector vectorA = new Vector(coordinatesOfVectorA);
Vector vectorB = new Vector(coordinatesOfVectorB);
double originX = 0.5;
double originY = 0.5;
double scaleDownFactor = 0.1;
double arrowHeadSize = 0.01;
System.out.println("Vector A = " + vectorA.toString());
System.out.println("Vector B = " + vectorB.toString());
System.out.println("A plus B equals " + vectorA.add(vectorB).toString());
System.out.println("A minus B equals " + vectorA.subtract(vectorB).toString());
System.out.println("Dot product of A and B equals " + vectorA.applyDotProduct(vectorB));
//System.out.println("Cross product of A and B equals " + vectorA.applyCrossProduct(vectorB).toString());
System.out.println(vectorA.isParallel(vectorB));
vectorA.draw(originX, originY, scaleDownFactor, arrowHeadSize);
vectorB.draw(originX, originY, scaleDownFactor, arrowHeadSize);
*/
StdDraw.setXscale(-1, 1);
StdDraw.setYscale(-1, 1);
for (int i = -10; i < 11; i++) {
for (int j = -10; j < 11; j++) {
if (i == 0 && j == 0) j++;
double x = 1.0 * i / 10;
double y = 1.0 * j / 10;
double vectorXCoordinate = -y;
double vectorYCoordinate = x;
double[] coordinates = {
vectorXCoordinate,
vectorYCoordinate
};
Vector vector = new Vector(coordinates);
vector.draw(x, y, 0.1, 0.01);
}
}
}
}
</code></pre>
<p><a href="https://introcs.cs.princeton.edu/java/stdlib/javadoc/StdDraw.html" rel="nofollow noreferrer">StdDraw</a> is a simple API written by the authors of the book. I checked my program and it works. Here is one instance of it:</p>
<p>Input (taken from <a href="https://tutorial.math.lamar.edu/classes/calciii/VectorFields.aspx" rel="nofollow noreferrer">here</a>):</p>
<p><a href="https://i.stack.imgur.com/hBvh3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hBvh3.png" alt="enter image description here" /></a></p>
<p>Output:</p>
<p><a href="https://i.stack.imgur.com/Xv0kH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Xv0kH.png" alt="enter image description here" /></a></p>
<p>Is there any way that I can improve my program?</p>
<p>Thanks for your attention.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T21:12:32.750",
"Id": "490281",
"Score": "1",
"body": "Comment from another user who lacks ability to comment currently: \"_The question is very broad and consequently there are many improvements you can make. You will likely get more meaningful answers if you state explicitly what do you want to improve. Some examples are \"I want it to run faster\", \"I want it to be able to manage large datasets\", \"I want to present the solution to students\", etc._\""
}
] |
[
{
"body": "<p>I have some suggestions for your code.</p>\n<h2>Extract the expression to variables when used multiple times.</h2>\n<p>You have multiple instances where you use the method <code>getCoordinatesLength</code> / <code>getCoordinate</code> multiple times in the same method.\nIn your code, you can extract the similar expressions into variables; this will make the code shorter and easier to read.</p>\n<h2>Simplify the boolean conditions.</h2>\n<p>Generally, when you are returning both <code>true</code> and <code>false</code> surrounded by a condition, you know you can refactor the logic of the expression.</p>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>public boolean isPerpendicular(Vector otherVector) {\n if (applyDotProduct(otherVector) == 0) return true;\n else return false;\n}\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>public boolean isPerpendicular(Vector otherVector) {\n return applyDotProduct(otherVector) == 0;\n}\n</code></pre>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>public boolean isParallel(Vector otherVector) {\n //[...]\n if (otherVector.isEqual(newVector)) return true;\n else return false;\n}\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>public boolean isParallel(Vector otherVector) {\n //[...]\n return otherVector.isEqual(newVector);\n}\n</code></pre>\n<h2>Use <code>java.lang.StringBuilder</code> to concatenate String in a loop.</h2>\n<p>It's generally more efficient to use the builder in a loop, since the compiler is unable to optimize it by itself while translating your code into bytecode; The compiler will not use the <code>java.lang.StringBuilder</code> in complex loops and your method will take more time and more memory to execute, since the String Object is immutable (a new instance will be created each iteration).</p>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>public String toString() {\n String printedCoordinates = "";\n for (int i = 0; i < getCoordinatesLength() - 1; i++) {\n printedCoordinates += (getCoordinate(i + 1) + ", ");\n }\n return "[" + printedCoordinates + getCoordinate(getCoordinatesLength()) + "]";\n}\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>public String toString() {\n StringBuilder printedCoordinates = new StringBuilder();\n for (int i = 0; i < getCoordinatesLength() - 1; i++) {\n printedCoordinates.append(getCoordinate(i + 1)).append(", ");\n }\n return "[" + printedCoordinates + getCoordinate(getCoordinatesLength()) + "]";\n}\n</code></pre>\n<h2>Vector#getDirection method</h2>\n<p>This method can be shortened by merging the conditions, using anonymous arrays and in-lining the variables.</p>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>public double[] getDirection() {\n //[...]\n int dimention = 0;\n if (getCoordinatesLength() == 2) dimention = 1;\n else if (getCoordinatesLength() == 3) dimention = 2;\n double[] angles = new double[dimention];\n if (getCoordinatesLength() == 2) {\n angles[0] = Math.atan(getCoordinate(2) / getCoordinate(1));\n } else if (getCoordinatesLength() == 3) {\n double vectorLength = getLength();\n double azimuth = Math.atan(getCoordinate(2) / getCoordinate(1));\n double zenith = Math.acos(getCoordinate(3) / vectorLength);\n angles[0] = azimuth;\n angles[1] = zenith;\n }\n return angles;\n}\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>public double[] getDirection() {\n int coordinatesLength = getCoordinatesLength();\n //[...]\n if (coordinatesLength == 2) {\n return new double[] {Math.atan(getCoordinate(2) / getCoordinate(1))};\n } else if (coordinatesLength == 3) {\n double atan = Math.atan(getCoordinate(2) / getCoordinate(1));\n double acos = Math.acos(getCoordinate(3) / getLength());\n return new double[] {atan, acos};\n } else {\n return new double[0]; // You can also throw an exception, null, etc.\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T22:14:39.253",
"Id": "249972",
"ParentId": "249965",
"Score": "4"
}
},
{
"body": "<p>Knowing that <code>Vector</code> is already a common class in Java, choosing Vector as a name for another class becomes quite confusing. Since this is specifically an <em>Euclidean vector</em>, you should literally name the class as such: <code>EuclideanVector</code>.</p>\n<p>The class is intended to be immutable but it's constructor exposes the internal data structure to external components and allows them to alter the object state after it has been initialized (this is a bug). The input array to constructor should not be stored as such. It should be cloned:</p>\n<pre><code>public Vector(double[] coordinates) {\n this.coordinates = (double[]) coordinates.clone();\n}\n</code></pre>\n<p>The <code>getCoordinatesLength()</code> suggests that the internal implementation is an array or a list but the <code>getCoordinate(int)</code> method requires a 1-based index, instead of being 0-based that is prevalent in everywhere else in Java. The <code>getCoordinatesLength()</code> should be renamed to <code>getComponentCount()</code> and the indexing should be changed to start from 0. That way you save youself from all the "+1,-1"-juggling inside the class.</p>\n<p>Likewise the <code>getCoordinate(int)</code> method should be renamed <code>getComponent(int)</code> as that is the correct mathematical term.</p>\n<p>The <code>getDirection2D()</code> method assumes that vector has at least two components but there is no validation. The user gets an ugly ArrayIndexOutOfBounds error without clarification. Add a check that there are enough components and throw an exception with specific information.</p>\n<p>The <code>Vector</code> class is riddled with the same three magic numbers all over again. Replace numeric constants 1, 2 and 3 with constant fields <code>X</code>, <code>Y</code> and <code>Z</code> and document them so that the user knows the values can be passed to the getComponent(int) method.</p>\n<p>The <code>draw(double, double, double, double)</code> absolutely does not belong in a vector class. Drawing the vector belongs in a UI component, not in a data structure. This violates the <a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"nofollow noreferrer\">single responsibility principle</a>. You should add a dedicated class for drawing an <code>EuclideanVectorField</code>. That might as well be a separate code review.</p>\n<p>I have a feeling that pretty much all of the <code>public</code> methods should also be <code>final</code>. This way your implementation of methods that rely on other methods can not be altered by subclassing and overriding the other methods.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T09:44:36.380",
"Id": "490319",
"Score": "0",
"body": "So draw should be a static method inside a test client? If yes, then why in a turtle graphics class we use draw to make computations simpler? And also could you please explain the last sentence more? Possibly with a before-after example. I appreciate your help."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T09:47:01.397",
"Id": "490320",
"Score": "0",
"body": "I cannot review your turtle graphics example as I don't have code for it, but let me say that just because it was given to you by a professor does not mean it's good code. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T09:49:02.150",
"Id": "490321",
"Score": "0",
"body": "I am self-learning from the above mentioned book. Here is the turtle graphics example https://codereview.stackexchange.com/questions/249564/drawing-dragon-curves-using-turtle-graphics"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T09:54:23.240",
"Id": "490322",
"Score": "1",
"body": "You should check SOLID-principles. It is the single most important thing (or 5 things actually) I have ever learned about software development. https://en.wikipedia.org/wiki/SOLID . You should keep in mind that the code you are given is classroom code which takes shortcuts to make learning easier compared to what you're expected to do once you have graduated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T09:55:50.623",
"Id": "490323",
"Score": "0",
"body": "Oh...! Thank you very much for this clarification. :)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T09:31:39.510",
"Id": "249988",
"ParentId": "249965",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249972",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T16:10:36.237",
"Id": "249965",
"Score": "4",
"Tags": [
"java",
"performance",
"beginner"
],
"Title": "Data-type implementation for vectors and drawing a vector field as a test client"
}
|
249965
|
<p>I have a list of products, I would like to filter that products e.g. by number, price, type etc. using checkboxes, selects and inputs. I get my data from REST API - using query params in GET method. My code is working but I'm wondering how to make it better and cleaner.</p>
<p>First, function in my component which connects with a service</p>
<pre><code> getMethod(): void {
this.listService
.getFilter(
this.FullName,
this.LastName,
this.IP,
this.price,
this.age,
this.dateTo,
this.dateFrom,
this.male,
this.female,
this.kid,
this.group
)
.subscribe(
(data) => {
this.items = data;
},
(error) => (this.errorMsg = error)
);
}
</code></pre>
<p>Next, my service. First I check if all values have some content/set to true etc. Then I put all variables as params and at the end I delete empty variables.</p>
<pre><code> getFilterList(
FullName: string,
LastName: string,
IP: number,
Price: number,
Age: number,
DateTo: string,
DateFrom: string,
Male: boolean,
Female: boolean,
Kid: boolean,
Group: boolean,
): Observable<ClientsAllData> {
let isMale = '';
if (Male=== true) {
isMale= '0';
}
let isFemale= '';
if (Female=== true) {
isFemale = '0';
}
let isKid= '';
if (Kid=== true) {
isKid = '0';
}
{...}
let params = new HttpParams()
.set('FullName', FullName)
.set('LastName', LastName)
.set('IP', IP)
{...}
params = params.delete('FullName', '');
params = params.delete('LastName', '');
params = params.delete('IP', '');
{...}
return this.http.get<any>(
MY_API,
{ params }
);
</code></pre>
<p>Basically that code looks bad, this is my side learning angular project and I couldn't find better way to do it. Could anyone show me how to write it cleaner or maybe better approach for that topic or just send some links, examples? What's the best way to handle query params if there are many of them.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T08:12:36.160",
"Id": "490316",
"Score": "0",
"body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T12:10:10.447",
"Id": "490395",
"Score": "0",
"body": "Why are you deleting the FullName, LastName and IP from the params? Why they are handled differently?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T19:47:49.377",
"Id": "249968",
"Score": "2",
"Tags": [
"javascript",
"typescript",
"angular-2+"
],
"Title": "The best way to handle many, different requests with custom query params"
}
|
249968
|
<p>I'm trying to get an object with <code>ratings</code> and <code>titles</code> properties:</p>
<pre class="lang-js prettyprint-override"><code>{
ratings: [3, 5],
titles: ['Movie1', 'Movie2']
}
</code></pre>
<p>from the following two functions:</p>
<pre class="lang-js prettyprint-override"><code>const getMovies = () => {
return new Promise((resolve) => {
resolve([
{
movieId: 1,
rating: 3
},
{
movieId: 2,
rating: 5
}
]);
});
};
</code></pre>
<pre class="lang-js prettyprint-override"><code>const getTitle = (movieId) => {
return new Promise((resolve, reject) => {
switch (movieId) {
case 1:
resolve({ title: "Movie1" });
break;
case 2:
resolve({ title: "Movie2" });
break;
default:
reject(new Error("404 - movie not found"));
}
});
};
</code></pre>
<p>I'm avoiding <code>async/await</code>, so trying to get that result using <code>then</code>.</p>
<p>Here is my approach:</p>
<pre class="lang-js prettyprint-override"><code>const result = {}
getMovies()
.then((movies) => {
result.ratings = movies.map(({rating}) => rating)
return Promise.all(movies.map(({ movieId }) => getTitle(movieId)));
})
.then((titles) => {
result.titles = titles.map(({title}) => title)
console.log(result)
})
.catch(console.log)
</code></pre>
<p>Can I do this in a better way withou having to nest <code>then</code> inside <code>then</code>? I don't like the use of a external variable to gather my result, but I don't like the nested thens in this other approach:</p>
<pre class="lang-js prettyprint-override"><code>getMovies()
.then((movies) => {
Promise.all(movies.map(({ movieId }) => getTitle(movieId)))
.then((titles) => {
console.log({
ratings: movies.map(({rating}) => rating),
titles: titles.map(({title}) => title),
})
})
.catch(console.log)
})
.catch(console.log)
</code></pre>
<p>How can I improve this using <code>then</code> and not <code>async/await</code>?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T22:43:51.333",
"Id": "490286",
"Score": "0",
"body": "About `getMovies`: what is returned?\nAn object like this: `{movieId:..., title:..., rating:...}`?\nIf you code it, how do you decide those values?\nI'm confused...\nAnd the object you are trying to get, why not: `movies={movieId001:{title:\"some title\", rating:some rating}, movieId002:{title........},...}`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T22:50:36.200",
"Id": "490287",
"Score": "1",
"body": "I'm also curious about the avoidance of async/await for the inner Promise.all for the titles, or just in general. What is the reason for not wanting to use async/await?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T23:59:26.997",
"Id": "490291",
"Score": "0",
"body": "This is just a contrived example; I'm doing this as an exercise to get a better understanding of the use of `then` with promises."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T03:16:20.017",
"Id": "490293",
"Score": "0",
"body": "Promises exist so you can deal with asynchronous code. You will hardly get any understanding of them if you only try to use it with synchronous code. Writing synchronous code with promises is probably only useful for stubs - to fullfill an interface. Otherwise it Is just unnecesary burden and any sane reviewer will first of all tell you to not use promises for synchronous code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T11:49:05.733",
"Id": "490326",
"Score": "1",
"body": "@slepic I never said I'm doing this to get a better understanding of promises, I said I'm doing this _to get a better understanding of the use of `then`_. Anyway, thanks for your input."
}
] |
[
{
"body": "<p>You could do like so if you prefer, essentially just pass forward the data i the promises. You could write your own promiseAllObject if you want it to be slightly neater.</p>\n<pre><code>const result = getMovies()\n .then(movies => {\n return Promise.all([\n Promise.all(movies.map(({ movieId }) => getTitle(movieId))),\n movies.map(_ => _.rating)\n ]);\n })\n .then(([titlesObj, ratings]) => ({\n titles: titlesObj.map(_ => _.title),\n ratings\n }))\n .catch(console.log);\n\nresult.then(r => console.log(r));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T00:03:18.117",
"Id": "490292",
"Score": "0",
"body": "Nice! Thanks, this is really helpful, I appreciate a lot you took the time to provide this feedback."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T23:38:03.737",
"Id": "249976",
"ParentId": "249971",
"Score": "5"
}
},
{
"body": "<p>The premise of your question indicates that you've identified one of the flaws of promises.</p>\n<p>Asynchronous code like this should return an observable which you can then <em>choose</em> to convert to a promise. When it's an observable you can use the full range of operators available in RxJs, make the changes you need in that pipeline, and <em>then</em> finish off with a <code>toPromise()</code>.</p>\n<p>Apologies, but I don't have an environment available to put together an example and reactive programming is challenging even with an IDE. I would simply recommend you learn about <a href=\"https://gist.github.com/staltz/868e7e9bc2a7b8c1f754\" rel=\"nofollow noreferrer\">observables and reactive programming</a>. Once you understand that, promises become trivial.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T12:36:03.430",
"Id": "249993",
"ParentId": "249971",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "249976",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T21:26:57.010",
"Id": "249971",
"Score": "4",
"Tags": [
"javascript",
"promise"
],
"Title": "Passing data from one promise to another using then"
}
|
249971
|
<p>I am new to Java.
My task is to create a <code>SequentalWriter</code> class and a <code>SequentalReader</code> class that implement the <em>Runnable</em> interface. They must provide a sequence of write-read operations (i.e., write-read-write-read-write-read, etc.).</p>
<p><strong>The task assumes only the use of "synchronized", "notify" and "wait".</strong></p>
<p>I would like to know if something needs to be changed or I have any unknown bugs?</p>
<pre><code>import java.lang.Thread;
import vectors.Array; /* My array implementation */
import vectors.CircularLinkedList; /* My list implementation */
import vectors.IVector; /* The interface that Array and CircularLinkedList implement */
public class Task7Part2 {
volatile int a = 0;
public static void main(String[] args) {
IVector arr1 = new Array(2);
System.out.print("[Test] arr1: "); arr1.print();
Keeper keeperArr1 = new Keeper(arr1);
SequentalWriter seqWriter = new SequentalWriter(keeperArr1);
SequentalReader seqReader = new SequentalReader(keeperArr1);
(new Thread(seqWriter)).start();
(new Thread(seqReader)).start();
// Sleep
try {
Thread.sleep(100);
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
IVector arr2 = new Array(3);
System.out.print("[Test] arr2: "); arr2.print();
Keeper keeperArr2 = new Keeper(arr2);
seqWriter = new SequentalWriter(keeperArr2);
seqReader = new SequentalReader(keeperArr2);
(new Thread(seqWriter)).start();
(new Thread(seqReader)).start();
// Sleep
try {
Thread.sleep(100);
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
IVector list = new CircularLinkedList(4);
System.out.print("[Test] list: "); list.print();
Keeper keeperList = new Keeper(list);
seqWriter = new SequentalWriter(keeperList);
seqReader = new SequentalReader(keeperList);
(new Thread(seqWriter)).start();
(new Thread(seqReader)).start();
}
public static class Keeper {
public volatile IVector vector;
public volatile boolean isWrite;
public Keeper(IVector vector) {
this.vector = vector;
this.isWrite = true;
}
}
public static class SequentalWriter implements Runnable {
public SequentalWriter(Keeper keeper) {
this.keeper = keeper;
}
public void run() {
try {
for (int i = 0, size = keeper.vector.size(); i < size; ++i) {
double d = Math.random();
synchronized(keeper) {
while (!keeper.isWrite) {
keeper.wait();
}
keeper.vector.set(i, d);
System.out.println("Write: " + d + " to position " + i);
keeper.isWrite = false;
keeper.notify();
}
}
} catch (Exception e) {
System.out.println(e.toString());
}
}
private Keeper keeper;
}
public static class SequentalReader implements Runnable {
public SequentalReader(Keeper keeper) {
this.keeper = keeper;
}
public void run() {
try {
for (int i = 0, size = keeper.vector.size(); i < size; ++i) {
synchronized(keeper) {
while (keeper.isWrite) {
keeper.wait();
}
System.out.println("Read: " + keeper.vector.get(i) + " from position " + i);
keeper.isWrite = true;
keeper.notify();
}
}
} catch (Exception e) {
System.out.println(e.toString());
}
}
private Keeper keeper;
}
}
</code></pre>
<p>Expected behavior:</p>
<pre><code>[Test] arr1: 0.0 0.0
Write: 0.11832270210075957 to position 0
Read: 0.11832270210075957 from position 0
Write: 0.18019604451043925 to position 1
Read: 0.18019604451043925 from position 1
[Test] arr2: 0.0 0.0 0.0
Write: 0.9208224707735939 to position 0
Read: 0.9208224707735939 from position 0
Write: 0.5204299894796229 to position 1
Read: 0.5204299894796229 from position 1
Write: 0.6221915557485913 to position 2
Read: 0.6221915557485913 from position 2
[Test] list: 0.0 0.0 0.0 0.0
Write: 0.2718292615666258 to position 0
Read: 0.2718292615666258 from position 0
Write: 0.5589338156490498 to position 1
Read: 0.5589338156490498 from position 1
Write: 0.11919746734454817 to position 2
Read: 0.11919746734454817 from position 2
Write: 0.7266106446478366 to position 3
Read: 0.7266106446478366 from position 3
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T05:14:06.133",
"Id": "249978",
"Score": "2",
"Tags": [
"java",
"beginner",
"multithreading",
"thread-safety"
],
"Title": "Sequential writing and reading (two threads)"
}
|
249978
|
<p>I have below route. I am using Laravel 8.</p>
<pre><code>Route::post('/update-crew',
array(
'uses' => 'App\Http\Controllers\Directory\Crew\API\CrewAPIController@Update',
'as' => 'apiUpdateCrew',
)
);
</code></pre>
<p>Is there any way to use namespace instead of writing the path in string. My route contains both <code>uses</code> and <code>as</code>.</p>
<p>can I improve the code by keeping the <code>uses</code> and <code>as</code> and instead of string path, can I use namespace something like below?</p>
<pre><code>use App\Http\Controllers\Directory\Crew\API\CrewAPIController;
Route::post('/update-crew',
array(
'uses' => ['CrewAPIController', 'Update'],
'as' => 'apiUpdateCrew',
)
);
</code></pre>
<p>Is this possible?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T23:58:59.103",
"Id": "490458",
"Score": "0",
"body": "I rolled back your last edit. After getting an answer you are not allowed to change your code anymore. This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). See the section _What should I not do?_ on [_What should I do when someone answers my question?_](https://codereview.stackexchange.com/help/someone-answers) for more information"
}
] |
[
{
"body": "<p>I recently heard about Laravel 8 changing the way routing was declared, as <a href=\"https://www.youtube.com/watch?v=MfE1tnMG6fE\" rel=\"nofollow noreferrer\"><strong>this video explains</strong></a> that developers upgrading from Laravel 7 or earlier will need to either switch to using the PHP callable syntax or fully namespace the controller in the string syntax (as your first code snippet does) (see the section <strong>Routing</strong> under <a href=\"https://laravel.com/docs/8.x/upgrade#upgrade-8.0\" rel=\"nofollow noreferrer\">Upgrading To 8.0 From 7.x</a>).</p>\n<p>Yes adding that <code>use</code> statement at the top then you should be able to reference the class without the namespace before it.</p>\n<p>You can use the <a href=\"https://www.php.net/manual/en/language.oop5.basic.php#language.oop5.basic.class.class\" rel=\"nofollow noreferrer\"><code>::class</code> keyword</a> for name resolution instead of using a string literal:</p>\n<pre><code>'uses' => [CrewAPIController::class, 'Update'], \n</code></pre>\n<p>Many populate IDEs will index the class names and allow you to then easily jump to the class definition -e.g. ctrl/command + click on name).</p>\n<hr />\n<p>I also wasn't familiar with the <code>'as'</code> syntax, then I found <a href=\"https://stackoverflow.com/questions/30860914/what-does-as-keyword-mean-in-laravel-routing#comment91142021_30860980\">this comment</a> on <a href=\"https://stackoverflow.com/a/30860980/1575353\">this accepted SO answer</a> to <a href=\"https://stackoverflow.com/q/30860914/1575353\"><em>What does “as” keyword mean in Laravel routing?</em></a></p>\n<blockquote>\n<p>As keyword is in older version, if you change the documentation to 5.2 you can see the <code>as</code> keyword. In newer version it's <code>->name</code></p>\n</blockquote>\n<p>So you could use the <a href=\"https://laravel.com/api/8.x/Illuminate/Routing/Route.html#method_name\" rel=\"nofollow noreferrer\"><code>name()</code></a> method to make the <a href=\"https://laravel.com/docs/8.x/routing#named-routes\" rel=\"nofollow noreferrer\">Named route</a> instead:</p>\n<pre><code>Route::post('/update-crew', [CrewAPIController::class, 'Update'])\n ->name('apiUpdateCrew');\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T15:31:36.930",
"Id": "250001",
"ParentId": "249980",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "250001",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T05:45:10.663",
"Id": "249980",
"Score": "2",
"Tags": [
"php",
"laravel",
"url-routing"
],
"Title": "Route Improvement in Laravel 8"
}
|
249980
|
<p>I need to convert my model to fit data in tableview cell finding better approach</p>
<pre><code>My Model
class MyResponseModel {
var question: String = ""
var id: String = ""
var answer: String = ""
//Other variables also but not required to display
init(fromDictionary dictionary: [String:Any]) {
self.question = (dictionary["question"] as? String) ?? ""
self.id = (dictionary["id"] as? String) ?? ""
self.answer = (dictionary["answer"] as? String) ?? ""
}
//MARK: Converting model to cell data
func toModel() -> MyTblCellDetail {
return MyTblCellDetail(title:self.question,detail:self.answer)
}
}
//MARK: Initialize cell data with custom model
struct MyTblCellDetail {
var title: String = ""
var detail: String = ""
var isSelected:Bool = false
init(title:String,detail:String) {
self.title = title
self.detail = detail
}
init(data:MyResponseModel) {
self.title = data.question
self.detail = data.answer
}
}
</code></pre>
<blockquote>
<p>Note: I am reusing same cell to display most of the data so i will use
the same method to converting all class model to MyTblCellDetail
struct</p>
</blockquote>
<p>So my question is which is better way to do the same or any other approach i can use for the same. Thank you!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-09T20:45:04.740",
"Id": "491383",
"Score": "0",
"body": "I would consider replacing `MyTblCellDetail` entirely with a protocol. `MyResponseModel` then conforms to that protocol by providing computed properties called `table`, `detail` and `isSelected`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T11:45:41.547",
"Id": "491408",
"Score": "0",
"body": "myResponsemodel is just for demo there are too many responses can you explain more"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T13:19:14.547",
"Id": "491423",
"Score": "0",
"body": "Make a protocol, and make all of your models conform to it. https://docs.swift.org/swift-book/LanguageGuide/Protocols.html"
}
] |
[
{
"body": "<p>Here is suggestions. Every approach has pros/cons, depending your app architecture and model complexity.</p>\n<pre><code>class MyResponseModel {\n // I think values in response model should be let instead of var\n // By definition response model should be immutable\n let question: String\n let id: String\n let answer: String\n\n // I guess MyResponseModel will be initialized from JSON and you can just conform it to Codable\n // Then you don't need this init(from dictionary: [String: Any])\n init(from dictionary: [String: Any]) {\n self.question = (dictionary["question"] as? String) ?? ""\n self.id = (dictionary["id"] as? String) ?? ""\n self.answer = (dictionary["answer"] as? String) ?? ""\n }\n}\n\nstruct MyTableCellViewModel {\n // I'm not sure what logic do you have, but I think it is better to define properties using let instead of var\n let title: String\n let detail: String\n let isSelected: Bool\n\n init(title: String, detail: String, isSelected: Bool) {\n self.title = title\n self.detail = detail\n self.isSelected = isSelected\n }\n\n // Approach #1: create initializer from necessary response model\n init(responseModel: MyResponseModel, isSelected: Bool) {\n self.init(title: responseModel.question, detail: responseModel.answer, isSelected: isSelected)\n }\n}\n\n// Approach #2: create separate mapper class (useful when you need to have external dependencies in order to map\n// For example you need to add some info that is not relevant to MyResponseModel.\n// Let's take cell selection info as an example\n\nprotocol MyTableCellSelectionProvider {\n func isCellSelected(for responseModel: MyResponseModel) -> Bool\n}\n\nstruct MyTableCellViewModelMapper {\n let cellSelectionProvider: MyTableCellSelectionProvider\n\n func map(responseModel: MyResponseModel) -> MyTableCellViewModel {\n return MyTableCellViewModel(\n title: responseModel.question,\n detail: responseModel.answer,\n isSelected: cellSelectionProvider.isCellSelected(for: responseModel)\n )\n }\n}\n\n// Approach #3: define cell view model protocol\n\nprotocol MyCellViewModel {\n var title: String { get }\n var detail: String { get }\n}\n\nextension MyResponseModel: MyCellViewModel {\n var title: String { return question }\n var detail: String { return answer }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T06:50:50.600",
"Id": "259229",
"ParentId": "249981",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T07:15:18.027",
"Id": "249981",
"Score": "2",
"Tags": [
"swift",
"ios",
"mvvm"
],
"Title": "Which is better-way to casting model"
}
|
249981
|
<p>I am cleaning str columns in a Pandas dataframe (see below for an example), and I have been wondering if there are more concise ways or additional inplace methods to do so. What are the general best practices for cleaning columns in Pandas?</p>
<pre><code>import pandas as pd
df = pd.DataFrame.from_dict({"col1": [0, 1, 2, 3], "col2": ["abcd efg", ".%ues", "t12 ^&3", "yupe"]})
df["col2"] = df["col2"].str.lower()
df["col2"] = df["col2"].str.strip()
df["col2"].replace(to_replace="[^a-zA-Z ]", value="", regex=True, inplace=True)
</code></pre>
|
[] |
[
{
"body": "<p>This is not too bad. It's a good thing you use keyword arguments for the <code>replace method</code></p>\n<p>I always try to keep my original data in its original state, and continue with the cleaned dataframe.</p>\n<h1>fluent style</h1>\n<p>This lends itself very well to a kind of fluent style as in <a href=\"https://github.com/psf/black/blob/master/docs/the_black_code_style.md#call-chains\" rel=\"nofollow noreferrer\">this example</a>. I use it too, and use a lot of <code>df.assign</code>, <code>df.pipe</code>, <code>df.query</code>...</p>\n<p>In this example I would do something like</p>\n<pre><code>df_cleaned = df.assign(\n col2=(\n df["col2"]\n .str.lower()\n .str.strip()\n .replace(to_replace="[^a-zA-Z ]", value="", regex=True)\n )\n)\n</code></pre>\n<p>So definately no <code>inplace</code> replacements</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T11:19:57.047",
"Id": "249991",
"ParentId": "249982",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249991",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T07:32:08.277",
"Id": "249982",
"Score": "4",
"Tags": [
"python",
"pandas"
],
"Title": "Best practice for cleaning Pandas dataframe columns"
}
|
249982
|
<p><strong>Goal:</strong></p>
<p>Look for a substring match within a text for given Keywords. Keep the substring match if the levenshtein distance is smaller than the length of the Keyword divided by (x=10), else return an empty list.</p>
<p>(First of all my apologies if the code is of lower quality. I am quite good in R but very new to Python.)</p>
<p><strong>Current implementation:</strong></p>
<pre><code>from fuzzywuzzy import process
from fuzzysearch import find_near_matches
import math
def fuzzy_extract(qs, ls, threshold, max_dist):
ret = []
for word, _ in process.extractBests(qs, (ls,), score_cutoff = threshold):
for match in find_near_matches(qs, word, max_l_dist = max_dist):
word = word[match.start:match.end]
ret.append({"kw": qs, "word": word, "dist": match.dist})
return(ret)
def get_match(text, keywords, treshold):
keywords = [keyword.lower() for keyword in keywords]
text = text.lower()
candidates = []
for li in [fuzzy_extract(query_string, text, 0, 1) for query_string in keywords]:
if len(li) > 0:
for di in li:
if di["dist"] <= math.ceil(len(di["word"])/treshold):
candidates.append(di)
if(len(candidates) == 0):
return([])
out = str(candidates[0]["kw"])
return(out)
keywords = ["apple", "banana", "cherry"]
text = "nana is Looking for an aple."
print(get_match(text, keywords, 10))
</code></pre>
<p>For me the part in the middle looks neither efficient and also not very declarative.
With part in the middle i mean the Code following:</p>
<pre><code>for li in [fuzzy_extract(query_string, text, 0, 1) for query_string in keywords]:
</code></pre>
<p>I started with something longer but more declarative:</p>
<pre><code>candidates = [fuzzy_extract(query_string, ocr_text, 0, 1) for query_string in keywords_ordering]
lens = [len(candidate) > 0 for candidate in candidates]
candidate_lengths = list(compress(candidates, lens))
filtered = [candidate_length[0]["dist"] < math.ceil(len(candidate_length[0]["word"])/10) for candidate_length in candidate_lengths]
candidate_filtered = list(compress(candidate_lengths, filtered))
</code></pre>
<p>In R i would make usage of pipes for These cases to avoid the undeclarative variables in between.</p>
<p><strong>Similar Topics:</strong></p>
<p><a href="https://codereview.stackexchange.com/questions/215174/find-a-best-fuzzy-match-for-a-string">Find a best fuzzy match for a string</a></p>
<p>(Difference is that in this question match candidates are compared to a single word and to a substring of a text).</p>
<p><a href="https://stackoverflow.com/a/36132391/3502164">https://stackoverflow.com/a/36132391/3502164</a></p>
<p>Custom implementation, rather long.</p>
|
[] |
[
{
"body": "<h1>Unnecessary parentheses</h1>\n<p>Switch the following:</p>\n<pre><code>return(...) -> return ...\nif(...) -> if ...\n</code></pre>\n<p>You switch between the two, probably due to coming from another language. Just try to be consistent and don't use parentheses if you don't have to.</p>\n<h1>Type Hints</h1>\n<p>You can use type hints to display what types of parameters are accepted, and what types of values are returned, if any.</p>\n<pre><code>def fuzzy_extract(query_string: str, match_string: str, threshold: int, max_dist: int):\ndef get_match(text: str, keywords: List[str], threshold: int):\n</code></pre>\n<p><em>The <code>List</code> is imported by <code>from typing import List</code></em></p>\n<h1>Simplify your loops</h1>\n<p>Instead of checking <code>if len(li) > = 0</code>, you can do that check inside the list comprehension. Also, I would move that outside of the loop into its own variable.</p>\n<pre><code>extracted = [fuzzy_extract(query_string, text, 0, 1) for query_string in keywords if len(query_string) > 0]\n</code></pre>\n<h1>Empty lists</h1>\n<p>Instead of checking if the length of the list is 0, simply check if the list is <code>None</code>. An empty list is implicitly <code>None</code>.</p>\n<pre><code>if not candidates:\n</code></pre>\n<h1>Default Parameters</h1>\n<p>When passing default parameters, there shouldn't be a space before or after the <code>=</code>.</p>\n<pre><code>for word, _ in process.extractBests(query_string, (match_string,), score_cutoff=threshold):\n for match in find_near_matches(query_string, word, max_l_dist=max_dist):\n</code></pre>\n<h1>Final Code</h1>\n<pre><code>from fuzzywuzzy import process\nfrom fuzzysearch import find_near_matches\nimport math\n\nfrom typing import List\n\ndef fuzzy_extract(query_string: str, match_string: str, threshold: int, max_dist: int):\n matches = []\n for word, _ in process.extractBests(query_string, (match_string,), score_cutoff=threshold):\n for match in find_near_matches(query_string, word, max_l_dist=max_dist):\n word = word[match.start:match.end]\n matches.append({"kw": query_string, "word": word, "dist": match.dist})\n return matches\n\ndef get_match(text: str, keywords: List[str], threshold: int):\n keywords = [keyword.lower() for keyword in keywords]\n text = text.lower()\n\n canidates = []\n extracted = [fuzzy_extract(query_string, text, 0, 1) for query_string in keywords if len(query_string) > 0]\n for item in extracted:\n for di in item:\n if di["dist"] <= math.ceil(len(di["word"]) / threshold):\n canidates.append(di)\n\n if not canidates:\n return []\n\n result = str(canidates[0]["kw"])\n return result\n\nkeywords = ["apple", "banana", "cherry"]\ntext = "nana is Looking for an aple."\n\nprint(get_match(text, keywords, 10))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T07:01:30.560",
"Id": "490375",
"Score": "0",
"body": "I would make `extracted` a generator instead of a list. Also, it seems odd to return `[]` for no match. I'd return `None` or an empty str."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T09:19:59.273",
"Id": "249987",
"ParentId": "249983",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T07:36:21.293",
"Id": "249983",
"Score": "4",
"Tags": [
"python"
],
"Title": "Substring match within a text for given keywords"
}
|
249983
|
<p>I'm doing assembly language problems on CodeWars, a website with practice problems.</p>
<h2>Problem</h2>
<p><a href="https://www.codewars.com/kata/545991b4cbae2a5fda000158/train/nasm" rel="nofollow noreferrer">https://www.codewars.com/kata/545991b4cbae2a5fda000158/train/nasm</a></p>
<blockquote>
<p>Create a method that accepts a list and an item, and returns true if the item belongs to the list, otherwise false.</p>
</blockquote>
<h2>Solution In C</h2>
<p>To give you an idea what the assembly code will be doing.</p>
<pre><code>#include <stdbool.h>
#include <stddef.h>
bool include(const int* arr, size_t size, int item)
{
int i = 0;
loop:
if ( i < size ) {
if ( arr[i] == item ) {
return true;
}
i++;
goto loop;
}
return false;
}
</code></pre>
<h2>Solution In NASM Assembly (Linux x64)</h2>
<p>CodeWars provided the 7 lines at the top.</p>
<pre><code>SECTION .text
global include
include:
; bool include(const int* arr, size_t size, int item)
; sizeof(int) = 4 bytes (32bit)
; sizeof(size_t) = 8 bytes (64bit)
;rdi = &arr pointer, 8 bytes
; arr[i] signed int, 4 bytes (dd)
;rsi = size size_t, unsigned int, 8 bytes
;edx = item signed int, 4 bytes
; Avoid using registers that we need to preserve (RBX, RBP, R12-R15). Else we'd have to push and pop them onto the stack.
mov rcx, 0 ; unsigned int i = 0;
loop1:
cmp rcx, rsi ; if ( i < size ) {
jae skip_loop
mov r8d, [rdi + 4 * rcx] ; make a temp variable so we can see this in step debugging
cmp edx, r8d ; if ( arr[i] == item ) {
jne skip_if
mov rax, 1 ; return true;
ret
skip_if:
inc rcx ; i++;
jmp loop1
skip_loop:
mov rax, 0 ; return false;
ret
</code></pre>
<h2>Questions</h2>
<p>I'm brand new to assembly. Any feedback on patterns and best practices would be appreciated. For example</p>
<ul>
<li>Is there a standard pattern to use when writing loops?</li>
<li>Is there a standard pattern to use when writing if/elseif/else?</li>
<li>Are there better word choices and formatting for the labels?</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-04T19:47:51.693",
"Id": "490813",
"Score": "0",
"body": "\"CodeWars provided the **6** lines at the top.\" Do you skip blank lines when numbering/counting? Is `;rdi = &arr pointer, 8 bytes` the first line line that you wrote yourself? It's not readily clear."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-05T06:58:53.233",
"Id": "490853",
"Score": "0",
"body": "Yes and yes. I'll edit for clarity."
}
] |
[
{
"body": "<p>First of all, props for the copious comments, particularly how you included a representation in C. The C representation itself has a signed vs unsigned comparison, which can cause <a href=\"https://blog.regehr.org/archives/268\" rel=\"nofollow noreferrer\">weird bugs</a> when and where you don't expect them, but I'm going to stick to the assembly code itself in this review. I would just recommend declaring the loop counter <code>i</code> as <code>size_t</code>, since that's what the type of the stop condition is.</p>\n<p>I assembled your C function using gcc version 10.2.0 with <code>-O3 -march=native</code>, so I'll include the output here so I can walk through it step by step, comparing the two implementations. This is a really good idea, by the way, because working backwards through what the C compiler did helps you see real assembly language, not just practice examples you wrote. <a href=\"https://godbolt.org/\" rel=\"nofollow noreferrer\">Compiler Explorer</a> is a great tool for this.</p>\n<p>Anyways, here is my input file.</p>\n<pre><code>#include <stdbool.h>\n#include <stddef.h>\n\nbool include(const int* arr, size_t size, int item) {\n for (size_t i = 0; i < size; ++i) {\n if (arr[i] == item) {\n return true;\n }\n }\n\n return false;\n}\n</code></pre>\n<p>To assemble it, I use the following command. Note the <code>-masm=intel</code> argument; the default assembly syntax is <code>AT&T</code> for GNU tools.</p>\n<pre><code>gcc -S -O3 -march=native -masm=intel -o output.asm input.c\n</code></pre>\n<p>You can filter out auxiliary metadata and its containing labels using the following command.</p>\n<pre><code>cat output.asm | sed -E '/^\\s+\\./d;/^\\.L[A-Z]/d'\n</code></pre>\n<p>And here is my output.</p>\n<pre><code>include:\n test rsi, rsi\n je .L4\n xor eax, eax\n jmp .L3\n.L8:\n inc rax\n cmp rsi, rax\n je .L4\n.L3:\n cmp DWORD PTR [rdi+rax*4], edx\n jne .L8\n mov eax, 1\n ret\n.L4:\n xor eax, eax\n ret\n</code></pre>\n<p>Notice that the first line is already different. In your version, you started by setting the <code>rcx</code> register to <code>0</code>, using the <code>mov</code> instruction, whereas the compiler output <code>test rsi, rsi</code>. Why?</p>\n<p>Well, as you noted, Intel x86-64 Linux assembly programming <a href=\"https://raw.githubusercontent.com/wiki/hjl-tools/x86-psABI/x86-64-psABI-1.0.pdf#Hfootnote.18\" rel=\"nofollow noreferrer\">calling convention</a> dictates that the <code>rsi</code> register contains the second argument to your function, in this case the size of the array.\nFrom the <a href=\"https://software.intel.com/content/dam/develop/public/us/en/documents/325462-sdm-vol-1-2abcd-3abcd.pdf\" rel=\"nofollow noreferrer\">Intel x86-64 documentation</a> (pg. 1866), the <code>test</code> instruction performs a logical AND test on its arguments. If the result is zero, it sets the zero flag <code>ZF</code> equal to <code>1</code>. The following instruction therefore makes sense, since the "jump near if equal" (<code>je</code>) instruction is carried out when the the zero flag is set (<code>ZF=1</code>).</p>\n<p>In other words, the subroutine begins by checking whether or not the input array actually contains any items before actually doing anything with it. Note that you weren't checking for this edge case in your original code (nor did you verify the array pointer wasn't <code>NULL</code>), and it's a great example of compilers being awesome. Matt Godbolt (the guy who made Compiler Explorer) has <a href=\"https://www.youtube.com/watch?v=bSkpMdDe4g4\" rel=\"nofollow noreferrer\">an awesome talk</a> about this kind of stuff that I highly recommend you check out if you like this sort of thing.</p>\n<p>Anyways, if you look at the <code>.L4</code> label, you'll notice it's semantically equivalent to your <code>skip_loop</code>. However, you literally set the <code>rax</code> register (i.e., the return value of the function) equal to zero by <code>mov</code>ing a <code>0</code> into it, whereas the compiler uses the exclusive-or <code>xor</code> instruction on <code>eax</code> with itself, which will obviously always be zero. You're not semantically wrong for doing it the way you did, but you can read <a href=\"https://stackoverflow.com/questions/33666617/what-is-the-best-way-to-set-a-register-to-zero-in-x86-assembly-xor-mov-or-and\">this SO post</a> that describes in significant detail why you should opt for the <code>xor eax, eax</code> method. The short version is that it's more efficient, and the longer version is that it's <em>much</em> more efficient, but there are other benefits, like power consumption. That post goes into a <strong>lot</strong> more detail, though, and it's a great read.</p>\n<p>Your loop itself looks okay to me. The compiler used the <code>rax</code> register for the loop counter, which both you and the compiler then used to get the value of the array at the appropriate index. The only real difference between the two versions is that the compiler used an unconditional jump <code>jmp</code> instruction to skip the first part of its main loop, which contained the loop counter increment, whereas your code had that last.</p>\n<p>I genuinely don't think this difference has any real impact, because both implementations contain two conditional jumps, which significantly impact performance because they trigger unconditional instruction fetches and involve more advanced processor features like <a href=\"https://stackoverflow.com/questions/11227809/why-is-processing-a-sorted-array-faster-than-processing-an-unsorted-array\">branch prediction</a>, which itself introduces problems via an optimization called <a href=\"https://en.wikipedia.org/wiki/Speculative_execution\" rel=\"nofollow noreferrer\">speculative execution</a>. (Long story short, optimization is complicated, you won't really know until you profile it, and you <a href=\"https://softwareengineering.stackexchange.com/questions/80084/is-premature-optimization-really-the-root-of-all-evil\">probably shouldn't even care about optimization until you have a working <em>something</em> to optimize</a>, but you're "probably" fine.)</p>\n<p>Something I found really interesting (although not particularly impactful or world-view shattering), was that believe it or not, creating that temporary variable and <em>then</em> comparing takes exactly as many bytes to encode as the direct comparison the compiler output in my version.</p>\n<p>Here is a snippet from the <code>objdump</code> output for your version. (To generate this on your local machine, the command I used after assembling with nasm was <code>objdump -Mx86-64,intel -D -S -s input.o</code>.)</p>\n<pre><code>0000000000000005 <loop1>:\nloop1:\n cmp rcx, rsi ; if ( i < size ) {\n 5: 48 39 f1 cmp rcx,rsi\n jae skip_loop\n 8: 73 14 jae 1e <skip_loop>\n \n mov r8d, [rdi + 4 * rcx] ; make a temp variable so we can see this in step debugging\n a: 44 8b 04 8f mov r8d,DWORD PTR [rdi+rcx*4]\n cmp edx, r8d ; if ( arr[i] == item ) {\n e: 44 39 c2 cmp edx,r8d\n jne skip_if\n 11: 75 06 jne 19 <skip_if>\n mov rax, 1 ; return true;\n 13: b8 01 00 00 00 mov eax,0x1\n ret\n 18: c3 ret \n</code></pre>\n<p>Now here's a snippet from the output for the compiler's version that contains the comparison operation.</p>\n<pre><code>0000000000000011 <include.L3>:\n.L3:\n cmp [dword rdi+rax*4], edx\n 11: 39 94 87 00 00 00 00 cmp DWORD PTR [rdi+rax*4+0x0],edx\n jne .L8\n 18: 75 ef jne 9 <include.L8>\n mov eax, 1\n 1a: b8 01 00 00 00 mov eax,0x1\n ret\n 1f: c3 ret \n</code></pre>\n<p>Notice how in your version, the assignment to a temporary variable takes four bytes. You specified the <code>r8d</code> register as the destination register, so this isn't exactly groundbreaking stuff, but the following comparison instruction required only three bytes to encode:</p>\n<pre><code>44 8b 04 8f mov r8d,DWORD PTR [rdi+rcx*4]\n44 39 c2 cmp edx,r8d\n</code></pre>\n<p>The compiler's version skipped the intermediate variable assignment, but the resulting instruction required seven bytes to encode.</p>\n<pre><code>39 94 87 00 00 00 00 cmp DWORD PTR [rdi+rax*4+0x0],edx\n</code></pre>\n<p>To explain why those extra zeroes at the end matter, I will borrow once again from <a href=\"https://stackoverflow.com/questions/33666617/what-is-the-best-way-to-set-a-register-to-zero-in-x86-assembly-xor-mov-or-and\">this great post which you should definitely read</a>.</p>\n<blockquote>\n<p>Smaller machine-code size [...] is always an advantage: Higher code density leads to fewer instruction-cache misses, and better instruction fetch and potentially decode bandwidth.</p>\n</blockquote>\n<p>To really drive this point home, let us read the <a href=\"https://software.intel.com/content/www/us/en/develop/articles/intel-sdm.html\" rel=\"nofollow noreferrer\">conditional jump instruction documentation</a> (pg. 1109 in the combined manual [vols 1-4]):</p>\n<blockquote>\n<p>All conditional jumps are converted to code fetches of one or two cache lines, regardless of jump address or cache-ability.</p>\n</blockquote>\n<p>I now leave this link to the <a href=\"https://gist.github.com/jboner/2841832\" rel=\"nofollow noreferrer\">latency numbers every programmer should know</a> for your edification, although it should be noted this document is from 2012. <a href=\"https://colin-scott.github.io/personal_website/research/interactive_latency.html\" rel=\"nofollow noreferrer\">Here's a cool updated version</a> where you can look at the latency numbers by year (including 2020), but I actually just found this myself, so I admit I haven't vetted the source for accuracy. I am including it for completeness nonetheless.</p>\n<p>As far as the labels themselves are concerned, since <code>loop1</code>, <code>skip_if</code>, and <code>skip_loop</code> are all logically related to the <code>include</code> subroutine, I would recommend using <a href=\"https://www.nasm.us/xdoc/2.15.05/html/nasmdoc3.html#section-3.9\" rel=\"nofollow noreferrer\">local labels</a> to more intuitively organize your assembly code. Local labels are particularly useful because the subroutine name serves as a sort of namespace, allowing you to reuse the local label names defined therein. You can see the <code>include</code> version above assembled by gcc uses local labels.</p>\n<p>The only recommendation I would make regarding loops is to be wary of using the right conditional jump for your situation. From the documentation:</p>\n<blockquote>\n<p>The terms "less" and "greater" are used for comparisons of signed integers and the terms "above" and "below" are used for unsigned integers.</p>\n</blockquote>\n<p>This isn't pedantry, either. Take for example, the "jump if above or equal" <code>jae</code> instruction in your code. It follows a <code>cmp</code> instruction, which subtracts the second operand from the first and modifies the <code>EFLAGS</code> register accordingly. Specifically, the intermediate <code>sub</code> instruction performs both signed and unsigned subtraction, setting the overflow and carry flags, respectively. However, by using the <code>jae</code> instruction, you are implicitly only checking the carry flag, so hopefully your loop counter and stop conditions are of the same type.</p>\n<p><a href=\"https://stackoverflow.com/questions/50605/signed-to-unsigned-conversion-in-c-is-it-always-safe\">The C standard defines how this should be done</a>, which does help mitigate bugs by both converting as properly and safely as possible, and by providing helpful warnings and even error messages (depending on the compilation strictness settings). Of course, if you're going to be writing assembly language directly, this obviously does not help you.</p>\n<p>For reference, the <code>EFLAGS</code> condition codes can be found in Volume 1 Appendix B of the <a href=\"https://software.intel.com/content/www/us/en/develop/articles/intel-sdm.html\" rel=\"nofollow noreferrer\">Intel® 64 and IA-32 Architectures Software Developer’s Manuals</a>, and the conditional jumps reference table starts on page 1106 of Volume 2.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T22:59:17.247",
"Id": "490455",
"Score": "0",
"body": "Thanks for the detailed reply. I am familiar with godbolt and I've taken a look at its output before.Great tool. So you basically recommend that I run all my C code through that to get an idea of best practices in assembly? Are default settings OK?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T00:07:42.190",
"Id": "490459",
"Score": "1",
"body": "@RedDragonWebDesign The best resource is always going to be an old hand, but if one isn't available, or when you're researching a question before posting on a site like this, compiler output is going to be a great resource because it's literally what would be getting run. I like to compare the output and performance from different optimization levels (particularly size vs. speed), but definitely make sure the C/C++/Rust/etc. code you're compiling is correct (syntactically, semantically, and idiomatically) so you get the best output. In other words, enable all warnings, checks, etc."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T16:45:13.967",
"Id": "250045",
"ParentId": "249986",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T08:06:34.433",
"Id": "249986",
"Score": "6",
"Tags": [
"programming-challenge",
"assembly",
"nasm"
],
"Title": "CodeWars - Assembly Language - Check List For Value"
}
|
249986
|
<p>The following is the web exercise 3.2.27. from the book <em>Computer Science An Interdisciplinary Approach</em> by Sedgewick & Wayne:</p>
<blockquote>
<p>Write a data type that represents a particle
undergoing a <a href="https://en.wikipedia.org/wiki/Brownian_motion" rel="noreferrer">Brownian motion</a> in two dimensions. Create a client
program that takes a command line integer N, creates N particles at
the origin, and simulates a Brownian motion for the N particles.</p>
</blockquote>
<p>One thing to note: For the initial position of particles I chose random points throughout the blank page instead of the origin.</p>
<p>Here is my data-type implementation for Brownian particles:</p>
<pre><code>public class BrownianParticle {
private double xPosition;
private double yPosition;
private final double particleRadius;
public BrownianParticle(double xPosition, double yPosition, double particleRadius) {
this.xPosition = xPosition;
this.yPosition = yPosition;
this.particleRadius = particleRadius;
}
public double getXPosition() {
return xPosition;
}
public double getYPosition() {
return yPosition;
}
public double getParticleRadius() {
return particleRadius;
}
public BrownianParticle updatePosition(double xIncrement, double yIncrement) {
double random = Math.random();
if (random < 1.0/8.0) {xPosition -= xIncrement; yPosition += yIncrement;}
else if (random < 2.0/8.0) {yPosition += yIncrement;}
else if (random < 3.0/8.0) {xPosition += xIncrement; yPosition += yIncrement;}
else if (random < 4.0/8.0) {xPosition += xIncrement;}
else if (random < 5.0/8.0) {xPosition += xIncrement; yPosition -= yIncrement;}
else if (random < 6.0/8.0) {yPosition -= yIncrement;}
else if (random < 7.0/8.0) {xPosition -= xIncrement; yPosition -= yIncrement;}
else if (random < 8.0/8.0) {xPosition -= xIncrement;}
return new BrownianParticle(xPosition, yPosition, particleRadius);
}
}
</code></pre>
<p>Here is my data-type implementation for drawing Brownian particles:</p>
<pre><code>import java.awt.Color;
public class BrownianParticleDraw {
private final BrownianParticle particle;
public BrownianParticleDraw(BrownianParticle particle) {
this.particle = particle;
}
public void draw() {
StdDraw.setPenColor(StdDraw.GRAY);
StdDraw.filledCircle(particle.getXPosition(),
particle.getYPosition(),
particle.getParticleRadius());
}
public void drawWithSpotlight() {
Color lightYellow = new Color(255,255,51);
StdDraw.setPenColor(lightYellow);
StdDraw.filledCircle(particle.getXPosition(),
particle.getYPosition(),
particle.getParticleRadius()*5);
StdDraw.setPenColor(StdDraw.GRAY);
}
}
</code></pre>
<p>Here is my test client for simulating Brownian motion:</p>
<pre><code>public class BrownianMotion {
public static double pickRandomlyBetween(double a, double b) {
return a + Math.random()*(b-a);
}
public static BrownianParticle[] InitializeRandomly(int numberOfParticles) {
BrownianParticle[] particles = new BrownianParticle[numberOfParticles];
double particleRadius = 0.005;
for (int i = 0; i < numberOfParticles; i++) {
// StdDraw creates a 1-by-1 blank page (from 0 to 1) by default
double xPoistion = pickRandomlyBetween(0.05, 0.95);
double yPosition = pickRandomlyBetween(0.05, 0.95);
particles[i] = new BrownianParticle(xPoistion, yPosition, particleRadius);
}
return particles;
}
public static void animate(int trials, BrownianParticle[] particles) {
int numberOfParticles = particles.length;
StdDraw.enableDoubleBuffering();
for (int t = 1; t <= trials; t++) {
double specificParticleRadius = particles[0].getParticleRadius();
particles[0].updatePosition(2*specificParticleRadius, 2*specificParticleRadius);
BrownianParticleDraw specificParticleDrawn = new BrownianParticleDraw(particles[0]);
StdDraw.clear();
specificParticleDrawn.drawWithSpotlight();
specificParticleDrawn.draw();
for (int i = 1; i < numberOfParticles; i++) {
double particleRadius = particles[i].getParticleRadius();
particles[i].updatePosition(2*particleRadius, 2*particleRadius);
BrownianParticleDraw particleDrawn = new BrownianParticleDraw(particles[i]);
particleDrawn.draw();
}
StdDraw.pause(100);
StdDraw.show();
}
}
public static void main(String[] args) {
int numberOfParticles = Integer.parseInt(args[0]);
int trials = Integer.parseInt(args[1]);
BrownianParticle[] particles = InitializeRandomly(numberOfParticles);
animate(trials, particles);
}
}
</code></pre>
<p><a href="https://introcs.cs.princeton.edu/java/stdlib/javadoc/StdDraw.html" rel="noreferrer">StdDraw</a> is a simple API written by the authors of the book. I checked my program and it works. Here are 2 different instances of it.</p>
<p>Input: 2 50</p>
<p>Output:</p>
<p><a href="https://i.stack.imgur.com/tgak9.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/tgak9.gif" alt="enter image description here" /></a></p>
<p>Input: 200 50</p>
<p>Output:</p>
<p><a href="https://i.stack.imgur.com/ZGtCI.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/ZGtCI.gif" alt="enter image description here" /></a></p>
<p>Is there any way that I can improve my programs (especially their performance)?</p>
<p>Thanks for your attention.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T21:06:23.567",
"Id": "490357",
"Score": "0",
"body": "Do particles pass through each other?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T10:14:25.643",
"Id": "490585",
"Score": "0",
"body": "Unfortunately yes. There are no elastic collisions."
}
] |
[
{
"body": "<ul>\n<li><p><strong>Physics</strong> is wrong.</p>\n<p>The Brownian motion is isotropic. Your model is not. The steps in major directions are <code>xIncrement</code> and <code>yIncrement</code> (<span class=\"math-container\">\\$I_x\\$</span> and <span class=\"math-container\">\\$I_y\\$</span> respectively), but the steps along the diagonals are larger, <span class=\"math-container\">\\$\\sqrt{I_x^2 + I_y^2}\\$</span>.</p>\n<p>The tests hide it because of the random initial positions. Shall you follow instructions and set the particles at the origin, you would immediately see that the distribution of particles is not radially symmetrical.</p>\n<p>Consider drawing a direction uniformly from a <span class=\"math-container\">\\$[0, 2\\pi)\\$</span> range, and a step from a geometric distribution. That will give much more realistic model.</p>\n</li>\n<li><p><strong><code>BrownianParticle.updatePosition</code></strong> returns <code>new BrownianParticle</code>. This is strange, especially considering that the return value is always ignored.</p>\n</li>\n<li><p>I don't see how the performance can be improved (beside not creating new particles continuously).</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T03:53:28.220",
"Id": "490373",
"Score": "0",
"body": "The fact that they have separate variable for x and y increments suggest that they want to be able to modify the code to allow for further anisotropy. Weird."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T16:35:09.440",
"Id": "250004",
"ParentId": "249992",
"Score": "12"
}
},
{
"body": "<h2>Naming</h2>\n<p>The names are not wrong, but I find them <em>very</em> verbose, which makes the code longer and harder to read and write.</p>\n<pre><code>private double xPosition;\nprivate double yPosition;\nprivate final double particleRadius;\n</code></pre>\n<p>It would be fine with <code>x</code> <code>y</code> and <code>radius</code> , and I see no risk of confusion as to the meaning of those names.</p>\n<p>This spreads further through your code when using functions like <code>.getParticleRadius()</code> and <code>getXPosition()</code></p>\n<h2>UpdatePosition</h2>\n<pre><code> public BrownianParticle updatePosition(double xIncrement, double yIncrement) {\n double random = Math.random();\n if (random < 1.0/8.0) {xPosition -= xIncrement; yPosition += yIncrement;}\n else if (random < 2.0/8.0) {yPosition += yIncrement;}\n else if (random < 3.0/8.0) {xPosition += xIncrement; yPosition += yIncrement;}\n else if (random < 4.0/8.0) {xPosition += xIncrement;}\n else if (random < 5.0/8.0) {xPosition += xIncrement; yPosition -= yIncrement;}\n else if (random < 6.0/8.0) {yPosition -= yIncrement;}\n else if (random < 7.0/8.0) {xPosition -= xIncrement; yPosition -= yIncrement;}\n else if (random < 8.0/8.0) {xPosition -= xIncrement;}\n return new BrownianParticle(xPosition, yPosition, particleRadius);\n}\n</code></pre>\n<p>This is wrong.\nThis method should be <code>public void</code> and it should not return anything at the end. It changes the position of an existing particle and there is no need to create a new particle, like you do at the end. That is a waste of memory. This is confirmed by looking at where you call this function, and you are not assigning the returned <code>new BrownianParticle</code> to anything, so it just takes up some CPU and memory when created and then later it will be garbage collected and removed again.</p>\n<h2>Constants</h2>\n<pre><code>public void drawWithSpotlight() {\n Color lightYellow = new Color(255,255,51);\n StdDraw.setPenColor(lightYellow);\n StdDraw.filledCircle(particle.getXPosition(),\n particle.getYPosition(), \n particle.getParticleRadius()*5);\n StdDraw.setPenColor(StdDraw.GRAY);\n}\n</code></pre>\n<p>This creation of a <code>new Color</code> is wrong. Just like your previous chaos drawing program, you should define and use constants ( <code>final Color ...</code> ) for anything that you are re-using. If you don't use constants, this code will create a new color object that takes up memory every time it iterates, which is many times per seconds.</p>\n<p>You need to understand what <code>new</code> means and be careful about using it in wasteful ways. It creates new objects and uses memory every time it is called.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T15:25:49.463",
"Id": "490516",
"Score": "1",
"body": "This is a nice example of where getters and setters make readability worse, because at best they litter the source code with useless pairs of (). If you *must* use them (e.g. for ideological reasons, not because they are necessary) x() and y() are better names than getXPosition() and getYPosition()."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T16:37:51.337",
"Id": "250006",
"ParentId": "249992",
"Score": "12"
}
},
{
"body": "<p>First of all, a general rule is that if you have more than a few else-ifs, you should start looking for a different control structure. For instance, you could replace your if-then-else-if block with <code>xPosition += (round(3*random)%3-1)*xIncrement; yPosition += (round(9*random)%3-1)*yIncrement;</code> But it's probably better to have two separate random numbers for x and y. And having different x and y increments is a bit weird. You end up plugging in the same numbers when you use the method, and Brownian motion generally has the same magnitude in both axes. And since the increment appears to depend on the radius, you might want to have the method simply access that attribute of the object, rather than having the external function access the attribute, then feed it back into the method.</p>\n<p>Furthermore, Brownian motion is Gaussian, so you should generate random numbers from a normal distribution. This addresses the isotropy issue raised in another answer, as two-dimensional Gaussian motion can be decomposed into independent Gaussian motion along the two axes.</p>\n<p>I also agree that the naming is overly wordy; having <code>particle.getParticleRadius()</code> is redundant. When you have a variable inside a class, you don't need to include class information in the variable name; that information is conveyed by the fact that it's part of the class.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T03:37:07.417",
"Id": "250022",
"ParentId": "249992",
"Score": "5"
}
},
{
"body": "<p><strong>Summary:</strong> You need to decide whether you are doing a random walk on a lattice <strong>(with <code>int</code>)</strong> or a random walk on a continuum <strong>(with <code>double</code>)</strong>.</p>\n<p>I'm going to discuss the physics and scientific computing aspects.</p>\n<h2>Brownian motion on a square lattice</h2>\n<p><strong>Contrary to what was said in another answer, the physics is not necessarily wrong.</strong> First, you might be simulating diffusion of molecules on top of a crystal plane with a square lattice (for example, the surface of gold called <a href=\"https://doi.org/10.1039/C6NR07709A\" rel=\"nofollow noreferrer\">Au(100)</a>). For this, a square grid would be completely appropriate. Furthermore, even in the absence of a physical lattice in what you are studying, your position distributions are isotropic in the limit of many steps. Your eventual <code>xPosition</code> is the sum of many random deviates from the set {<code>-xIncrement</code>, <code>0</code>, <code>+xIncrement</code>} and <code>yPosition</code> is the sum of random deviates from the set {<code>-yIncrement</code>, <code>0</code>, <code>+yIncrement</code>}. <code>UpdatePosition()</code> applies the displacements in x and the displacements in y in a way that they are independent. By the central limit theorem, <code>xPosition</code> and <code>yPosition</code> approach normal distributions, so that the position distribution after a large number of steps is:</p>\n<p><span class=\"math-container\">$$P(x,y) \\sim \\frac{1}{\\sqrt{2 \\pi \\sigma^2}} \\exp\\left( -\\frac{x^2+y^2}{2\\sigma^2} \\right).$$</span></p>\n<p>This has a circularly symmetric form: that is, it can be expressed as a function of distance from the initial point <span class=\"math-container\">\\$r=\\sqrt{x^2+y^2}\\$</span> only.</p>\n<p>Here's an <a href=\"https://www.wolframscience.com/nks/p330--the-phenomenon-of-continuity/\" rel=\"nofollow noreferrer\">example</a> of the approach to circular symmetry in Wolfram's <em>New Kind of Science</em>. I'm not sure how trustworthy this book is on everything, but I think he's probably right here.</p>\n<p><a href=\"https://i.stack.imgur.com/8PoEn.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/8PoEn.png\" alt=\"Approach to circular symmetry for a random walk on a square lattice.\" /></a></p>\n<p>You are using a fixed increment, which means your particles stay on a fixed grid (lattice). Studying molecules on a lattice can be a useful approximation to allow efficient simulation. However, <strong>if you are doing a random walk on a lattice, <code>xPosition</code> and <code>yPosition</code> should be <code>int</code></strong>, since all of the advantages of doing simulation on a lattice are best implemented with integers, which are discrete like the lattice. If <code>xPosition</code> and <code>yPosition</code> are supposed to be on a grid, you don't want to accumulate small floating-point errors that make all the particles slightly off the lattice. In the future, you may want to make it so two particles can't occupy the same positions. Checking whether a lattice position is occupied is easy with <code>int</code> positions. With <code>double</code>, checking whether two particles occupy the same lattice point could be error-prone due to the limited precision of floating-point representations.</p>\n<h2>Brownian motion on a continuum</h2>\n<p>If you want to do this off-lattice with floating-point numbers, then you should implement the physics differently. @vnp's suggestion of randomly selecting an angle from 0 to 2π and incrementing by <code>xPosition += increment*cos(angle)</code> or <code>yPosition += increment*sin(angle)</code> is isotropic by construction and you wouldn't have to run many steps to see circular symmetry. However, the magnitude of the steps is wrong and you have to run many steps to approach true Brownian motion. A better approach that gives you true Brownian motion even for a single step is <a href=\"https://doi.org/10.1063/1.436761\" rel=\"nofollow noreferrer\">the algorithm of Ermak and McCammon</a>.</p>\n<p>If we ignore their hydrodynamic interactions, position-dependent diffusion coefficients and forces, the algorithm simplifies to:</p>\n<p><span class=\"math-container\">$$x_{i+1} = x_i + g_t \\sqrt{2 D \\Delta t},$$</span></p>\n<p>where <span class=\"math-container\">\\$D\\$</span> is the diffusion coefficient (in units of <span class=\"math-container\">\\$\\mathsf{distance}^2/\\mathsf{time}\\$</span>), <span class=\"math-container\">\\$\\Delta t\\$</span> is the time step, and <span class=\"math-container\">\\$g_t\\$</span> is a random number from a normal distribution with a mean of 0 and a variance of 1. You can get such normal deviates from the <a href=\"https://www.geeksforgeeks.org/random-nextgaussian-method-in-java-with-examples/\" rel=\"nofollow noreferrer\">Java Random class</a> using the <strong><code>nextGaussian()</code></strong> function or by generating them from uniformly distributed random numbers using a method like the <a href=\"https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform\" rel=\"nofollow noreferrer\">Box–Mueller transform</a>. The Ermak–McCammon algorithm is exact for your system, although it becomes approximate if you have forces between the particles. In the continuum, you can easily add interparticle forces and/or external forces between the particles:</p>\n<p><span class=\"math-container\">$$x_{i+1} = x_i + \\frac{D}{kT}F^{(x)}_i \\Delta t + g^{(x)}_t \\sqrt{2 D \\Delta t},$$</span>\n<span class=\"math-container\">$$y_{i+1} = y_i + \\frac{D}{kT}F^{(y)}_i \\Delta t + g^{(y)}_t \\sqrt{2 D \\Delta t},$$</span></p>\n<p>where <span class=\"math-container\">\\$F^{(x)}_i\\$</span> is the net force on particle <span class=\"math-container\">\\$i\\$</span> in the <span class=\"math-container\">\\$x\\$</span>-direction. <span class=\"math-container\">\\$\\Delta t\\$</span> must be small enough that the force on each particle changes little between steps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T10:16:09.573",
"Id": "490586",
"Score": "1",
"body": "Thank you very much for the great answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T18:59:27.807",
"Id": "250051",
"ParentId": "249992",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "250051",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T12:36:02.420",
"Id": "249992",
"Score": "9",
"Tags": [
"java",
"performance",
"beginner"
],
"Title": "Simulating Brownian motion for N particles"
}
|
249992
|
<p>I have the following code, comparing two lists that contains equally structured tuples:</p>
<pre class="lang-py prettyprint-override"><code>list_one = [('id_01','aaa','bbb'), ('id_02','aaa','bbb'), ('id_03','aaa','bbb'), ('id_04','aab','bbc')]
list_two = [('id_01','aaa','bbb'), ('id_02','aaa','bbb'), ('id_03','aad','bbd')]
for tupl in list_one:
for tup in list_two:
if tupl[0] == tup[0] and (tupl[1] != tup[1] or tupl[2] != tup[2]):
print("There is a difference on "+
"{} between the two lists".format(tup[0]))
</code></pre>
<p>this code would print
<code>There is a difference on id_03 between the two lists</code>
which is the expected result.
But I wonder if there is a better way to achieve the same result, maybe whitout iterating through <code>list_two</code> for every item of <code>list_one</code>, but any suggestion will be appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T13:57:27.507",
"Id": "490338",
"Score": "2",
"body": "If `id_03` were the same in both lists what output would you expect?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T15:12:21.690",
"Id": "490342",
"Score": "0",
"body": "Hi @Peilonrayz I understand it would be a good idea including this validation, but for my scope, I'm only concerned about the differences, i.e. this validation not returning anything would mean that everything is ok."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T20:52:01.400",
"Id": "490356",
"Score": "1",
"body": "Are the lists in order by id? That is, the tuple with id_01 is before the tuple with id_02, etc. The sample data has them in order; is that always the case?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T18:07:10.240",
"Id": "490429",
"Score": "0",
"body": "No @RootTwo, and the real IDS are strings, like, \"SOMETHING_OTHER_SOMETHING\", without any kind of ordinance."
}
] |
[
{
"body": "<p>Looks like you should use a dictionary instead of a list. The <code>id_01</code> in your case would be the key for each dictionary and the other items can be contained in a list.</p>\n<p>Like this (same for dict_two)</p>\n<pre><code>dict_one = {\n 'id_01': ['aaa', 'bbb'],\n 'id_02': ['aaa', 'bbb'],\n}\n</code></pre>\n<p>then you can iterate over the keys</p>\n<pre><code>for k in dict_one.keys():\n if dict_one[k][0] != dict_two[k][0] or dict_one[k][1] != dict_two[k][1]:\n print("there is a diff....")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T14:02:10.233",
"Id": "490339",
"Score": "0",
"body": "This doesn't work the same as the OP's"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T16:24:06.300",
"Id": "490346",
"Score": "1",
"body": "It does what was asked for `a better way to achieve the same result, maybe whitout iterating through list_two for every item of list_one,` . What do you think is missing in my suggestion? The data structure used by OP seems inappropriate for what they want to do with it, don't you agree?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T23:18:44.123",
"Id": "490362",
"Score": "1",
"body": "it'd raise an error for key id_04"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T23:50:24.757",
"Id": "490365",
"Score": "0",
"body": "@hjpotter92 correct. I assumed too much"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T13:59:23.553",
"Id": "249997",
"ParentId": "249995",
"Score": "1"
}
},
{
"body": "<p>I think you would be better off <a href=\"https://devdocs.io/python%7E3.8/library/functions#set\" rel=\"nofollow noreferrer\">using <code>set</code></a>. It provides features like set difference by itself, thereby reducing a lot of work at your end:</p>\n<pre><code>set_one = set([('id_01','aaa','bbb'), ('id_02','aaa','bbb'), ('id_03','aaa','bbb'), ('id_04','aab','bbc')])\nset_two = set([('id_01','aaa','bbb'), ('id_02','aaa','bbb'), ('id_03','aad','bbd')])\nfor difference in (set_two - set_one):\n print(f"There is a difference on {difference[0]} between the two lists")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T15:26:29.200",
"Id": "250000",
"ParentId": "249995",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "250000",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T13:26:35.863",
"Id": "249995",
"Score": "1",
"Tags": [
"python"
],
"Title": "comparing lists of tuples"
}
|
249995
|
<p>I have the following implementation of the Fnv1a hashing for a string, which should be correct:</p>
<pre><code>public static uint Fnv1a(string toHash, bool separateUpperByte = false)
{
IEnumerable<byte> bytesToHash;
if (separateUpperByte)
{
bytesToHash = toHash.ToCharArray().Select(c => new[] { (byte)((c - (byte)c) >> 8), (byte)c }).SelectMany(c => c);
}
else
{
bytesToHash = toHash.ToCharArray().Select(Convert.ToByte);
}
uint hash = FnvConstants.FnvOffset32;
foreach (var chunk in bytesToHash)
{
hash ^= chunk;
hash *= FnvConstants.FnvPrime32;
}
return hash;
}
</code></pre>
<p>I now want to hash Guids instead of strings. Will the following give a good fnv1 hash?</p>
<pre><code>public static uint Fnv1a(Guid toHash, bool separateUpperByte = false)
{
IEnumerable<byte> bytesToHash;
if (separateUpperByte)
{
bytesToHash = toHash.ToByteArray().Select(c => new[] { (byte)((c - (byte)c) >> 8), (byte)c }).SelectMany(c => c);
}
else
{
bytesToHash = toHash.ToByteArray();
}
uint hash = FnvConstants.FnvOffset32;
foreach (var chunk in bytesToHash)
{
hash ^= chunk;
hash *= FnvConstants.FnvPrime32;
}
return hash;
}
</code></pre>
<p>We use the hash for determining partitions in a Service Fabric cluster. My concern is whether this implementation distributes the keys evenly.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T14:31:31.527",
"Id": "490340",
"Score": "1",
"body": "It would seem to me that best reusability would be to reduce the second method to a one-liner: `public static uint Fnv1aGuid(Guid toHash, bool separateUpperByte = false) => Fnv1a(toHash.ToString(), separateUpperByte);`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T15:31:36.773",
"Id": "490345",
"Score": "0",
"body": "And considering that you can have the same method name with a different type of parameter, you can even leave off the \"Guid\" in `Fnv1aGuid`. Plus you could make it an extension method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T23:39:10.087",
"Id": "490364",
"Score": "0",
"body": "@JesseC.Slicer I am thinking that would hurt performance. In that case it would probably be better to store the Guids as strings instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T01:22:09.880",
"Id": "490370",
"Score": "0",
"body": "@yngling if this is your performance bottleneck, I'd be extremely surprised."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T07:29:50.653",
"Id": "490376",
"Score": "0",
"body": "@JesseC.Slicer Well, when I say performance I am thinking compared with just using strings. If I want to convert to strings before hashing, I feel I might as well just store the Guids as strings, as hashing is about the only thing I do with them."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T14:23:51.497",
"Id": "249998",
"Score": "2",
"Tags": [
"c#",
"hashcode"
],
"Title": "Fnv1a hashing of C# Guid"
}
|
249998
|
<p>Sanity check needed, as I'm still very unfamiliar with the nuances behind async/await and how they relate to more traditional Task / TPL code.</p>
<p>I have a high-level repository layer which is assembling a business object from various lower-level repositories. As a business decision, we are doing keyed lookups at the data layer and assembling the composite object in code. In the following code, "Account" is the business object, and the various _tAccountXXXRepo objects are all patterned similarly to this (we are using NPoco):</p>
<pre><code>public class T_AccountMapperRepository : BaseNPocoRepository<T_AccountMapper>
, IRetrieveMany<T_AccountMapper>
, IRetrieve<AccountId, T_AccountMapper>
{
public T_AccountMapperRepository(IDatabase database) : base(database)
{
}
public async Task<T_AccountMapper> Retrieve(AccountId input)
{
return await Database.QueryAsync<T_AccountMapper>()
.First(x => x.AccountId == input)
.ConfigureAwait(false);
}
}
</code></pre>
<p>The code to fetch the different values <em>can</em> be logically executed in parallel, and I am wondering if this implementation is the correct pattern to do so: (the various methods being called on the Account object are thread-safe as well)</p>
<pre><code>public async Task<Account> Retrieve(AccountId input1, DateTime input2)
{
var account = new Account();
await Task.WhenAll(
_tAccountMapperRepo.Retrieve(input1)
.ContinueWith(async result => account.SetAccountMap(await TranslateAccountMap(result))),
_tPaymentRedirectionRepo.Retrieve(input1, input2)
.ContinueWith(async result => account.ChangePayerToAccount(await TranslatePaymentRedirection(result))),
_tAccountAncestorRepo.Retrieve(input1, input2)
.ContinueWith(async result => await _tAccountMapperRepo.Retrieve((await result).AncestorId))
.ContinueWith(async result => account.MoveAccountToNewParentAccountMap(await TranslateAccountMap(await result))),
_tAccountRepo.Retrieve(input1)
.ContinueWith(async result => await _tAccountTypeRepo.Retrieve((await result).TypeId))
.ContinueWith(async result => account.SetAccountType(await TranslateAccountType(await result)))
);
return account;
}
</code></pre>
<p>Any method that is labelled with TranslateXXX all look similar to this:</p>
<pre><code>private static async Task<AccountMap> TranslateAccountMap(Task<T_AccountMapper> mapTask)
{
if (!mapTask.IsCompletedSuccessfully)
throw new InvalidOperationException(nameof(mapTask), mapTask.Exception);
var map = await mapTask;
return new AccountMap(map.AccountId, map.Login, map.Namespace);
}
</code></pre>
<p>My main concerns are mixing Task and async/await, and whether or not my async & awaiting is re-introducing an element of synchronicity in what I'm hoping to make a very asynchronous process. My end goal is that as many various properties as possible are fetched in parallel and assembled</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T13:19:25.250",
"Id": "490402",
"Score": "0",
"body": "@BryanBoettcher Please do not use the name `result` in your `ContinueWith` delegates. They are really misleading. Because you haven't specified `TaskContinuationOptions.OnlyOnRanToCompletion` that's why your ancestor / antecedent task could have failed. IMO, calling a failed task as `result` is misleading."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T16:16:59.827",
"Id": "490519",
"Score": "3",
"body": "I updated your title to what I **think** your code is doing from the description you provided. This allows people looking to answer questions find such questions that are related to their domain interests instead of having to rely on what you as the reviewee **think** your problem is. It also makes for a better variety of titles :) I hope this also clarifies what BCdotWEB wanted from your title."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T14:36:51.350",
"Id": "490621",
"Score": "0",
"body": "@Vogel612: that isn't what my question was though, unfortunately. I was specifically looking to know if the way I was mixing & matching async/await with Task.ContinueWith was going to cause deadlocks or synchronization problems."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T14:40:40.690",
"Id": "490622",
"Score": "1",
"body": "that is **exactly** the point. The title is ***not*** what your question about the code is, it's what the **code is doing**."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T14:55:06.397",
"Id": "490623",
"Score": "0",
"body": "@Vogel612: So then I should have asked on a different Stack Exchange site, is ultimately what I'm gathering."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T15:00:56.550",
"Id": "490624",
"Score": "0",
"body": "well, the problem with that is, that for Stack Overflow, while it's a specific question you have, a lot of people think that it belongs here on Code Review. And overall code review **is** a better fit than SO, so they're not even wrong. It's not a perfect fit, but it works well enough, I'd say. Other programming-related stack exchanges fit even less than SO, soo..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T15:13:22.070",
"Id": "490626",
"Score": "0",
"body": "I mean, ultimately you guys control the format, I'm just of the opinion that anything could be happening asynchronously, so bucketing it to \"assemble an object\" misses the point. Is it up to the reader to recognize that \"fetching these 4 URLs is exactly the same use-case as 'building a domain object'\"?"
}
] |
[
{
"body": "<p>As for me it looks fine except one thing. You have already completed <code>Task</code> in <code>.ContinueWith</code> block, thus you may use <code>.Result</code> then instead of <code>await</code> and avoid redundant <code>async</code> State Machine.</p>\n<p>By the way, if you're using <code>async/await</code>, probably there's no continuations needed.</p>\n<p>Consider this continuations-free implementation of 1st <code>Task.WhenAll()</code> job.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public async Task<Account> Retrieve(AccountId input1, DateTime input2)\n{\n var account = new Account();\n\n // probably try-catch wrapper maybe useful here as replacement of !mapTask.IsCompletedSuccessfully\n await Task.WhenAll((Func<Task>)(async () =>\n {\n T_AccountMapper map = await _tAccountMapperRepo.Retrieve(input1);\n // continuation:\n AccountMap accountMap = new AccountMap(map.AccountId, map.Login, map.Namespace);\n account.SetAccountMap(accountMap);\n })\n //, (Func<Task>)(async() => {...})\n );\n\n return account;\n}\n</code></pre>\n<p>As you can see, <code>TranslateAccountMap</code> method isn't needed anymore.</p>\n<p>Finally, it's up to you.</p>\n<p>P.S. Here's a <a href=\"https://devblogs.microsoft.com/pfxteam/processing-tasks-as-they-complete/\" rel=\"nofollow noreferrer\">useful link</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T19:04:36.050",
"Id": "490353",
"Score": "1",
"body": "The \"useful link\" was already purple :) That's what gave me something like the pattern"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T18:32:36.167",
"Id": "250012",
"ParentId": "250002",
"Score": "3"
}
},
{
"body": "<p>Based on feedback from aepot, and lessons from <a href=\"https://github.com/davidfowl/AspNetCoreDiagnosticScenarios/blob/master/AsyncGuidance.md#prefer-await-over-continuewith\" rel=\"nofollow noreferrer\">AspNetCore Async Guidance</a>, this is what I refactored the code into:</p>\n<pre><code>public async Task<Account> RetrieveAsync(AccountId input1, DateTime input2)\n{\n Account account = new Account();\n\n await Task.WhenAll(\n SetAccountMap(account, input1, input2),\n ChangePayer(account, input1, input2),\n SetParentMap(account, input1, input2),\n SetAccountType(account, input1, input2)\n );\n\n return account;\n}\n\nprivate async Task SetAccountType(Account account, AccountId accountId, DateTime dateTime)\n{\n var baseAccount = await _tAccountRepo.RetrieveAsync(accountId);\n var accountType = await _tAccountTypeRepo.RetrieveAsync(baseAccount.TypeId); \n var convertedAccountType = _accountTypeConverter.Convert(accountType);\n\n account.SetAccountType(convertedAccountType);\n}\n\nprivate async Task SetParentMap(Account account, AccountId accountId, DateTime dateTime)\n{\n var accountAncestor = await _tAccountAncestorRepo.RetrieveAsync(accountId, dateTime);\n var accountMap = await _tAccountMapperRepo.RetrieveAsync(accountAncestor.DescendentId);\n var convertedAccountMap = _accountMapConverter.Convert(accountMap);\n\n account.MoveAccountToNewParentAccountMap(convertedAccountMap);\n}\n\nprivate async Task ChangePayer(Account account, AccountId accountId, DateTime dateTime)\n{\n var paymentRedirection = await _tPaymentRedirectionRepo.RetrieveAsync(accountId, dateTime);\n var convertedPaymentRedirection = _paymentRedirectionConverter.Convert(paymentRedirection);\n\n account.ChangePayerToAccount(convertedPaymentRedirection);\n}\n\nprivate async Task SetAccountMap(Account account, AccountId accountId, DateTime dateTime)\n{\n var accountMap = await _tAccountMapperRepo.RetrieveAsync(accountId);\n var convertedAccountMap = _accountMapConverter.Convert(accountMap);\n\n account.SetAccountMap(convertedAccountMap);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T22:42:22.297",
"Id": "490454",
"Score": "0",
"body": "I suggest to rename `input1` and `input2` to `id` and `date` accordingly. `accountId` and `dateTime` arguments can be shorten in the same way. Btw, I like this version of the code, looks more friendly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T12:23:13.173",
"Id": "490494",
"Score": "0",
"body": "@BryanBoettcher With this code you are running 4 different functions concurrently that are try to modify the same object. It can work (and will not cause race condition) if these functions are working on independent set of properties of the Account. What if you would do the necessary data retrievals concurrently and then you could construct the Account object on a single thread? With that your ET(L) would be nicely separated. Parallel Extraction and Single threaded Transformation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T14:51:19.047",
"Id": "490513",
"Score": "0",
"body": "@PeterCsala: in this case the object is thread-aware and there will not be race conditions. Good catch though, because that could definitely be problematic! Can you post an answer that would illustrate the parallel-fetch & single-threaded set? I feel like it may bring a bunch of noise back to the main method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T07:53:44.837",
"Id": "490575",
"Score": "0",
"body": "@BryanBoettcher I've just posted an answer, please check it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T12:05:36.193",
"Id": "490718",
"Score": "0",
"body": "It would be nice if you accept the most helpful answer or your own to make the review complete."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-05T15:23:55.647",
"Id": "490920",
"Score": "1",
"body": "@aepot: I had to wait before accepting -- I upvoted yours, but will be accepting mine since ultimately that's what I went with."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T21:58:47.080",
"Id": "250059",
"ParentId": "250002",
"Score": "3"
}
},
{
"body": "<p>Here I've two alternative versions of Bryan Boettcher revised code.</p>\n<p>In his version there are 4 <em>ETL</em> functions and they are running concurrently.</p>\n<p>In my solutions only the <em>Extract</em> part is running concurrently. The <em>Transformation</em> and <em>Load</em> parts are executed sequentially.</p>\n<h3>Alternative #1</h3>\n<p>Please bear in mind that I had to use some made up type names (like: <code>AccountType</code>, <code>PaymentRedirection</code>) because I could not tell the exact types based on the provided code.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public async Task<Account> RetrieveAsync(AccountId accountId, DateTime dateTime)\n{\n //Extract\n var accountTypeJob = RetrieveAccountType(accountId);\n var paymentRedirectionJob = RetrievePaymentRedirection(accountId, dateTime);\n var accountMapJob = RetrieveAccountMap(accountId);\n var parentAccountMapJob = RetrieveAccountMapForParent(accountId, dateTime);\n\n //Transform\n var accountType = await accountTypeJob;\n var convertedAccountType = _accountTypeConverter.Convert(accountType);\n\n var paymentRedirection = await paymentRedirectionJob;\n var convertedPaymentRedirection = _paymentRedirectionConverter.Convert(paymentRedirection);\n\n var accountMap = await accountMapJob;\n var convertedAccountMap = _accountMapConverter.Convert(accountMap);\n\n var parentAccountMap = await parentAccountMapJob;\n var convertedParentAccountMap = _accountMapConverter.Convert(parentAccountMap);\n\n //Load\n var account = new Account();\n account.SetAccountType(convertedAccountType);\n account.ChangePayerToAccount(convertedPaymentRedirection);\n account.SetAccountMap(convertedAccountMap);\n account.MoveAccountToNewParentAccountMap(convertedParentAccountMap);\n return account;\n}\n\nprivate async Task<AccountType> RetrieveAccountType(AccountId accountId)\n{\n var baseAccount = await _tAccountRepo.RetrieveAsync(accountId);\n return await _tAccountTypeRepo.RetrieveAsync(baseAccount.TypeId);\n}\n\nprivate async Task<AccountMap> RetrieveAccountMapForParent(AccountId accountId, DateTime dateTime)\n{\n var accountAncestor = await _tAccountAncestorRepo.RetrieveAsync(accountId, dateTime);\n return await _tAccountMapperRepo.RetrieveAsync(accountAncestor.DescendentId);\n}\n\nprivate async Task<PaymentRedirection> RetrievePaymentRedirection(AccountId accountId, DateTime dateTime)\n{\n return await _tPaymentRedirectionRepo.RetrieveAsync(accountId, dateTime);\n}\n\nprivate async Task<AccountMap> RetrieveAccountMap(AccountId accountId)\n{\n return await _tAccountMapperRepo.RetrieveAsync(accountId);\n}\n</code></pre>\n<p>As you can see I have 4 <code>RetrieveXYZ</code> functions and these are responsible for loading data. I suppose these are I/O operations, so they are not CPU-bound (concurrency is not limited by the available cores).</p>\n<p>During the <em>Extract</em> phase I start all of the <code>Task</code>s, so there is no need to explicitly call the <code>Task.WhenAll</code> In the <em>Transform</em> phase I access the retrieved data via the <code>await</code> keywords.</p>\n<h3>Alternative #2</h3>\n<p>With a simple helper function we can make the <code>RetrieveAsync</code> function neater and more concise.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public static class TaskExtensions\n{\n public static async Task<(T1, T2, T3, T4)> WhenAll<T1, T2, T3, T4>(Task<T1> t1, Task<T2> t2, Task<T3> t3, Task<T4> t4)\n {\n return (await t1, await t2, await t3, await t4);\n }\n}\n</code></pre>\n<p>By taking advantage of this helper method the new version of the <code>RetrieveAsync</code> would look like this:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public async Task<Account> RetrieveAsync(AccountId accountId, DateTime dateTime)\n{\n //Extract\n var (accountType, paymentRedirection, accountMap, parentAccountMap) = await TaskExtensions.WhenAll(\n RetrieveAccountType(accountId), RetrievePaymentRedirection(accountId, dateTime),\n RetrieveAccountMap(accountId), RetrieveAccountMapForParent(accountId, dateTime));\n\n //Transform\n var convertedAccountType = _accountTypeConverter.Convert(accountType);\n var convertedPaymentRedirection = _paymentRedirectionConverter.Convert(paymentRedirection);\n var convertedAccountMap = _accountMapConverter.Convert(accountMap);\n var convertedParentAccountMap = _accountMapConverter.Convert(parentAccountMap);\n\n //Load\n var account = new Account();\n account.SetAccountType(convertedAccountType);\n account.ChangePayerToAccount(convertedPaymentRedirection);\n account.SetAccountMap(convertedAccountMap);\n account.MoveAccountToNewParentAccountMap(convertedParentAccountMap);\n return account;\n}\n</code></pre>\n<h3>Advantages</h3>\n<ul>\n<li>Only the I/O bound operations are running concurrently\n<ul>\n<li>Each helper function has single responsibility</li>\n<li>The top-level function acts as a coordinator</li>\n</ul>\n</li>\n<li>There is no shared resource, so we don't have to worry that much about thread-safety</li>\n</ul>\n<h3>Disadvantages</h3>\n<ul>\n<li>If the <em>Transform</em> and/or <em>Load</em> parts are I/O bound as well then this approach would be slower</li>\n<li>It is not relying on the built-in <code>Task.WhenAll</code> rather than it relies on the <code>ValueTuple</code> and C# 7's Deconstruction capabilities, so it can't be used in older .NET Framework versions.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T07:53:09.793",
"Id": "250106",
"ParentId": "250002",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "250059",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T16:15:55.543",
"Id": "250002",
"Score": "4",
"Tags": [
"c#",
"async-await"
],
"Title": "Asynchronously assembling a complex object"
}
|
250002
|
<p>This is for an assignment in my robotics class so the requirements I needed to meet was that it had to be in a while loop and the input numbers needed to be float point. I just want to make sure that I'm not using any bad practices and if there are any areas that can be improved.</p>
<pre><code>while (True):
# Gets operator, converts to int and breaks if its not a number
try: operator = int(input("Choose an Operator:\n1) Addition\n2) Subtraction\n3) Multiplication\n4) Division\nInput (1/2/3/4):"))
except:
print('Invalid Input: Choose A Valid Operation')
break
# Checks the operator is within 1 and 4
if operator > 4 or operator < 1:
print('Invalid Input: Choose A Valid Operation')
break
# Gets first and second number, converts numbers to float and breaks if its not a number
try: firstnum = float(input('First Number:'))
except:
print('Invalid Input: Not a valid number')
break
try: secondnum = float(input('Second Number:'))
except:
print('Invalid Input: Not a valid number')
break
if operator == 1:
print('{0} + {1} ='.format(firstnum, secondnum), end =" ")
print(firstnum + secondnum)
break
if operator == 2:
print('{0} - {1} ='.format(firstnum, secondnum), end =" ")
print(firstnum - secondnum)
break
if operator == 3:
print('{0} * {1} ='.format(firstnum, secondnum), end =" ")
print(firstnum * secondnum)
break
if operator == 4:
print('{0} / {1} ='.format(firstnum, secondnum), end =" ")
print(firstnum / secondnum)
break
</code></pre>
|
[] |
[
{
"body": "<p>I don't think the program should stop if a person entered something incorrectly. Also, the part at the end is larger than need be and you don't need the 0 and 1 within the braces as they are added by defalt. Here's a solution(although it uses multiple <code>while</code> loops):</p>\n\n<pre><code>operators = ["+", "-", "*", "/"]\nwhile True:\n # Gets operator, converts to int and breaks if it's a number\n try: operator_switch = int(input("Choose an Operator:\\n1) Addition\\n2) Subtraction\\n3) Multiplication\\n4) Division\\nInput (1/2/3/4):"))\n except:\n print("Invalid Input: Choose a valid operation")\n else:\n # Checks the operator is within 1 and 4\n if operator_switch > 4 or operator_switch < 1:\n print("Invalid Input: Choose a valid operation")\n continue # goes straight back to the beginning without running what's after\n operator = operators[operator_switch - 1]\n break\nwhile True:\n # Gets first and second number, converts numbers to float and breaks only if it's a number\n try: firstnum = float(input("First number: "))\n except: \n print("Invalid Input: Not a valid number")\n continue\n try: secondnum = float(input("Second number: "))\n except: \n print("Invalid Input: Not a valid number")\n continue\n else:\n break\n# Shortens the end significantly. Don't read this if you don't want to\nop_func = int.__add__ if operator == "+" else int.__sub__ if operator == "-" else int.__mul__ if operator == "*" else int.__div__\nprint(f"{firstnum} {operator} {secondnum} = {op_func(firstnum, secondnum)}")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T19:47:02.773",
"Id": "490354",
"Score": "0",
"body": "When trying it after inputing the two numbers it loops back to asking the first number. I think its not exiting that second while loop."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T11:44:01.563",
"Id": "490394",
"Score": "0",
"body": "The first paragragh is a pretty good answer, there really isn't any need to provide an alternate solution."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T18:21:59.460",
"Id": "250010",
"ParentId": "250003",
"Score": "2"
}
},
{
"body": "<h1>Formatting strings in Python</h1>\n<pre class=\"lang-py prettyprint-override\"><code>foo = 5\nprint('{foo}'.format(foo))\n</code></pre>\n<p>This is a nice way to format string, But there is a short and cleaner way to format strings in Python 3 known as the <a href=\"https://realpython.com/python-f-strings/\" rel=\"nofollow noreferrer\">f-String</a>. The problem with <code>str.format()</code> is that if you have multiple parameters. Your string starts to look a little werid.For example</p>\n<pre class=\"lang-py prettyprint-override\"><code>first_name = "Eric"\nlast_name = "Idle"\nage = 74\nprofession = "comedian"\naffiliation = "Monty Python"\nprint(("Hello, {first_name} {last_name}. You are {age}. " + \n "You are a {profession}. You were a member of {affiliation}.") \\\n .format(first_name=first_name, last_name=last_name, age=age, \\\n profession=profession, affiliation=affiliation))\n</code></pre>\n<p>With <a href=\"https://realpython.com/python-f-strings/\" rel=\"nofollow noreferrer\">f-strings</a>. The same would look like.</p>\n<pre class=\"lang-py prettyprint-override\"><code>print(f"Hello, {first_name} {last_name}. You are {age}. " +\n f"You are a {profession}. You were a member of {affiliation}.")\n</code></pre>\n<p>This is why you should prefer using <a href=\"https://realpython.com/python-f-strings/\" rel=\"nofollow noreferrer\">f-strings</a>.</p>\n<h1><code>eval</code> in Python</h1>\n<p>When you want to perform the arithmetic part, I see that you have used a thread of if-statements. But we can use Python's <a href=\"https://www.geeksforgeeks.org/eval-in-python/\" rel=\"nofollow noreferrer\">eval</a> function to make life much easier. We simple place the operator entered by the user un between the two numbers.</p>\n<h2>old</h2>\n<pre class=\"lang-py prettyprint-override\"><code>if operator == 1:\n print('{0} + {1} ='.format(firstnum, secondnum), end =" ")\n print(firstnum + secondnum)\n break\nif operator == 2:\n print('{0} - {1} ='.format(firstnum, secondnum), end =" ")\n print(firstnum - secondnum)\n break\nif operator == 3:\n print('{0} * {1} ='.format(firstnum, secondnum), end =" ")\n print(firstnum * secondnum)\n break\nif operator == 4:\n print('{0} / {1} ='.format(firstnum, secondnum), end =" ")\n print(firstnum / secondnum)\n break\n</code></pre>\n<p>We ask the user to enter the operation the want directly , for example</p>\n<blockquote>\n<p>Choose an operator: +</p>\n</blockquote>\n<p>Or if you want to stick to using numbers.\n<code>operators = operators = {'+':1,'-':2,'*':3,'/':4}</code></p>\n<p>I have gone with the 1st method. You can use whatever you prefer to</p>\n<h2>new</h2>\n<pre class=\"lang-py prettyprint-override\"><code>print(f"{firstnum} {operator} {secondnum} = {float(eval(firstnum + operator + secondnum))}")\n</code></pre>\n<p>The new code using <code>eval</code> would like</p>\n<pre class=\"lang-py prettyprint-override\"><code>operators = ['+','-','*','/']\nwhile (True):\n # Gets operator, converts to int and breaks if its not a number\n try: operator = input("Choose an Operator:\\n1) Addition\\n2) Subtraction\\n3) Multiplication\\n4) Division\\nInput\\n(+,-,*,/):")\n except:\n print('Invalid Input: Choose A Valid Operation')\n break\n\n # Checks the operator is within 1 and 4\n if operator not in operators:\n print('Invalid Input: Choose A Valid Operation')\n break\n\n # Gets first and second number, converts numbers to float and breaks if its not a number\n try: firstnum = input('First Number:')\n except:\n print('Invalid Input: Not a valid number')\n break\n try: secondnum = input('Second Number:')\n except:\n print('Invalid Input: Not a valid number')\n break\n\n print(f"{firstnum} {operator} {secondnum} = {float(eval(firstnum + operator + secondnum))}")\n</code></pre>\n<p>With that simple change, I removed about 20 lines of code into one. Making it much more readable</p>\n<h1>Clearing the screen</h1>\n<p>It would be nicer to see a clear terminal after finishing one job. There are many ways to clear the terminal in python. A common way for windows users is</p>\n<pre class=\"lang-py prettyprint-override\"><code>os.system('cls')\n</code></pre>\n<p>But this way is considered bad as it is quite expensive. You can get away by simply</p>\n<pre class=\"lang-py prettyprint-override\"><code>print(chr(27) + "[2J")\n</code></pre>\n<p>Adding this to the start of each iteration in the <code>while(True):</code> loop will give a better experience to the user.</p>\n<h1>Waiting for input</h1>\n<p>Lastly, adding this line of code to the end will pause on the current text before going to the next one.\n<code>input("Press any key to continue...")</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T22:09:35.860",
"Id": "500478",
"Score": "0",
"body": "`eval` is a rather unsafe method, _no matter what_. It's unlikely to matter much here. Also, f-strings are only available on Python 3.6+. `input(\"Press any key to continue...\")` will pause until someone presses enter. I think `getch` would be more useful for a \"press a key to continue\"-type thing. Sorry about criticizing; mine isn't too great either."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T09:40:24.427",
"Id": "500510",
"Score": "0",
"body": "@Someone Any reason to *not* use python 3.6+?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T18:01:44.497",
"Id": "500552",
"Score": "0",
"body": "support. Sometimes a platform may not support Python 3.6+."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T12:42:10.547",
"Id": "500629",
"Score": "0",
"body": "@Someone and which platform ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T18:32:26.840",
"Id": "500666",
"Score": "0",
"body": "1. You never know and 2. OnlineGDB. I didn't know of Repl at the time and I suffered due to the lack of f-strings."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T18:42:46.927",
"Id": "250049",
"ParentId": "250003",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "250049",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T16:33:01.633",
"Id": "250003",
"Score": "6",
"Tags": [
"python"
],
"Title": "Simple Calculator to add/subtract/multiply/divide 2 inputs"
}
|
250003
|
<p>I have two folders that contain multiple <code>json</code> files. The first folder contains game logs for all MLB teams and is structured like this.</p>
<pre><code>{"Team": "PIT", "Games": [{"Date": "Jul 24, 2020", "Opponent": "@ San Diego", "Results": "L", "Score": "7-2", "Line": "+128", "Over_Under": "O", "Total": "8", "Players": []}, {"Date": "Jul 25, 2020", "Opponent": "@ San Diego", "Results": "L", "Score": "5-1", "Line": "+115", "Over_Under": "U", "Total": "8", "Players: []}]}
</code></pre>
<p>I have a second folder containing <code>json</code> files and the files are structured like this</p>
<pre><code>[{"StatID": 2593242, "TeamID": 4, "PlayerID": 10002075, "SeasonType": 1, "Season": 2019, "Name": "Colin Moran", "Team": "PIT", "Position": "3B", "PositionCategory": "IF", "Started": 1, "InjuryStatus": null, "GameID": 54207, "OpponentID": 31, "Opponent": "STL", "Day": "2019-04-01T00:00:00", "DateTime": "2019-04-01T13:05:00", "HomeOrAway": "HOME", "Games": 1, "FantasyPoints": 12.0, "AtBats": 3.0, "Runs": 1.0, "Hits": 2.0, "Singles": 0.0, "Doubles": 1.0, "Triples": 0.0, "HomeRuns": 1.0, "RunsBattedIn": 3.0, "BattingAverage": 0.667, "Outs": 1.0, "Strikeouts": 0.0, "Walks": 2.0, "HitByPitch": 0.0, "Sacrifices": 0.0, "SacrificeFlies": 0.0, "GroundIntoDoublePlay": 0.0, "StolenBases": 0.0, "CaughtStealing": 0.0, "OnBasePercentage": 0.8, "SluggingPercentage": 2, "OnBasePlusSlugging": 2.8, "Wins": 0.0, "Losses": 0.0, "Saves": 0.0, "InningsPitchedDecimal": 0.0, "TotalOutsPitched": 0.0, "InningsPitchedFull": 0.0, "InningsPitchedOuts": 0.0, "EarnedRunAverage": 0, "PitchingHits": 0.0, "PitchingRuns": 0.0, "PitchingEarnedRuns": 0.0, "PitchingWalks": 0.0, "PitchingStrikeouts": 0.0, "PitchingHomeRuns": 0.0, "PitchesThrown": 0.0, "PitchesThrownStrikes": 0.0, "WalksHitsPerInningsPitched": 0, "PitchingBattingAverageAgainst": 0, "FantasyPointsFanDuel": 37.7, "FantasyPointsDraftKings": 27.0, "WeightedOnBasePercentage": 0.8, "PitchingCompleteGames": 0.0, "PitchingShutOuts": 0.0, "PitchingOnBasePercentage": 0, "PitchingSluggingPercentage": 0, "PitchingOnBasePlusSlugging": 0, "PitchingStrikeoutsPerNineInnings": 0, "PitchingWalksPerNineInnings": 0, "PitchingWeightedOnBasePercentage": 0}]
</code></pre>
<p>I want to add the players stats from the second set of files to the first set. Right now I'm using a nested for loop and matching the two dicts based on date and team like this if <code>player['Day'].split('T')[0] == obj['Date'] and player['Team'] == team_data['Team']:</code></p>
<p>However, this is incredibly slow and inefficient. Is there a faster and more efficient way to do this?</p>
<p>Here is my code:</p>
<pre><code>import json
import pandas as pd
import os
path_to_json = '/Users/aus10/MLB/Combined_Clean_Team_Data'
Game_logs_json_files = [pos_json for pos_json in os.listdir(path_to_json) if pos_json.endswith('.json')]
path_to_json = '/Users/aus10/MLB/FPTS_Data'
FPTS_json_files = [pos_json for pos_json in os.listdir(path_to_json) if pos_json.endswith('.json')]
for file in Game_logs_json_files:
with open('/Users/aus10/MLB/Combined_Clean_Team_Data/'+file+'') as json_file:
team_data = json.load(json_file)
for file_1 in FPTS_json_files:
with open('/Users/aus10/MLB/FPTS_Data/'+file_1+'') as json_file:
fantasy_data = json.load(json_file)
for obj in team_data['Games']:
for player in fantasy_data:
if player['Day'].split('T')[0] == obj['Date'] and player['Team'] == team_data['Team']:
obj['Players'].append(player)
for obj in team_data['Games']:
for player in fantasy_data:
if player['Day'].split('T')[0] == obj['Date'] and player['Opponent'] == team_data['Team']:
obj['Opposing_P_ERA'] = player["EarnedRunAverage"]
obj['Opposing_P_WoBA'] = player["PitchingWeightedOnBasePercentage"]
with open('/Users/aus10/MLB/Combined_Clean_Team_Data/'+file+'', 'w') as my_file:
json.dump(team_data, my_file)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T20:19:33.027",
"Id": "490355",
"Score": "1",
"body": "How are the files organized in the directories? One file per team for the game logs? One file per player for the fantasy data? How much data in total (Mega or Giga bytes)? Does the end result need to be a bunch of json files?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T12:15:31.453",
"Id": "490493",
"Score": "0",
"body": "@RootTwo One file per team and then files for players in every player who played on a certain date. Team data is 358.7 MB and player data is 164 MB. The end results should be one json file for every team with all of the team game stats plus player stats included in the player array."
}
] |
[
{
"body": "<p>Use <code>pathlib</code>. It has a very nice interface for file/directory operations. The <code>/</code> operator\njoins path components together. A <code>pathlib.Path</code> has a <code>.glob()</code> method for finding filenames\nthat match a pattern, and an <code>.open()</code> for opening files.</p>\n<p>It is wise to save updated data to a new file or directory. At least until you verify the\ncode is working correctly.</p>\n<p>The player data is small enough that it can all be loaded into memory at once. Use a data\nstructure that makes things easier. In this case, use dicts to group the player data by\nteam and date.</p>\n<pre><code>team_game_player_data = {'STL':{date(7, 24, 2020):[player_1, player_2, ...],\n date(7, 25, 2020):[player_1, player_2, ...],\n ...\n },\n 'PIT':{date(7, 24, 2020):[player_1, player_2, ...],\n date(7, 25, 2020):[player_1, player_2, ...],\n ...\n },\n }\n \n</code></pre>\n<p>Then open each team file and add the player data to the games.</p>\n<p>The ERA and WoBA code didn't look right in the original (or I didn't understand it), so I collected\nif, but didn't save it.</p>\n<p>I don't have any data files, so this code is not tested. But, it should give you an idea on how to\nproceed.</p>\n<p>You didn't state your goals for the code, but I suspect you might be better off\nwith a database of some kind rather than a bunch of json files.</p>\n<pre><code>import datetime\nimport json\n\nfrom collections import defaultdict\nfrom pathlib import Path\n\n\nBASE_DIR = Path('/Users/aus10/MLB/')\nGAME_DIR = BASE_DIR / 'Combined_Clean_Team_Data'\nFPTS_DIR = BASE_DIR / 'FPTS_Data'\nSAVE_DIR = BASE_DIR / 'Saved_Team_Data'\n\nteam_game_player_data = defaultdict(lambda:defaultdict(list))\nopposing_player_data = defaultdict(lambda:defaultdict(dict))\n\nfor path in FPTS_DIR.glob('*.json'):\n with path.open() as fpts_file:\n fantasy_data = json.load(fpts_file)\n\n for player_game_data in fantasy_data:\n date = datetime.date.fromisoformat(player_game_data['Day'][:10])\n team = player_game_data['Team']\n opponent = player_game_data['Opponent']\n\n team_game_player_data[team][date].append(player_game_data)\n\n opposing_player_data[team][date]['Opposing_P_ERA'] = player_game_data["EarnedRunAverage"]\n opposing_player_data[team][date]['Opposing_P_WoBA'] = player_game_data["PitchingWeightedOnBasePercentage"]\n \n\nfor path in GAME_DIR.glob('*.json'):\n with path.open() as team_file:\n data = json.load(team_file)\n \n team = data['Team']\n \n for game in data['Games']:\n game_day = dt.datetime.strptime(game['Date'], "%b %d, %Y").date()\n game['Players'] = team_game_player_data[team][game_day]\n \n filename = path.name\n with (SAVE_DIR / filename).open('w') as save_file:\n json.dump(data, save_file)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-06T07:08:14.703",
"Id": "250263",
"ParentId": "250007",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "250263",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T16:53:34.233",
"Id": "250007",
"Score": "3",
"Tags": [
"python"
],
"Title": "Combining Files from different folders"
}
|
250007
|
<p>Recently submitted a code assessment and I was wondering what other's feedback might be. What red flags can you see? I included gradle file if you're interested in running the application locally. Note that I used H2 to make it easier for the grader to run the app without having to worry about the DB they need install and configure. The expected input is of this sort ...</p>
<pre><code><string>,<name>
</code></pre>
<p>Examples:</p>
<pre><code>aauaiibbbru,Ivaana Bello
eiiuuegiebeici,Cami Diaz
eiiegbczu,Bob Bloch
</code></pre>
<p>Added README file for more clarity and details.
Here is the code.</p>
<p><strong>Application.java</strong></p>
<pre><code>package com.nr.stringville;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
</code></pre>
<p><strong>SubmissionController.java</strong></p>
<pre><code>package com.nr.stringville.controllers;
import com.google.common.base.CharMatcher;
import com.nr.stringville.models.Formula;
import com.nr.stringville.models.Submission;
import com.nr.stringville.repositories.SubmissionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
@RestController
public class SubmissionController {
public static final int TOP_LIST_SIZE = 10;
private final AtomicInteger validSubsCount = new AtomicInteger(0);
private final AtomicInteger invalidSubsCount = new AtomicInteger(0);
private final LocalDateTime startTime = LocalDateTime.now();
private final Formula formula = new Formula();
private volatile Submission lastSubmission = null;
private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss dd-MM-yyyy ");
@Autowired
private SubmissionRepository submissionRepository;
@RequestMapping("/")
public String index() {
return "Welcome to Stringville!";
}
@PostMapping("/submission")
public ResponseEntity submission(@RequestBody String body) {
// Verify the length (10,000 characters) and format (ASCII) of the String
if (body.length() > 10000) {
getInvalidSubsCount().getAndIncrement();
return ResponseEntity.status(400).body("Input too long");
}
if (!CharMatcher.ascii().matchesAllOf(body)) {
getInvalidSubsCount().getAndIncrement();
return ResponseEntity.status(400).body("Input contains invalid characters");
}
String[] parts = body.split(",");
// Validate string as having the comma, that the string.length>=1 and that name.length>=1
if (parts.length == 1) {
getInvalidSubsCount().getAndIncrement();
return ResponseEntity.status(400).body("Missing information");
}
if (parts[0].trim().length() < 1) {
getInvalidSubsCount().getAndIncrement();
return ResponseEntity.status(400).body("Invalid submission");
}
if (parts[1].trim().length() < 1) {
getInvalidSubsCount().getAndIncrement();
return ResponseEntity.status(400).body("Invalid name");
}
// Valid input. Proceed to save in the DB
getValidSubsCount().getAndIncrement();
Submission submission = new Submission(parts[1],parts[0],calculateScore(parts[0]));
try {
submissionRepository.save(submission);
} catch (Exception exception) {
exception.printStackTrace();
return ResponseEntity.status(400).body("Unable to persist submission. Verify there is no submission already recorded for this name");
}
// Record as last submission
setLastSubmission(submission);
return ResponseEntity.status(200).body("submission accepted");
}
@GetMapping("/results")
public ResponseEntity results() {
StringBuilder response = new StringBuilder("submission accepted");
List<Submission> submissions = submissionRepository.findAll();
// Sort results to be able to display top TOP_LIST_SIZE only
submissions.sort(Collections.reverseOrder());
if (submissions.size() > 0) {
response = new StringBuilder();
// Limit the result size to the least of TOP_LIST_SIZE or records count
int maxRecords = Math.min(submissions.size(),TOP_LIST_SIZE);
for (int i = 0; i < maxRecords; i++) {
response.append(submissions.get(i).getName()).append(",").append(submissions.get(i).getScore());
// Add a line break if not at the end of the list
if (i < maxRecords - 1) {
response.append("\n");
}
}
}
return ResponseEntity.status(200).body(response.toString());
}
@GetMapping("/health")
public ResponseEntity health() {
StringBuilder response = new StringBuilder();
response.append("System uptime : ").append(calculateTimeSince(startTime)).append("\n");
response.append("Valid submissions : ").append(getValidSubsCount()).append("\n");
response.append("Invalid submissions : ").append(getInvalidSubsCount()).append("\n");
if (getValidSubsCount().intValue() > 0 && getLastSubmission() != null) {
response.append("Last submission : ").append(getLastSubmission().getName()).append(" at ")
.append(getLastSubmission().getTime().format(formatter)).append("(")
.append(calculateTimeSince(getLastSubmission().getTime()))
.append(" ago)").append("\n");
} else {
response.append("Last submission : No submissions yet." + "\n");
}
return ResponseEntity.status(200).body(response.toString());
}
@GetMapping("/reset")
public ResponseEntity reset() {
getValidSubsCount().set(0);
getInvalidSubsCount().set(0);
setLastSubmission(null);
submissionRepository.deleteAll();
return ResponseEntity.status(200).body("system reset");
}
public AtomicInteger getValidSubsCount() {
return validSubsCount;
}
public AtomicInteger getInvalidSubsCount() {
return invalidSubsCount;
}
public void setValidSubsCount(int value) {
this.validSubsCount.set(value);
}
public void setInvalidSubsCount(int value) {
this.invalidSubsCount.set(value);
}
public void setSubmissionRepository(SubmissionRepository submissionRepository) {
this.submissionRepository = submissionRepository;
}
public int calculateScore(String string) {
Map<Character,Integer> charCountMap = new HashMap<>();
// Update count of occurrences
for (Character character : string.toCharArray()) {
charCountMap.merge(character, 1, Integer::sum);
}
return formula.getScore(charCountMap);
}
public String calculateTimeSince(LocalDateTime startTime) {
StringBuilder result = new StringBuilder();
long secondsElapsed = startTime.until(LocalDateTime.now(), ChronoUnit.MILLIS);
long diffSeconds = secondsElapsed / 1000 % 60;
long diffMinutes = secondsElapsed / (60 * 1000) % 60;
long diffHours = secondsElapsed / (60 * 60 * 1000);
long diffDays = secondsElapsed / (24 * 60 * 60 * 1000);
if (diffDays != 0) {
result.append(diffDays).append(" days, ");
}
if (diffHours != 0) {
result.append(diffHours).append(" hours, ");
}
if (diffMinutes > 1) {
result.append(diffMinutes).append(" minutes, ");
} else if (diffMinutes > 0) {
result.append(diffMinutes).append(" minute, ");
}
if (diffSeconds != 0) {
result.append(diffSeconds).append(" seconds");
}
if (result.toString().isEmpty()) {
result.append("Just now");
}
return result.toString();
}
public Submission getLastSubmission() {
return lastSubmission;
}
public void setLastSubmission(Submission lastSubmission) {
this.lastSubmission = lastSubmission;
}
}
</code></pre>
<p><strong>submission.java</strong></p>
<pre><code>package com.nr.stringville.models;
import javax.persistence.*;
import java.time.LocalDateTime;
@Entity
public class Submission implements Comparable<Submission>{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true)
private String name;
private String string;
private LocalDateTime time;
private int score;
public Submission(){
}
public Submission(String name, String string, int score){
this.name = name;
this.string = string;
this.time = LocalDateTime.now();
this.score = score;
}
public void setId(Long id) {
this.id = id;
}
public String getString() {
return string;
}
public String getName() {
return name;
}
public LocalDateTime getTime() {
return time;
}
public void setTime(LocalDateTime time) {
this.time = time;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public int compareTo(Submission o) {
return score - o.score;
}
}
</code></pre>
<p><strong>Formula.java</strong></p>
<pre><code>package com.nr.stringville.models;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class Formula {
private final List<Rule> ruleList = new ArrayList<>();
private static final String EXACT = "exactly";
private static final String EVERY = "every";
public Formula() {
// This can be offloaded to json file, or a db for runtime customization not requiring compiling
this.ruleList.add(new Rule('a',EXACT,3,1));
this.ruleList.add(new Rule('e',EXACT,2,5));
this.ruleList.add(new Rule('i',EVERY,2,2));
this.ruleList.add(new Rule('g',EXACT,1,3));
this.ruleList.add(new Rule('u',EVERY,1,1));
this.ruleList.add(new Rule('z',EVERY,1,-10));
}
public int getScore(Map<Character,Integer> charCountMap) {
int result = 0;
for (Rule rule : ruleList) {
Integer count = charCountMap.get(rule.character);
if (count == null || count == 0) {
// Don't do anything, just safety against null. Keeping this here for clarity
} else if (EXACT.equals(rule.getFrequency()) && count.equals(rule.getCount())) {
result = result + rule.getPoints();
} else if (EVERY.equals(rule.getFrequency())) {
result = result + Math.floorDiv(count,rule.getCount()) * rule.getPoints();
}
}
return result;
}
static class Rule {
private final char character;
private final String frequency;
private final int count;
private final int points;
public Rule(char character, String frequency, int count, int points) {
this.character = character;
this.frequency = frequency;
this.count = count;
this.points = points;
}
public String getFrequency() {
return frequency;
}
public int getCount() {
return count;
}
public int getPoints() {
return points;
}
}
}
</code></pre>
<p><strong>submissionrepository.java</strong></p>
<pre><code>package com.nr.stringville.repositories;
import com.nr.stringville.models.Submission;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface SubmissionRepository extends JpaRepository<Submission, Long> {
}
</code></pre>
<p><strong>build.gradle</strong></p>
<pre><code>buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:2.1.3.RELEASE")
}
}
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
bootJar {
baseName = 'stringville-boot'
version = '0.1'
}
repositories {
mavenCentral()
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-test'
compile("org.springframework.boot:spring-boot-starter-web")
runtimeOnly('com.h2database:h2')
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
compile group: 'com.google.guava', name: 'guava', version: '23.5-jre'
}
</code></pre>
<p><strong>README.md</strong></p>
<pre><code>Stringville Raffle Contest The city of Stringville organizes one of the most bizarre raffles in the country. Stringville citizens enter the competition by writing down their favorite string on a piece of paper along with their name, and putting this piece of paper in a big jar.
Unlike traditional raffles, Stringville's raffle rules are different. Instead of a single winner, there are multiple winners. Winners are selected based on a formula that is unknown to participants. At the end of the raffle the top N tickets with the highest scores are the winners.
For this year, the Stringville Raffle committee has privately agreed on the following formula. A ticket will be given:
+1 point if the string contains exactly three a's
+5 points if the string contains exactly two e's
+2 points for every two i's in the string
+3 points if the string contains exactly one g
+1 point for every u in the string
-10 points for every z in the string Note: All strings are case-insensitive and characters in the string do not need to be consecutive to get points. Participants can submit more than 1 string.
Here are a few example scores:
Raffle Ticket: aaaiibbbru,Ivaana Bello
Three a's (+1), two i's (+2), one u (+1) = 4 points
Raffle Ticket: eiiegiebeici,Camille Diaz
Two i's (+2), two i's (+2), one g (+3) = 7 points
Raffle Ticket: eiiegbczu,Bob Bloch
Two e's (+5), two i's (+2), one g (+3), one z (-10), one u (+1) = 1 point
Raffle Ticket: aaaluckycharmz,Derek Lee
One u (+1), one z (-10) = -9 point
Raffle Ticket: bananaram,Bonnie Chang
0 points
In this example, Camille, Ivaana, and Bob would be the lucky winners.
Stringville Raffle Service As a Software Engineer selected by Stringville to help automate this process, your task is to use this starter project to do the following:
Build an endpoint at /submission that will accept POST requests
The body of each submission will be plain text, containing the citizen's string followed by a comma and then their name. The payload (string,name) must not exceed 10,000 characters (ASCII only). The string must be at least one character. The name must be present.
Sample ticket: abekdkbjbjeheimaaabb,James LaCroix
If the ticket doesn't conform to the submission rules, then the endpoint should return a 400 status code with a message body explaining the reason why it wasn't accepted. Otherwise the endpoint should return a 200 status code indicating that the submission was accepted.
Build an endpoint at /results that will accept GET requests. The endpoint will display the top 10 winners based on the scoring system above.
The endpoint should display a list of the top 10 winners and their scores. Each winner should be on a new line with their name followed by their score (separated by a comma).
Example:
Cami Diaz,9 Ivaana Bello,5 Bob Bloch,1 ... Build an endpoint at /health that will accept GET requests. This endpoint should help you monitor your system. This should display any necessary information to know if your system is working as expected, including any useful statistics to monitor the health of your system. At a minimum, it should report the number of valid and invalid submissions.
Build an endpoint at /reset that will clear any saved or cached data, reset counts, results, and health checks.
Write unit tests that would help you validate your system. Don't forget to document any test cases you would have covered if you had more time.
Make your solution as performant as possible. The Stringville committee is interested in processing as many requests as possible. Describe any tools or scripts you used to measure performance, and what you measured (like requests per second), and any changes you made to make your solution more performant, if any.
Note:
Please use any dependency or libraries that you like. Your solution must run on port 8080 (unless documented in your instructions), and respond to /submission, /results, /health, and /reset as specified in 1-4. Please include comments where you think it's necessary. Feel free to provide a write-up of anything you would have done differently with more time, or any efforts related to performance testing. Provided A spring-boot gradle project is already stubbed out with a working test.
There is a run script run.sh which can start the application and a test script test.sh which shows basic examples of what requests look like. Feel free to edit these or create new scripts for testing purposes.
Our Evaluation We care not only about your solution, but also your general development approach. In addition to evaluating your solution for correctness and performance, we also heavily weigh your code structure and style.
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T17:13:57.183",
"Id": "490348",
"Score": "4",
"body": "This question should include more details and clarify the problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T17:49:53.330",
"Id": "490349",
"Score": "0",
"body": "Added more details and info."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T09:49:45.950",
"Id": "490388",
"Score": "0",
"body": "Please edit the readme.md into the question so that it can be read without gratituous horizontal scrolling. It's an essential part of the review so it has to be easily accessible."
}
] |
[
{
"body": "<p>Lot of code so I'm just going to concentrate on the interesting bits: <em>the scoring</em>.</p>\n<p>Your <code>Rule</code> class is written specifically to the limitations of the requirements and nothing else and so it allows no easy expansions. For example, if you wanted to give points for having certain consecutive characters you would have to redesign and rewrite everything in the scoring system.</p>\n<p>The <code>Formula</code> class is written so that it places quite a burden on the caller. They have to first calculate a character frequency map from the submission before they can pass the submission to the formula. This exposes the implementation of the rules to callers and thus makes changing them hard because changes to the rules now require changes to the caller too. The formula should only require the submission string as input.</p>\n<p>As it is now, the <code>Formula</code> class rejects the idea of dependency injection and instead creates the Rule instances itself. This is a big red flag considering that you're using Spring Boot, which is built on providing extremely capable DI features.</p>\n<p>Before you make optinizations like the character frequency map you should be able to show that it provides a considerable performance advantage over a more generic and more maintainable code. If you have those numbers, add them to the question. If you don't have them, you have fallen for <a href=\"https://en.wikipedia.org/wiki/Program_optimization#When_to_optimize\" rel=\"nofollow noreferrer\">premature optimization</a> and failed an evaluation.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T09:56:36.527",
"Id": "250027",
"ParentId": "250008",
"Score": "3"
}
},
{
"body": "<h1>Bug / Misfeature</h1>\n<p>The task description states</p>\n<blockquote>\n<p>Participants can submit more than 1 string.</p>\n</blockquote>\n<p>However due to the unique constraint on the <code>name</code> field, this is prevented (unless the "participant" uses unique names for each submission).</p>\n<p>This also removes a different problem in the code: In order to catch duplicate names you are catching (and swallowing) all <code>Exception</code>s in general. Never do this. Always only catch explicitly the exceptions you are expecting. There is so much that can go wrong when accessing a database, so this way you are ignoring any other possible errors.</p>\n<p>And you are counting a submission as valid even if the submission fails to be stored due to a duplicate name.</p>\n<p>Also printing the stack trace is not appropriate error handling in production code, especially in a web application where no one ever will see it.</p>\n<h1>Spring Data</h1>\n<p>There are several places where you could optimize things by taking advantage of the database.</p>\n<p>You shouldn't be storing the valid/invalid counts and the last submission in the controller. The count of valid submissions is the number of submissions in the database (especially ), so you can access that with <code>submissionRepository.count()</code> and the last submission can be accessed by declaring a method in <code>SubmissionRepository</code>:</p>\n<pre><code>public Submission findFirstByOrderByTimeDesc();\n</code></pre>\n<p>You shouldn't declare the class <code>Submission</code> as <code>Comparable</code> for several reasons:</p>\n<ul>\n<li>it's business logic that doesn't belong in an database entity</li>\n<li>it limits you to being able to sort by only one aspect</li>\n<li>you aren't taking advantage of the sorting features of the database</li>\n</ul>\n<p>Instead you can either declare another method in <code>SubmissionRepository</code>:</p>\n<pre><code>public List<Submission> findTop10ByOrderByScoreDesc();\n</code></pre>\n<p>or, if you don't want to hard-code the number of winners into the method name, the <code>findAll()</code> method optionally takes a <code>Pagination</code> object:</p>\n<pre><code>Page<Submission> submissions = submissionRepository.findAll(PageRequest.of(0, 10, Sort.by(Sort.Direction.DESC, "score")));\n</code></pre>\n<p><em>(More possibly later)</em></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T17:55:25.340",
"Id": "490526",
"Score": "0",
"body": "This is fantastic feedback, thank you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T10:16:04.030",
"Id": "250028",
"ParentId": "250008",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T16:56:29.930",
"Id": "250008",
"Score": "4",
"Tags": [
"java",
"api",
"rest"
],
"Title": "Application to calculate scores of strings submitted to an endpoint"
}
|
250008
|
<p>I wrote a calculator that can solve equations with variables using matplotlib and sympy.
I am looking for tips on performance and style.
How can I improve on this calculator? Is it a good idea to use sympy for this purpose?
<a href="https://repl.it/talk/share/Introducing-msh-A-graphing-shell/55694" rel="nofollow noreferrer">Repl.it</a></p>
<pre><code>import sympy
import matplotlib.pyplot as plt
class Iterator:
name, equation, val = None, None, None
def __repr__(self):
return self.__str__()
def __init__(self, nameIn, equationIn, valIn):
self.name, self.equation, self.val = nameIn, equationIn, valIn
def __str__(self):
return self.get_name() + "," + str(self.get_value())
def iterate(self):
replaced = self.equation.replace(self.name, str(self.val))
self.val = sympy.sympify(replaced)
def get_name(self):
return self.name
def get_value(self):
return self.val
def graph():
numTimes = input("How many points ")
x = input("What to calculate ")
points = []
i = 0
numInputs = int(input("How many variables "))
j = 0
replaced = []
iterators = []
while numInputs > j:
name = input("What's the variabe name ")
iter = input("What's the iteration equation ")
val = int(input("What's the starting value "))
iterators.append(Iterator(name, iter, val))
j += 1
while i < int(numTimes):
replaced = x.replace("n", str(i))
for j in iterators:
replaced = replaced.replace(j.get_name(), str(j.get_value()))
j.iterate()
final = sympy.sympify(replaced)
right_type = int(final)
points.append(right_type)
i += 1
plt.plot(points)
plt.ylabel(input("What's the y label "))
plt.show()
while(True):
command = input(">> ")
if command == "graph":
graph()
elif command == "help":
print("""
msh.
Used for graphing.
Commands:
graph: an interactive graphing calculator
help: bring up this message
quit: exit msh
""")
elif command == "quit":
break
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T18:24:24.837",
"Id": "490350",
"Score": "4",
"body": "In Python, indentation is important. Please fix your indentation. Why did you create a class if it's basically an initialisation and one big function after that?"
}
] |
[
{
"body": "<h1>Indentation</h1>\n<p>You should use four spaces instead of two.</p>\n<h1>Spacing</h1>\n<p>Your class methods should be separated by an empty line, so everything doesn't look so crowded.</p>\n<h1>Getters</h1>\n<p>Since all class variables are public (except <code>_var</code> and <code>__var</code> variables), you don't need to define getters to access these properties. Simple do <code>Iterator.name</code>, etc.</p>\n<h1><code>Iterator.__str__</code></h1>\n<p>You should utilize <code>f""</code> strings to directly include variables in strings.</p>\n<pre><code>def __str__(self):\n return f"{self.name},{self.val}"\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-18T10:10:44.480",
"Id": "500130",
"Score": "0",
"body": "But doesn't it make sense to make all variables \"private\" (__var or at least _var) and provide setters and getters with @property?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-18T15:08:13.177",
"Id": "500149",
"Score": "1",
"body": "@TomGebel Not really. There's no structural advantage to making something private (which isn't enforced in Python anyway) and then offering for anyone to set it to anything; public accomplishes the same thing and is more Python-idiomatic."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-18T09:50:11.000",
"Id": "253608",
"ParentId": "250009",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "253608",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T17:34:31.657",
"Id": "250009",
"Score": "4",
"Tags": [
"python",
"performance",
"graph",
"calculator",
"matplotlib"
],
"Title": "A graphing calculator"
}
|
250009
|
<p>I have built a To Do App in Javascript, using Webpack and some modules. The app lets you store projects (School, Sport, Grocery, etc.)... And inside these projects, you can store todo items... You can also edit the todo item, and click it do delete/finish it.</p>
<p>The app should be built with OOP principles in mind, and that's the main concern with the code, and the reason that I want it to be reviewed. This is the weakness of my code. And I would want you to give me tips on how to improve this...</p>
<p>It is my first post here... I hope I followed all the rules. And that is why I posted only the following code here, and shared my github repo if there is a person generous to look into it.</p>
<p><a href="https://github.com/polhek/To-Do-List" rel="nofollow noreferrer">Github repo</a>! (Posted it because of webpack...)</p>
<p>Index.js:</p>
<pre><code>if (myProjects.length == 0) {
defaultProject();
}
//defaultProject();
// Add new project!
newProjectListener.addEventListener("submit", (event) => {
event.preventDefault();
const newProjectTitle = document.getElementById("newProjectName").value;
if (newProjectTitle == "") {
} else {
newProjectEvent(event);
addProjectUI(newProject);
// saveToLocalStorage(myProjects);
emptyForm();
}
});
// Delete project, adding event listeners to all future trash buttons for projects...
window.addEventListener("click", (event) => {
let element = event.target.classList.contains("bi-trash")
? event.target.parentElement
: event.target.classList.contains("trash-project")
? event.target
: false;
if (element) {
let itemToRemove = element.parentElement.parentElement;
deleteProject(itemToRemove);
deleteItemUI(itemToRemove);
cleanToDoView();
// localStorage.clear();
// saveToLocalStorage(myProjects);
}
});
// clicked project
projectListDiv.addEventListener("click", (event) => {
if (event.target.tagName == "P") {
resetClickedProject();
clickedProject(event);
clickedProjectIndex = idClickedProject(event);
cleanToDoView();
render();
}
});
// new to do...
newToDoListener.addEventListener("submit", (event) => {
event.preventDefault();
if (
toDoTitle.value == "" ||
description.value == "" ||
dueDate.value == "" ||
priority.value == "" ||
note.value == ""
) {
} else {
newToDoEvent(event, clickedProjectIndex);
let toDo = newToDo;
appendToDo(toDo);
// localStorage.clear();
// saveToLocalStorage(myProjects);
emptyToDoForm();
}
});
tableListener.addEventListener("click", (event) => {
let element = event.target.classList.contains("delete")
? event.target.parentElement.parentElement
: event.target.classList.contains("fa-check")
? event.target.parentElement.parentElement.parentElement
: false;
if (element) {
let deleteItem = element;
deleteToDoFromObject(deleteItem, clickedProjectIndex);
deletToDoUI(deleteItem);
// localStorage.clear();
// saveToLocalStorage(myProjects);
}
});
window.addEventListener("click", (event) => {
let element = event.target.classList.contains("edit-button")
? event.target.parentElement.parentElement
: event.target.classList.contains("fa-pencil-square-o")
? event.target.parentElement.parentElement.parentElement
: false;
if (element) {
toDoIndex = clickedToDoIndex(event, element);
editTodo(clickedProjectIndex, toDoIndex);
}
});
editToDo.addEventListener("submit", (event) => {
event.preventDefault();
editFinish(clickedProjectIndex, toDoIndex);
cleanToDoView();
render();
// localStorage.clear();
// saveToLocalStorage(myProjects);
});
const render = () => {
myProjects[clickedProjectIndex].toDos.forEach((todo) => {
appendToDo(todo);
});
};
const initialLoad = () => {
myProjects.forEach((project) => {
addProjectUI(project);
console.log(project)
const projectHeader = document.querySelector(".projectName");
projectHeader.textContent = project.title
});
};
initialLoad();
const initalTodoLoad = () => {
myProjects[0].toDos.forEach((todo) => {
appendToDo(todo);
});
};
initalTodoLoad();
</code></pre>
<p>projectFactory.js:</p>
<pre><code>let myProjects = [];
let newProject;
// let myProjects = localStorage.getItem("projects")
// ? JSON.parse(localStorage.getItem("projects"))
// : [
// ];
const saveToLocalStorage = () => {
localStorage.setItem("projects", JSON.stringify(myProjects));
};
// Project factory, which takes in title and makes toDo array, to which the toDos will be added...
const newProjectFactory = (id, title) => {
const toDos = [];
const add_toDo = (toDo) => {
toDos.push(toDo);
};
return { id, title, toDos, add_toDo };
};
const newProjectEvent = (event) => {
// DOM elements of form ...
event.preventDefault();
const newProjectTitle = document.getElementById("newProjectName").value;
let ID;
if (myProjects.length > 0) {
ID = myProjects[myProjects.length - 1].id + 1;
} else {
ID = 0;
}
newProject = newProjectFactory(ID, newProjectTitle);
myProjects.push(newProject);
};
</code></pre>
|
[] |
[
{
"body": "<p>This review will focus on what <a href=\"https://en.wikipedia.org/wiki/Object-oriented_programming\" rel=\"nofollow noreferrer\">object oriented programming</a> [oop] is and how we can use two concepts of oop (encalpsulation and abstraction) in your code to make it more object oriented.</p>\n<p>The self-drawn pictures of this review come from my <a href=\"https://github.com/rgabisch/presentations/tree/master/object-oriented-programming\" rel=\"nofollow noreferrer\">Github-Repository for a presentation that is supposed to show the basics of oop</a>.</p>\n<h1>How to write Object-Oriented Code</h1>\n<p>Object-Oriented Programming is based on the following 4 concepts:</p>\n<ul>\n<li><a href=\"https://en.wikipedia.org/wiki/Abstraction_(computer_science)\" rel=\"nofollow noreferrer\">abstraction</a></li>\n<li><a href=\"https://en.wikipedia.org/wiki/Encapsulation_(computer_programming)\" rel=\"nofollow noreferrer\">encapsulation</a></li>\n<li><a href=\"https://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)\" rel=\"nofollow noreferrer\">inheritance</a></li>\n<li><a href=\"https://en.wikipedia.org/wiki/Polymorphism_(computer_science)\" rel=\"nofollow noreferrer\">polymorphism</a></li>\n</ul>\n<p>Not all of these concepts have to be implemented per file, class, object, ... in order to be object-oriented.</p>\n<p>But following the concepts of abstraction and encapsulation especially at the beginning will make the code much more object-oriented.</p>\n<p>To make these concepts easier to remember, there is the acronym called <em>"a pie"</em>.</p>\n<p><img src=\"https://github.com/rgabisch/presentations/raw/master/object-oriented-programming/images/concepts.png\" alt=\"image, that lists the four concepts of oop and a drawing of a pie\" /></p>\n<h1>Encapsulation</h1>\n<h2>What it is</h2>\n<blockquote>\n<p>Encapsulation is used to hide the values or state of a structured data object inside a class, preventing unauthorized parties' direct access to them.</p>\n<p>— <a href=\"https://en.wikipedia.org/wiki/Encapsulation_(computer_programming)\" rel=\"nofollow noreferrer\">wikipedia</a></p>\n</blockquote>\n<p><img src=\"https://github.com/rgabisch/presentations/raw/master/object-oriented-programming/images/encapsulation.png\" alt=\"image, that describes encapsulation with the sentence "It is the hiding of the internals." and an drawing of a lock.\" /></p>\n<h1>What is against the concept of encapsulation?</h1>\n<p>The variable <code>myProjects</code> has been defined globally and can be read and modified by anyone and everyone.</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>// in projectFactory.js\nlet myProjects = [];\n\n// in index.js\nif (myProjects.length == 0) { /* ... */ }\n//...\nconst newProjectEvent = (event) => {\n //...\n if (myProjects.length > 0) {/ * ... */}\n // ...\n myProjects.push(newProject); \n};\n</code></pre>\n<p>Breaking the code is easy. All that has to be done is to assign a different value to <code>myProjects</code>:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>myProjects = "";\n</code></pre>\n<p>Now you will think that nobody would do that, but when you work in a team it goes faster than expected. Even if it is accidental.</p>\n<hr />\n<p>The same for <code>toDos</code> of you project object:</p>\n<blockquote>\n<pre class=\"lang-javascript prettyprint-override\"><code>myProjects[clickedProjectIndex].toDos.forEach((todo) => {\n appendToDo(todo);\n});\n</code></pre>\n</blockquote>\n<p>The variable <code>toDos</code> can be intervened again without restriction and we could modify it again: <code>myProjects[clickedProjectIndex].toDos = /* something wrong */</code></p>\n<h2>How can we fix the violations?</h2>\n<p>We can hide the variables inside objects with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields\" rel=\"nofollow noreferrer\">#-Symbol</a>.</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>class ProjectCollection {\n #projects = [];\n}\n\nconst projects = new ProjectCollection();\n// not possible anymore\nprojects.projects = /* something wrong */ \n</code></pre>\n<h1>Abstraction</h1>\n<h2>What it is</h2>\n<blockquote>\n<p>The term encapsulation refers to the hiding of state details, but extending the [...] associate behavior most strongly with the data, and standardizing the way that different data types interact, is the beginning of abstraction.</p>\n<p>— <a href=\"https://en.wikipedia.org/wiki/Abstraction_(computer_science)#Abstraction_in_object_oriented_programming\" rel=\"nofollow noreferrer\">wikipedia</a></p>\n</blockquote>\n<p><img src=\"https://github.com/rgabisch/presentations/raw/master/object-oriented-programming/images/abstraction.png\" alt=\"\" /></p>\n<h1>What is against the concept of abstraction?</h1>\n<p>Since the code has no encapsulation, there is no abstraction. For example, we ask whether the length of the array <code>myProjects</code> is 0:</p>\n<blockquote>\n<pre class=\"lang-javascript prettyprint-override\"><code>if (myProjects.length == 0) {\n // ...\n}\n</code></pre>\n</blockquote>\n<p>However, we can abstract this by calling a method:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>if (myProjects.containsNon()) {\n // ...\n}\n</code></pre>\n<pre class=\"lang-javascript prettyprint-override\"><code>const myProjects = new ProjectCollection();\n\nclass ProjectCollection {\n #projects = [];\n\n containsNon() {\n return this.#projects == 0;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T19:28:00.603",
"Id": "490538",
"Score": "0",
"body": "Okey, will keep in mind. So basically also modules (IIFE) should be some kind of object-oriented programming. As they help you encapsulate and hide the inner parts of code, and therefore cannot be accessed from the outside?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T02:44:13.110",
"Id": "490570",
"Score": "1",
"body": "Important thing to note about [private class fields](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields): “_Both Public and private field declarations are an experimental feature (stage 3) proposed at TC39, the JavaScript standards committee.\n\nSupport in browsers is limited, but the feature can be used through a build step with systems like Babel. See the compat information below._”"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T04:46:16.047",
"Id": "490573",
"Score": "1",
"body": "@ŽigaGrošelj, yes, these concepts can also be followed with IIFE. :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T18:06:15.270",
"Id": "250086",
"ParentId": "250013",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "250086",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T18:54:53.690",
"Id": "250013",
"Score": "2",
"Tags": [
"javascript",
"object-oriented",
"modules",
"to-do-list"
],
"Title": "To Do List Project - app lets you make projects and inside of this projects you can save to-dos"
}
|
250013
|
<p>It might help to check my <a href="https://codereview.stackexchange.com/questions/249890/c-profile-scraper">previous question</a> out, its part of the same application. The only minor changes are with the entity class names. They now each have their own entities, and I use interfaces for polymorphism so each site has its own entity, rather than ambious class names like <code>ProfilePost</code>, <code>ProfileConnection</code>, which represented all implementations (sites).</p>
<p>This class is probably the worst area of the whole application, as time developed it got larger and larger, and I wasn't at a point where I could stop for long enough to completely refactor it.</p>
<p><strong>What does this class do?</strong></p>
<p>It implements the ISocialEventHandler, and each implementation of my scraper has its own event handler for each site. This allows each site to have slightly different ways of doing things to scrape it. If you see my previous question, you'll see how this class gets used in practice.</p>
<p><strong>What do I want help with?</strong></p>
<p>I would like to try and get some advice on how I can reduce the size of it, and what areas of the class shouldn't be part of the event handler. I guess I sort of used this class as "everything that needs to be done for each implementation of a scraper type".</p>
<p>I already sort of know what to do, although it's hard to apply that in practice when you have never done it before, it is also hard to know which areas to focus on, what is bad code if you were never taught what bad code was?</p>
<p>When giving suggestions, it would help me to know what sort of class names I should give new classes, its an area I struggle most in and I usually end up making classes that don't have descriptive names, or don't explain what they are doing.</p>
<p>Please also give any other general recommendations, to the class in question or associated classes.</p>
<p>So TLDR: Can someone give me a practical example (in code) of how I can I abstract areas the following class, into their own areas (SRP).</p>
<p>Here is the class in question (500+ lines):</p>
<pre><code>public class DellyEventHandler : AbstractSocialEventHandler, ISocialEventHandler
{
private bool _loginNeeded = true;
private readonly IWebDriver _webDriver;
private readonly ScraperAccountDao _accountDao;
private readonly DellyProfileDao _profileDao;
private readonly ScraperSettings _scraperSettings;
private readonly IScraperValidator _scraperValidator;
private readonly ILogger _logger;
private readonly Client _bugSnagClient;
private readonly NotificationSender _notificationSender;
private ScraperAccount _currentAccount;
private string _currentItem;
private int _itemsProcessedSinceLogin;
public DellyEventHandler(
IWebDriver webDriver,
ScraperAccountDao accountRepository,
DellyProfileDao profileDao,
ScraperSettings scraperSettings,
IScraperValidator scraperValidator,
ILogger logger,
Client bugsnagClient,
NotificationSender notificationSender)
{
_webDriver = webDriver;
_accountDao = accountRepository;
_profileDao = profileDao;
_scraperSettings = scraperSettings;
_scraperValidator = scraperValidator;
_logger = logger;
_bugSnagClient = bugsnagClient;
_notificationSender = notificationSender;
}
public override string GetLoginPageUrl()
{
return "https://delly.test/accounts/login";
}
public override string GetLogoutPageUrl()
{
return "https://delly.test/accounts/logout";
}
public override void NavigateToProfile()
{
_webDriver.Navigate().GoToUrl(_currentItem);
}
public override bool TryWaitForProfileToLoad()
{
return _webDriver.WaitUntilVisible(By.XPath(ScraperDomSelectors.DellyProfileFollowers), 3) != null;
}
public override bool IsLoginNeeded()
{
return _loginNeeded;
}
public override void Login()
{
if (!_loginNeeded)
{
return;
}
if (_webDriver.PageSource.Contains("js logged-in"))
{
Logout();
}
_webDriver.Navigate().GoToUrl(GetLoginPageUrl());
if (!TryGetAccount(out _currentAccount))
{
WaitUntilAccountAvailable();
Login();
return;
}
var usernameField = _webDriver.WaitUntilVisible(By.Name("username"), 5);
var passwordField = _webDriver.WaitUntilVisible(By.Name("password"), 0);
if (usernameField == null || passwordField == null)
{
throw new Exception("Failed to find the required login form fields.");
}
usernameField.SendKeys(_currentAccount.Username);
passwordField.SendKeys(_currentAccount.Password);
passwordField.SendKeys(Convert.ToString(Convert.ToChar((object)57351)));
if (_webDriver.WaitUntilVisible(By.Id("slfErrorAlert"), 3) != null)
{
OnFailedLogin();
return;
}
if (_webDriver.PageSource.Contains("challengeType") || _webDriver.PageSource.Contains("RecaptchaChallengeForm") || _webDriver.PageSource.Contains("Help Us Confirm It's You"))
{
OnFailedLogin();
return;
}
_itemsProcessedSinceLogin = 0;
_loginNeeded = false;
}
private void OnFailedLogin()
{
_accountDao.MarkAccountAsDisabled(_currentAccount.Id);
Logout();
Login();
}
private void WaitUntilAccountAvailable()
{
_logger.Warning($"Worker {StaticState.WorkerId} is waiting for an available account.");
var waitingSince = DateTime.Now;
var waitTicks = 0;
while (!TryGetAccount(out var _, false))
{
// If we've been waiting for an account for longer than 30 minutes, lets send a notification as a warning.
if (waitTicks >= 60)
{
_notificationSender.SendNotification($"Worker {StaticState.WorkerId} has been waiting for an account since {waitingSince.ToShortTimeString()}.", "829YaL");
waitTicks = 0;
}
Thread.Sleep(TimeSpan.FromSeconds(30));
waitTicks++;
}
_logger.Success("We found an available account, lets continue.");
}
public override ISocialProfile CreateProfile()
{
var bio = GetBio();
var name = GetName();
var profile = new DellyProfile(_profileDao, _scraperSettings, _scraperValidator)
{
Url = GetUrl(),
Username = GetUsername(),
Name = name,
Picture = GetProfilePicture(),
Bio = bio,
IsPrivate = GetIsPrivate(),
FollowerCount = GetFollowerCount(),
FollowingCount = GetFollowingCount(),
SnapchatFound =
_scraperValidator.StringContainsSnapchatUsername(bio.ToLower()) ||
_scraperValidator.StringContainsSnapchatUsername(name.ToLower())
};
if (_scraperValidator.TryExtractAgeFromString(bio, out var ageGuessed))
{
profile.AgeGuessed = ageGuessed;
}
if (_scraperValidator.StringContainsFemaleName(name.CleanQueueItem()) || _scraperValidator.StringContainsFemaleName(profile.Username.CleanQueueItem()))
{
profile.GenderGuessed = 'F';
}
else
{
profile.GenderGuessed = 'M';
}
if (!profile.SnapchatFound)
{
return profile;
}
if (_scraperValidator.TryExtractSnapchatUsernameFromString(bio.ToLower(), out var snapchatUsername) ||
_scraperValidator.TryExtractSnapchatUsernameFromString(name.ToLower(), out snapchatUsername))
{
profile.SnapchatUsername = snapchatUsername;
}
return profile;
}
private bool TryGetAccount(out ScraperAccount profile, bool markAsFetched = true)
{
return _accountDao.TryFindAccount(
out profile,
1,
int.Parse(_scraperSettings["minutes_to_wait_since_account_throttled"]),
int.Parse(_scraperSettings["minutes_to_wait_since_account_fetched"]),
markAsFetched);
}
public override void Logout()
{
_loginNeeded = true;
_webDriver.Navigate().GoToUrl(GetLogoutPageUrl());
}
private long GetProfileId()
{
var jse = (IJavaScriptExecutor) _webDriver;
var profileIdFromSharedData = jse.ExecuteScript("return window._sharedData.entry_data.ProfilePage[0].logging_page_id;")?.ToString();
if (profileIdFromSharedData != null && long.TryParse(profileIdFromSharedData.Split("_").Last(), out var profileId))
{
return profileId;
}
var username = new Uri(_currentItem).AbsolutePath.Replace("/", "");
var possibleProfileId = _webDriver.PageSource.GetInbetween(
"window.__additionalDataLoaded('/" + username + "/',{\"logging_page_id\":\"", "\",");
if (string.IsNullOrEmpty(possibleProfileId) || !long.TryParse(possibleProfileId.Split("_").Last(), out profileId))
{
throw new Exception("Failed to find the unique ID for the profile.");
}
return profileId;
}
public override List<DellyConnection> GetConnections()
{
var connections = new List<DellyConnection>();
var endCursor = "";
while (true)
{
if (connections.Count >= int.Parse(_scraperSettings["maximum_connections_to_scrape_for_profile"]))
{
break; // We've got enough
}
var profileId = GetProfileId();
if (profileId < 1)
{
throw new Exception("Failed to find the unique ID for the profile.");
}
var jse = (IJavaScriptExecutor) _webDriver;
var csrfToken = jse.ExecuteScript("return window._sharedData.config.csrf_token;")?.ToString();
HttpResponseMessage httpResponse;
try
{
httpResponse = DellyConnectionCollector.GetConnectionsFromApi(profileId, csrfToken, _webDriver.Manage().Cookies.AllCookies, endCursor);
}
catch (AggregateException)
{
SwitchAccount(true);
continue;
}
if (httpResponse.StatusCode == HttpStatusCode.TooManyRequests)
{
_logger.Warning($"Connections have been throttled for {_currentAccount.Username} ({_currentAccount.Id}).");
SwitchAccount(true);
continue;
}
var responseText = httpResponse.Content.ReadAsStringAsync().Result;
if (string.IsNullOrEmpty(responseText))
{
_logger.Warning("The Delly testing API returned an empty string for connection nodes.");
return new List<DellyConnection>();
}
if (responseText.Contains("https://www.delly.test/challenge/"))
{
_logger.Warning($"Connections have been challenged for {_currentAccount.Username} ({_currentAccount.Id}).");
_accountDao.MarkAccountAsDisabled(_currentAccount.Id);
Logout();
Login();
NavigateToProfile();
continue;
}
// TODO: Validate if it contains valid json.
JObject responseJsonObject = JObject.Parse(responseText);
var connectionNodes = JsonConvert.DeserializeObject<JArray>(responseJsonObject["data"]["user"]["followed_by"].ToString());
foreach (var connection in connectionNodes)
{
connections.Add(new DellyConnection
{
Item = "https://delly.test/" + connection["node"]["username"],
IsPrivate = connection["node"]["is_private"].ToString() == "True",
});
}
if (responseJsonObject["data"]["user"]["followed_by"]["page_info"]["has_next_page"].ToString().ToLower() != "true")
{
break;
}
endCursor = responseJsonObject["data"]["user"]["followed_by"]["page_info"]["end_cursor"].ToString();
Thread.Sleep(1000);
}
return connections;
}
public override string GetUrl()
{
return _webDriver.Url;
}
public override string GetUsername()
{
return _webDriver.WaitUntilVisible(By.XPath(ScraperDomSelectors.DellyProfileUsername), 0)?.GetAttribute("innerHTML") ?? "";
}
public override string GetName()
{
return _webDriver.WaitUntilVisible(By.XPath(ScraperDomSelectors.DellyProfileName), 0)?.GetAttribute("innerHTML") ?? GetUsername();
}
public override string GetProfilePicture()
{
return _webDriver.WaitUntilVisible(By.XPath(ScraperDomSelectors.DellyProfilePicture), 0).GetAttribute("src");
}
public override string GetBio()
{
var bioElement = _webDriver.WaitUntilVisible(By.XPath(ScraperDomSelectors.DellyProfileBio), 0);
return bioElement == null ? "" : bioElement.GetAttribute("innerText").Replace(Environment.NewLine, " ");
}
public override bool GetIsPrivate()
{
return _webDriver.PageSource.Contains("This Account is Private");
}
public override int GetFollowerCount()
{
return GetFollowBoxCount(ScraperDomSelectors.DellyProfileFollowers);
}
public override int GetFollowingCount()
{
return GetFollowBoxCount(ScraperDomSelectors.DellyProfileFollowing);
}
private int GetFollowBoxCount(string xpathSelector)
{
var followingElement = _webDriver.WaitUntilVisible(By.XPath(xpathSelector), 0);
var titleAttributeValue = followingElement.GetAttribute("title");
if (titleAttributeValue.Length > 0)
{
return int.Parse(titleAttributeValue.Replace(",", ""));
}
return int.Parse(followingElement.GetAttribute("innerHTML").Replace(",", ""));
}
public override List<DellyPost> GetPosts(string owner)
{
return new List<DellyPost>
{
new DellyPost
{
Media = GetPostMedia(owner)
}
};
}
public override List<DellyPostMedia> GetPostMedia(string owner)
{
var media = new List<DellyPostMedia>();
foreach (var domElement in _webDriver.FindElements(By.XPath(ScraperDomSelectors.DellyProfilePostPicture)).Take(20))
{
if (string.IsNullOrEmpty(domElement.GetProperty("src")))
{
continue;
}
media.Add(new DellyPostMedia
{
CdnUrl = domElement.GetProperty("src"),
MetaData = domElement.GetAttribute("alt")
});
}
return media;
}
public override void SetCurrentItem(string item)
{
_currentItem = item;
_itemsProcessedSinceLogin++;
if (_itemsProcessedSinceLogin > int.Parse(_scraperSettings["maximum_scrapes_before_forced_login"]))
{
// Lets test on another account, switch it.
_loginNeeded = true;
}
}
public override List<DellyConnection> GetFilteredConnections(List<DellyConnection> connections)
{
var filteredConnections = new List<DellyConnection>();
foreach (var connection in connections)
{
var connectionUrl = connection.Item;
if (!_scraperValidator.StringContainsMaleFirstName(connectionUrl.CleanQueueItem()) &&
!_scraperValidator.StringContainsMaleUsername(connectionUrl.CleanQueueItem()) &&
!_scraperValidator.StringContainsAnythingBad(connectionUrl) &&
!_scraperValidator.StringContainsAnythingBad(connectionUrl.CleanQueueItem()))
{
filteredConnections.Add(connection);
}
}
return filteredConnections;
}
public override string GetPageSource()
{
return _webDriver.PageSource;
}
public override List<ScraperQueueItem> ConvertConnectionsToQueueItems(List<DellyConnection> connections)
{
var queueItems = new List<ScraperQueueItem>();
foreach (var connection in connections)
{
var isConfirmed = true; // TODO
queueItems.Add(new ScraperQueueItem(0, Utilities.GetConsistentSocialUrl(connection.Item), 1, connection.IsPrivate, isConfirmed));
}
return queueItems;
}
public override bool IsProfileVisitsThrottled()
{
return _webDriver.PageSource.Contains("wait a few minutes before you try again");
}
public override bool IsProfileNotFound()
{
return _webDriver.PageSource.Contains("Page Not Found");
}
public override void SwitchAccount(bool markCurrentAsThrottled)
{
if (markCurrentAsThrottled)
{
_accountDao.MarkAccountAsThrottled(_currentAccount.Id);
}
Logout();
Login();
NavigateToProfile();
}
}
</code></pre>
<p>Below you can find snippets of classes involved with the class I'm focusing on.</p>
<p>ScraperSettings:</p>
<pre><code>public class ScraperSettings : Dictionary<string, string>
{
private readonly ScraperSettingsDao _scraperSettingsDao;
private readonly Timer _timer;
public ScraperSettings(ScraperSettingsDao scraperSettingsDao)
{
_scraperSettingsDao = scraperSettingsDao;
_timer = new Timer(Load, null, 0, 60 * 1000);
Load();
}
private void Load(object o = null)
{
foreach (DataRow settingsRow in _scraperSettingsDao.GetSettingsTable().Rows)
{
this[(string)settingsRow["name"]] = (string)settingsRow["value"];
}
}
}
</code></pre>
<p>ScraperAccount (entity, database mapper to and from):</p>
<pre><code>public class ScraperAccount
{
public int Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public int TypeId { get; set; }
}
</code></pre>
<p>IScraperValidator:</p>
<pre><code>public interface IScraperValidator
{
bool StringContainsMaleFirstName(string str);
bool StringContainsFemaleName(string str);
bool StringContainsMaleUsername(string str);
bool IsStringForeign(string str);
bool StringContainsSnapchatUsername(string str);
bool TryExtractSnapchatUsernameFromString(string str, out string snapchatUsername);
bool TryExtractAgeFromString(string str, out int age);
bool StringContainsGenericBadPhrase(string str);
bool StringContainsPromotion(string str);
bool StringContainsMakeUpPhrase(string str);
bool StringContainsDeletedProfilePhrase(string str);
bool StringContainsAnythingBad(string str);
}
</code></pre>
<p>IScraperValidator Implementation (DellyValidator):</p>
<pre><code>public class DellyValidator : IScraperValidator
{
private readonly List<string> _maleFirstNamePhrases;
private readonly List<string> _maleUsernamePhrases;
private readonly List<string> _femaleFirstNamePhrases;
public DellyValidator(
List<string> maleFirstNamePhrases,
List<string> maleUsernamePhrases,
List<string> femaleFirstNamePhrases)
{
_maleFirstNamePhrases = maleFirstNamePhrases;
_maleUsernamePhrases = maleUsernamePhrases;
_femaleFirstNamePhrases = femaleFirstNamePhrases;
}
public bool StringContainsMaleFirstName(string str)
{
return _maleFirstNamePhrases.Any(s => str.StartsWith(s, StringComparison.InvariantCultureIgnoreCase));
}
public bool StringContainsFemaleName(string str)
{
return _femaleFirstNamePhrases.Any(s => str.Contains(s, StringComparison.InvariantCultureIgnoreCase));
}
public bool StringContainsMaleUsername(string str)
{
return _maleUsernamePhrases.Any(s => str.Contains(s, StringComparison.InvariantCultureIgnoreCase));
}
public bool IsStringForeign(string str)
{
var foreignTriggers = new List<string>
{
"african american", "romanian", "italian", "nigerian", "australian", "russian", "aussie", "australian", "australia", "collumbian",
"french", "brazilian", "arabic", "polish", "swedish",
"california", "washington", "michigan", "arizona", "massachusetts", "pennsylvania", "wisconsin", "connecticut", "louisiana", "kentucky"
};
return foreignTriggers.Any(str.ContainsIgnoreCase) || HasArabicCharacters(str);
}
private bool HasArabicCharacters(string str)
{
return new Regex("[\u0600-\u06ff]|[\u0750-\u077f]|[\ufb50-\ufc3f]|[\ufe70-\ufefc]").IsMatch(str);
}
public bool StringContainsSnapchatUsername(string str)
{
var snapTriggers = new List<string>
{
"", " ", " :", "", "sc’", "sc - ", "sc ", "sc:", "scm ", "scm;", "sc- ", "sc.", "sc-", "sc ~", "sc;", "sc; ", "sc~", "sc/", "snapchat:",
"snapchat - ", "snapchat-", "snap~", "snap =", "snap:", "add my sc", "add me on sc", "add me sc", "add my snap", "add my snapchat", "add me on snap",
"scm~", "scm ~", "sc•", "sc •", " "
};
return snapTriggers.Any(str.Contains);
}
public bool TryExtractSnapchatUsernameFromString(string str, out string snapchatUsername)
{
if (
TryExtractSnapchatUsernameFromConvention("sc:", str, out snapchatUsername) ||
TryExtractSnapchatUsernameFromConvention("sc-", str, out snapchatUsername) ||
TryExtractSnapchatUsernameFromConvention("sc -", str, out snapchatUsername) ||
TryExtractSnapchatUsernameFromConvention("sc~", str, out snapchatUsername) ||
TryExtractSnapchatUsernameFromConvention("sc ~", str, out snapchatUsername) ||
TryExtractSnapchatUsernameFromConvention("scm ~", str, out snapchatUsername) ||
TryExtractSnapchatUsernameFromConvention("sc;", str, out snapchatUsername) ||
TryExtractSnapchatUsernameFromConvention("sc:", str, out snapchatUsername) ||
TryExtractSnapchatUsernameFromConvention("sc~", str, out snapchatUsername) ||
TryExtractSnapchatUsernameFromConvention("sc •", str, out snapchatUsername) ||
TryExtractSnapchatUsernameFromConvention("sc•", str, out snapchatUsername) ||
TryExtractSnapchatUsernameFromConvention("scm:", str, out snapchatUsername) ||
TryExtractSnapchatUsernameFromConvention("scm-", str, out snapchatUsername) ||
TryExtractSnapchatUsernameFromConvention("scm~", str, out snapchatUsername) ||
TryExtractSnapchatUsernameFromConvention("scm:", str, out snapchatUsername) ||
TryExtractSnapchatUsernameFromConvention("scm~", str, out snapchatUsername) ||
TryExtractSnapchatUsernameFromConvention("scm •", str, out snapchatUsername) ||
TryExtractSnapchatUsernameFromConvention("scm•", str, out snapchatUsername) ||
TryExtractSnapchatUsernameFromConvention("snap:", str, out snapchatUsername) ||
TryExtractSnapchatUsernameFromConvention("snap-", str, out snapchatUsername) ||
TryExtractSnapchatUsernameFromConvention("snap~", str, out snapchatUsername) ||
TryExtractSnapchatUsernameFromConvention("snap;", str, out snapchatUsername) ||
TryExtractSnapchatUsernameFromConvention("snap:", str, out snapchatUsername) ||
TryExtractSnapchatUsernameFromConvention("snap~", str, out snapchatUsername) ||
TryExtractSnapchatUsernameFromConvention("snap", str, out snapchatUsername) ||
TryExtractSnapchatUsernameFromConvention("snap •", str, out snapchatUsername) ||
TryExtractSnapchatUsernameFromConvention("snap•", str, out snapchatUsername) ||
TryExtractSnapchatUsernameFromConvention("sc/", str, out snapchatUsername) ||
TryExtractSnapchatUsernameFromConvention("snapchat:", str, out snapchatUsername) ||
TryExtractSnapchatUsernameFromConvention("snapchat-", str, out snapchatUsername) ||
TryExtractSnapchatUsernameFromConvention("snapchat -", str, out snapchatUsername) ||
TryExtractSnapchatUsernameFromConvention("snapchat~", str, out snapchatUsername) ||
TryExtractSnapchatUsernameFromConvention("snapchat;", str, out snapchatUsername) ||
TryExtractSnapchatUsernameFromConvention("snapchat:", str, out snapchatUsername) ||
TryExtractSnapchatUsernameFromConvention("snapchat~", str, out snapchatUsername) ||
TryExtractSnapchatUsernameFromConvention("snapchat •", str, out snapchatUsername) ||
TryExtractSnapchatUsernameFromConvention("snapchat•", str, out snapchatUsername) ||
TryExtractSnapchatUsernameFromConvention(":", str, out snapchatUsername) ||
TryExtractSnapchatUsernameFromConvention("-", str, out snapchatUsername) ||
TryExtractSnapchatUsernameFromConvention("~", str, out snapchatUsername) ||
TryExtractSnapchatUsernameFromConvention(";", str, out snapchatUsername) ||
TryExtractSnapchatUsernameFromConvention("•", str, out snapchatUsername) ||
TryExtractSnapchatUsernameFromConvention("-", str, out snapchatUsername))
{
snapchatUsername = Regex.Replace(snapchatUsername, @"\p{Cs}", ""); // Lets remove any unicode such as emojis.
}
else if (str.Contains("sc "))
{
var sequences = str.Split(" ").SkipWhile(x => x != "sc");
snapchatUsername = sequences.Count() > 0 ? sequences.Skip(1).First() : "";
}
else if (str.StartsWith(" "))
{
snapchatUsername = str.Split(" ").SkipWhile(x => x != "").Skip(1).First();
}
else if (str.StartsWith(""))
{
snapchatUsername = str.Split(" ").SkipWhile(x => !x.StartsWith("")).First().Substring("".Length);
}
else if (str.Split(" ").Any(x => x.EndsWith("")))
{
snapchatUsername = str.Split(" ").SkipWhile(x => !x.EndsWith("")).First();
}
snapchatUsername = Regex.Replace(snapchatUsername, @"\p{Cs}", ""); // Lets remove any unicode such as emojis.
snapchatUsername = snapchatUsername.Replace("•", "");
return !string.IsNullOrEmpty(snapchatUsername) && Utilities.IsValidSnapchatUsername(snapchatUsername);
}
private bool TryExtractSnapchatUsernameFromConvention(string convention, string str, out string snapchatUsername)
{
if (str.Contains(convention + " "))
{
var possibleConventions = str.Split(" ").SkipWhile(x => x != convention);
if (!possibleConventions.Any())
{
var everythingAfterConvention = str.Substring(str.IndexOf(convention) + convention.Length + 1);
if (!everythingAfterConvention.Contains(" "))
{
snapchatUsername = everythingAfterConvention;
}
else
{
snapchatUsername = everythingAfterConvention.Split(" ").First();
}
}
else
{
snapchatUsername = str.Split(" ").SkipWhile(x => x != convention).Skip(1).First();
}
}
else if (str.StartsWith(convention) && !str.Contains(" "))
{
snapchatUsername = str.Substring(convention.Length);
}
else if (str.Contains(convention))
{
if (str.Contains(" ") && str.Split(" ").Last().Contains(convention))
{
snapchatUsername = str.Split(" ").Last().Substring(convention.Length);
}
else if (str.Contains(" ") && str.Split(" ").First().Contains(convention))
{
snapchatUsername = str.Split(" ").First().Substring(convention.Length);
}
else
{
var firstWordWithConvention = str.Split(" ").SkipWhile(x => x != convention).FirstOrDefault();
if (firstWordWithConvention == null)
{
snapchatUsername = "";
}
else
{
snapchatUsername = firstWordWithConvention.Substring(convention.Length);
}
}
}
else
{
snapchatUsername = string.Empty;
}
return !string.IsNullOrEmpty(snapchatUsername);
}
public bool TryExtractAgeFromString(string str, out int age)
{
var allowedAgesForSuccess = new List<int> { 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 };
var twelveYearsOldFilters = new List<string>
{"12•", "//12", "|12|", "12 x", "year 7", "12", "12❤️", "1️⃣2️⃣", "12yo "};
var thirteenYearsOldFilters = new List<string>
{"13•", "//13", "|13|", "13 x", "year 8", "13", "13❤️", "1️⃣3️⃣", "13yo "};
var fourteenYearsOldFilters = new List<string>
{"14•", "//14", "|14|", "14 x", "year 9", "14", "14❤️", "1️⃣4️⃣", "14yo "};
var fifteenYearsOldFilters = new List<string>
{"15•", "//15", "|15|", "15 x", "year 10", "15", "15❤️", "1️⃣5️⃣", "15yo"};
var sixteenYearsOldFilters = new List<string>
{"16•", "//16", "|16|", "16 x", "year 11", "6teen", "16", "16❤️", "16~", "16yo "};
var seventeenYearsOldFilters = new List<string>
{"17•", "//17", "|17|", "17 x", "s•e•v•e•n•t•e•e•n", "seventeen xo", "year 12", "7teen", "17", "17❤️", "17~", "17yo "};
var eighteenYearsOldFilters = new List<string>
{"18•", "//18", "|18|", "18 x", "year 13", "8teen", "18", "18❤️", "18~", "18yo "};
var nineteenYearsOldFilters = new List<string> {"19•", "//19", "|19|", "19 x", "9teen", "19", "19❤️", "19~"};
var twentyYearsOldFilters = new List<string> {"20•", "//20", "|20|", "20 x", "20", "20❤️", "20~"};
var twentyOneYearsOldFilters = new List<string> {"21•", "//21", "|21|", "21 x", "21", "21❤️", "21~"};
var twentyTwoYearsOldFilters = new List<string> {"22•", "//22", "|22|", "22 x", "22", "22❤️", "22~"};
var twentyThreeYearsOldFilters = new List<string> {"23•", "//23", "|23|", "23 x", "23", "23❤️", "23~"};
var twentyFourYearsOldFilters = new List<string> {"24•", "//24", "|24|", "24 x", "24", "24❤️", "24~"};
if (twelveYearsOldFilters.Where(str.Contains).Any())
{
age = 12;
}
else if (thirteenYearsOldFilters.Where(str.ContainsIgnoreCase).Any())
{
age = 13;
}
else if (fourteenYearsOldFilters.Where(str.ContainsIgnoreCase).Any())
{
age = 14;
}
else if (fifteenYearsOldFilters.Where(str.ContainsIgnoreCase).Any())
{
age = 15;
}
else if (sixteenYearsOldFilters.Where(str.ContainsIgnoreCase).Any())
{
age = 16;
}
else if (seventeenYearsOldFilters.Where(str.ContainsIgnoreCase).Any())
{
age = 17;
}
else if (eighteenYearsOldFilters.Where(str.ContainsIgnoreCase).Any())
{
age = 18;
}
else if (nineteenYearsOldFilters.Where(str.ContainsIgnoreCase).Any())
{
age = 19;
}
else if (twentyYearsOldFilters.Where(str.ContainsIgnoreCase).Any())
{
age = 20;
}
else if (twentyOneYearsOldFilters.Where(str.ContainsIgnoreCase).Any())
{
age = 21;
}
else if (twentyTwoYearsOldFilters.Where(str.ContainsIgnoreCase).Any())
{
age = 22;
}
else if (twentyThreeYearsOldFilters.Where(str.ContainsIgnoreCase).Any())
{
age = 23;
}
else if (twentyFourYearsOldFilters.Where(str.ContainsIgnoreCase).Any())
{
age = 24;
}
else
{
age = 0;
}
return allowedAgesForSuccess.Contains(age);
}
public bool StringContainsPromotion(string str)
{
var promotions = new List<string>()
{
"save up to", "drinks from ", "10% off", "for sale"
};
return promotions.Any(x => str.ContainsIgnoreCase(x));
}
public bool StringContainsMakeUpPhrase(string str)
{
var makeupPhrases = new List<string>()
{
"makeupby", "hairby", "nailsby", ".nails", "nails.", "aesthetics", "lashesby", "lashes_by"
};
return makeupPhrases.Any(x => str.ContainsIgnoreCase(x));
}
public bool StringContainsDeletedProfilePhrase(string str)
{
var deletedPhrases = new List<string>()
{
"notactive", "notusing", "notbeingused", "deactivated", "deleted", "delete", "notused", "oldaccount"
};
return deletedPhrases.Any(x => str.ContainsIgnoreCase(x));
}
public bool StringContainsGenericBadPhrase(string str)
{
var badPhrases = new List<string>()
{
"ignore_delly_scraper", "#noscrape"
};
return badPhrases.Any(x => str.ContainsIgnoreCase(x));
}
/// <summary>
/// Primary method to check all sub-methods
/// Checks GenericBadPhrase, DeletedProfilePhrase and MakeUpPhrase
/// </summary>
/// <returns></returns>
public bool StringContainsAnythingBad(string str)
{
return StringContainsGenericBadPhrase(str) ||
StringContainsDeletedProfilePhrase(str) ||
StringContainsMakeUpPhrase(str);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T13:38:54.670",
"Id": "490404",
"Score": "1",
"body": "Nice follow up question, but please provide the code for the abstract class `AbstractSocialEventHandler`. You are getting into more areas of SOLID in this question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T20:14:47.843",
"Id": "490439",
"Score": "0",
"body": "I know you want to improve your coding abilities and that is great, but right now no one is going to answer this question because it is off-topic. Without the definition for the base class of `DellyEventHandler` we don't really have enough information to provide a good review. Please read the [asking guidelines in our help center](https://codereview.stackexchange.com/help/asking), they are the rules we go by here. Read at least the first 4, but it might help to read all of them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T10:59:35.163",
"Id": "490488",
"Score": "0",
"body": "Will upload a github repo link shortly, thanks."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T19:25:40.433",
"Id": "250014",
"Score": "2",
"Tags": [
"c#",
"web-scraping",
"selenium"
],
"Title": "C# Scraper - EventHandler"
}
|
250014
|
<p>I'm currently working on a project which should create VDM files. Here's a basic example:</p>
<pre><code>demoactions
{
"1"
{
factory "SkipAhead"
name "skip"
starttick "1"
skiptotick "3623"
}
"2"
{
factory "PlayCommands"
name "startrec"
starttick "4123"
commands "startrecording"
}
"3"
{
factory "PlayCommands"
name "stoprec"
starttick "4753"
commands "stoprecording"
}
"4"
{
factory "PlayCommands"
name "nextdem"
starttick "4125"
commands "playdemo demoName.dem"
}
}
</code></pre>
<p>The main gist of this is the following:</p>
<p>"1":
The first thing we do is skip to a tick</p>
<p>"2": A few ticks later we issue the command "startrecording".
"3": After x amount of time we issue the command "stoprecording"</p>
<p>We repeat "2" and "3" with different ticks how many times we need.
At the end we optionally issue the command "playdemo".</p>
<p>To automatically generate such files I wrote the following class:</p>
<pre><code>class EventVDM {
constructor() {
this.link;
this.fileName;
this.events = [];
this.recordingMultipliers= []
}
set setLink(fileName) {
this.link = fileName;
}
addEvent(tick,recordingMultiplier = 0) {
this.events.push(tick)
this.recordingMultipliers.push(recordingMultiplier)
}
toString() {
this.events.sort((a, b) => a - b) //Make sure the ticks are in order
let vdmString = "demoactions\n {\n"
let indexAdjust = 0; //If we have two ticks that are too close to each other this increments e.g (100,110)
let count = 2; //The number we write in quotation marks
let skipBuffer = 500; //skips 500 ticks before the record statement is issued
let stopRecordBuffer = parseInt($("#recordDuration")[0].value) * 66 //The user can specify a custom value default is 5(seconds) *66
let startRecordBuffer = parseInt($("#prerecordDuration")[0].value) *66//The user can specify a custom value default is 5(seconds) *66
for (let tickIndexString in this.events) {
let tickIndex = parseInt(tickIndexString)
if (indexAdjust + tickIndex < this.events.length) { //Make sure we don't try to access an element out of range
let tick = this.events[tickIndex + indexAdjust]
if (tickIndex == 0) { //If it's the very first index skip to first tick ("1")
vdmString += this.skipToTickBuilder(count - 1, 1, tick, skipBuffer)
}
vdmString += this.buildPart(count, "PlayCommands", "startrec", tick - startRecordBuffer, `commands "startrecording"`) //Initiate first record
count++;
if (this.events[tickIndex +indexAdjust +1] > tick + stopRecordBuffer+(this.recordingMultipliers[tickIndex]*66)) { //If we can safely skip to the next tick
vdmString += this.buildPart(count, "PlayCommands", "stoprec", tick + stopRecordBuffer + (this.recordingMultipliers[tickIndex] * 66), `commands "stoprecording"`)
count++;
vdmString += this.skipToTickBuilder(count, tick + stopRecordBuffer + (this.recordingMultipliers[tickIndex] * 66), this.events[tickIndex +indexAdjust+ 1], skipBuffer)
count++;
}
else { //Otherwise
indexAdjust++;
vdmString += this.buildPart(count, "PlayCommands", "stoprec", tick + stopRecordBuffer + (this.recordingMultipliers[tickIndex] * 66), `commands "stoprecording"`)
count++;
}
}
}
if (this.link != undefined) {
vdmString += this.buildPart(count, "PlayCommands", "nextdem", this.events[this.events.length - 1] + stopRecordBuffer + 300, `commands "playdemo ${this.link}"`)
}
vdmString += "}"
return vdmString;
}
skipToTickBuilder(count, starttick, tick, skipBuffer) {
if (tick - skipBuffer > 1) {
return this.buildPart(count, "SkipAhead", "skip", starttick, `skiptotick ${tick - skipBuffer}`)
}
else {//This generates initial skip ahead
return this.buildPart(count, "SkipAhead", "skip", starttick, `skiptotick ${tick}`)
}
}
buildPart(count, factory, name, starttick, arg) {
let string = `\t"${count}"\n`
string += "\t{\n"
string += `\t\t factory "${factory}"\n`
string += `\t\t name "${name}"\n`
string += `\t\t starttick "${starttick}"\n`
string += `\t\t ${arg}\n`
string += "\t}\n"
return string;
}
}
</code></pre>
<p>Basically you can use addEvent to add ticks to a list and it the toString() method to create the "file". To create the file we have above we'd the following:</p>
<pre><code>let vdm = new EventVDM()
vdm.setfileName = "demoName.dem"
vdm.addEvent(4453) //300 tick difference because of the startRecordBuffer
vdm.toString()
</code></pre>
<p>I'm very much new to all of this so I'm wondering if what I've done is readable and understandable and also if there are any better ways to do things like this.</p>
<p>Many thanks in advance!</p>
|
[] |
[
{
"body": "<p><strong>Always <a href=\"https://softwareengineering.stackexchange.com/q/278652\">use <code>const</code></a></strong> when possible if you're going to write in ES6+; only use <code>let</code> when you need to reassign a variable</p>\n<p><strong>Consistent spacing</strong> You have lines like: <code>[0].value) *66</code> <code>this.events[tickIndex +indexAdjust +1]</code> <code>stopRecordBuffer+(this.recordingMultipliers</code> Code is easiest to read when operators have a space between the operator and its operands. Consider using an IDE which properly formats code automatically (like VSCode), or <a href=\"https://eslint.org/docs/rules/space-infix-ops\" rel=\"nofollow noreferrer\">a linter</a> that can detect such things and prompt you to fix it automatically.</p>\n<p><strong>setLink?</strong> You have a <code>setLink</code> setter. For it to be used, it'd look like: <code>vdm.setLink = 'foobar'</code>. That looks somewhat odd. How about making <code>setLink</code> a normal method instead, so you can do <code>vdm.setLink('foobar')</code>?</p>\n<p><strong>String building</strong> You might be able to improve the <code>buildPart</code> method. To start with, template literals can span multiple lines, which can be nicer than using lots of <code>string +=</code> and <code>\\n</code> concatenation, eg:</p>\n<pre><code>const buildPart = (count, factory, name, starttick, arg) =>\n`\\t"${count}"\n\\t{\n\\t\\t factory "${factory}"\n\\t\\t name "${name}"\n// etc\n</code></pre>\n<p>You could also use literal tab characters instead of <code>\\t</code> to improve readability (but Stack Exchange's renderer doesn't work well with tabs).</p>\n<p>Also, the VDM format looks very close to JSON. It may be possible to construct an object of objects instead:</p>\n<pre><code>{\n 1: {\n factory: "SkipAhead",\n name: "skip",\n starttick: "1",\n skiptotick: "3623"\n },\n // ...\n</code></pre>\n<p>When you need to turn it into a string, use <code>JSON.stringify</code> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify\" rel=\"nofollow noreferrer\">with a space argument</a>, then use a simple regular expression to get the rest to line up with the required format as needed.</p>\n<p><strong>Break early to avoid indentation hell</strong> You have:</p>\n<pre><code>for (let tickIndexString in this.events) {\n let tickIndex = parseInt(tickIndexString)\n if (indexAdjust + tickIndex < this.events.length) { //Make sure we don't try to access an element out of range\n // a large block\n }\n} // end of for loop\n</code></pre>\n<p>IMO, code is most readable when you try to cut down on the amount of indentation and <code>}</code>s in a row at the end of a section of logic. Consider instead something like:</p>\n<pre><code>for (let tickIndexString in this.events) {\n const tickIndex = parseInt(tickIndexString);\n const tick = this.events[tickIndex + indexAdjust];\n if (!tick) {\n break;\n }\n // more code here\n}\n</code></pre>\n<p><strong>Line length</strong> You have (original indentation included):</p>\n<pre><code> vdmString += this.skipToTickBuilder(count, tick + stopRecordBuffer + (this.recordingMultipliers[tickIndex] * 66), this.events[tickIndex + indexAdjust + 1], skipBuffer)\n</code></pre>\n<p>Even on my reasonably large Full HD monitor, this line goes off the screen. If someone has to scroll horizontally to see all the code, that's a bad sign. Consider requiring a <a href=\"https://eslint.org/docs/rules/max-len\" rel=\"nofollow noreferrer\">maximum line length</a>. It doesn't have to be the (IMO) incredibly small 80 characters, but 187 is probably too much. Choose a number that can at least fit comfortably on the monitors of those who may need to read the code.</p>\n<p>Scrolling isn't the only issue - there's quite a lot happening in that line. Don't be afraid to break something up into multiple lines if it makes it easier to understand, eg:</p>\n<pre><code>vdmString += this.skipToTickBuilder(\n count,\n tick + stopRecordBuffer + (this.recordingMultipliers[tickIndex] * 66),\n this.events[tickIndex + indexAdjust + 1],\n skipBuffer\n);\n</code></pre>\n<p>or put the arguments into variables first, to make the code more self-documenting:</p>\n<pre><code>const startTick = tick + stopRecordBuffer + (this.recordingMultipliers[tickIndex] * 66);\nconst nextTick = this.events[tickIndex + indexAdjust + 1];\nvdmString += this.skipToTickBuilder(count, startTick, nextTick, skipBuffer);\n</code></pre>\n<p><strong>Semicolons</strong> Sometimes you're using semicolons when proper at the end of statements. Sometimes you aren't. If you forget a semicolon, you may eventually run into a bug due to <a href=\"https://stackoverflow.com/questions/2846283/what-are-the-rules-for-javascripts-automatic-semicolon-insertion-asi\">automatic semicolon insertion</a>. Code style should be consistent; either use semicolons or don't. Unless you're an expert on ASI and can avoid those sorts of bugs on sight, I'd recommend using semicolons. Enforce your desired style with <a href=\"https://eslint.org/docs/rules/semi\" rel=\"nofollow noreferrer\">with a linting rule</a>.</p>\n<p><strong>Avoid repeating lines</strong> You repeat the same <em>long</em> line twice, the one starting with <code>vdmString += this.buildPart</code>:</p>\n<pre><code>if (this.events[tickIndex + indexAdjust + 1] > tick + stopRecordBuffer + (this.recordingMultipliers[tickIndex] * 66)) { //If we can safely skip to the next tick\n vdmString += this.buildPart(count, "PlayCommands", "stoprec", tick + stopRecordBuffer + (this.recordingMultipliers[tickIndex] * 66), `commands "stoprecording"`)\n count++;\n vdmString += this.skipToTickBuilder(count, tick + stopRecordBuffer + (this.recordingMultipliers[tickIndex] * 66), this.events[tickIndex + indexAdjust + 1], skipBuffer)\n count++;\n}\nelse { //Otherwise \n indexAdjust++;\n vdmString += this.buildPart(count, "PlayCommands", "stoprec", tick + stopRecordBuffer + (this.recordingMultipliers[tickIndex] * 66), `commands "stoprecording"`)\n count++;\n}\n</code></pre>\n<p>Whenever you see a not-insignificant amount of code being repeated, it's a good time to take a step back and consider if it can be made more <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY</a>, to make the code more concise and structured so that if a change needs to occur in the future, you can change only <em>one</em> section, rather than two or more at the same time. The above can be turned into:</p>\n<pre><code>const startTick = tick + stopRecordBuffer + (this.recordingMultipliers[tickIndex] * 66);\nvdmString += this.buildPart(count, "PlayCommands", "stoprec", startTick, `commands "stoprecording"`)\nconst nextTick = this.events[tickIndex + indexAdjust + 1];\nif (nextTick > startTick) { //If we can safely skip to the next tick\n count++;\n vdmString += this.skipToTickBuilder(count, startTick, nextTick, skipBuffer);\n} else {\n indexAdjust++;\n}\ncount++;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T02:18:51.170",
"Id": "490372",
"Score": "0",
"body": "Code formatting: an empty line above and below all conditional statement blocks; `if`, `while`, `for`, et cetera. From years of reading code, I love this."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T01:29:38.733",
"Id": "250020",
"ParentId": "250016",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "250020",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T20:24:20.793",
"Id": "250016",
"Score": "4",
"Tags": [
"javascript"
],
"Title": "Class to automatically create Valve VDM files by timestamps"
}
|
250016
|
<p>I'm writing an AI in C++ for OpenTTD, and the first component is a path finder. If you'd like to run it yourself, it's on Github here: <a href="https://github.com/marlonsmith10/empire_ai" rel="noreferrer">https://github.com/marlonsmith10/empire_ai</a>. Currently, it will pick two random towns and build a road between them.</p>
<p>The pathfinder class Path is used by calling find() repeatedly until a path is found. It provides an iterator that can be used to get the index of each tile in the path, once it has been found. The class works correctly to find a 2D list of tiles that are able to have roads built on them. It does not take slope into account, so sometimes roads will not connect after they're built, but I'd prefer to leave that out of the review for now (to be implemented in the future).</p>
<p>My goal is to improve my C++ skills, so any C++ comments or advanced techniques would be appreciated. Comments on the algorithm or general code style are welcome as well.</p>
<p>path.hh</p>
<pre><code>#ifndef PATH_HH
#define PATH_HH
#include "stdafx.h"
#include "command_func.h"
#include <vector>
namespace EmpireAI
{
class Path
{
public:
Path(TileIndex start, TileIndex end);
~Path();
// Find a partial path from start to end, returning true if the full path has been found
bool find();
private:
struct Node
{
Node(TileIndex in_tile_index, int32 in_h)
: tile_index(in_tile_index), h(in_h)
{}
bool update_costs(Node* adjacent_node);
const TileIndex tile_index = 0;
Node* previous_node = NULL;
bool open = true;
int32 g = 0;
const int32 h = 0;
int32 f = -1;
};
void parse_adjacent_tile(Node* current_node, int8 x, int8 y);
// Return the corresponding node or create a new one if none is found
Node* get_node(TileIndex tile_index);
// Get the open node with the cheapest f cost
Node* cheapest_open_node();
// Check this many nodes per call of find()
static const uint8 NODE_COUNT_PER_CALL = 20;
void open_node(Node* node);
void close_node(Node* node);
bool m_path_found = false;
Node* m_start_node;
Node* m_current_node;
TileIndex m_end_tile_index;
std::vector<Node*> m_open_nodes;
std::vector<Node*> m_closed_nodes;
public:
class Iterator
{
public:
Iterator(const Path::Node* node)
: m_iterator_node(node)
{}
bool operator==(const Iterator& iterator) const
{
return m_iterator_node == iterator.m_iterator_node;
}
const Iterator& operator=(const Path::Node* node)
{
m_iterator_node = node;
return *this;
}
bool operator!=(const Iterator& iterator) const
{
return m_iterator_node != iterator.m_iterator_node;
}
const Iterator& operator++()
{
m_iterator_node = m_iterator_node->previous_node;
return *this;
}
Iterator operator++(int)
{
Iterator iterator = *this;
m_iterator_node = m_iterator_node->previous_node;
return iterator;
}
TileIndex operator*() const
{
if(m_iterator_node == nullptr)
{
return 0;
}
return m_iterator_node->tile_index;
}
private:
const Path::Node* m_iterator_node;
};
Iterator begin()
{
return Iterator(m_current_node);
}
Iterator end()
{
return Iterator(m_start_node);
}
};
}
#endif // PATH_HH
</code></pre>
<p>path.cc</p>
<pre><code>#include "path.hh"
#include "script_map.hpp"
#include "script_road.hpp"
#include "script_tile.hpp"
#include <algorithm>
#include <iostream>
using namespace EmpireAI;
Path::Path(TileIndex start, TileIndex end)
{
// Save start node
m_current_node = m_start_node = get_node(start);
m_current_node->update_costs(m_current_node);
m_end_tile_index = end;
}
bool Path::find()
{
if(m_path_found)
{
return true;
}
// While not at end of path
for(uint8 node_count = 0; node_count < NODE_COUNT_PER_CALL; node_count++)
{
// Find the cheapest open node
m_current_node = cheapest_open_node();
// Mark the current node as closed
close_node(m_current_node);
// If we've reached the destination, return true
if(m_current_node->tile_index == m_end_tile_index)
{
m_path_found = true;
break;
}
// Calculate the f, h, g, values of the 4 surrounding nodes
parse_adjacent_tile(m_current_node, 1, 0);
parse_adjacent_tile(m_current_node, -1, 0);
parse_adjacent_tile(m_current_node, 0, 1);
parse_adjacent_tile(m_current_node, 0, -1);
}
return m_path_found;
}
void Path::parse_adjacent_tile(Node* current_node, int8 x, int8 y)
{
TileIndex adjacent_tile_index = current_node->tile_index + ScriptMap::GetTileIndex(x, y);
// Create a node for this tile only if it is buildable
if(ScriptTile::IsBuildable(adjacent_tile_index) || ScriptRoad::IsRoadTile(adjacent_tile_index))
{
Node* adjacent_node = get_node(adjacent_tile_index);
if(adjacent_node->update_costs(current_node))
{
open_node(adjacent_node);
}
}
}
Path::Node* Path::get_node(TileIndex tile_index)
{
// Return the node if it already exists
for(Node* node : m_open_nodes)
{
if(node->tile_index == tile_index)
{
return node;
}
}
// Return the node if it already exists
for(Node* node : m_closed_nodes)
{
if(node->tile_index == tile_index)
{
return node;
}
}
Node* node = new Node(tile_index, ScriptMap::DistanceManhattan(tile_index, m_end_tile_index));
m_open_nodes.push_back(node);
return node;
}
Path::Node* Path::cheapest_open_node()
{
// Get the first open node to start
Node* cheapest_open_node = m_open_nodes.front();
// Compare the first open node to all other open nodes to find the cheapest
for(Node* node : m_open_nodes)
{
if(node->f < cheapest_open_node->f)
{
cheapest_open_node = node;
}
// Break ties by choosing closest to destination
if(node->f == cheapest_open_node->f && node->h < cheapest_open_node->h)
{
cheapest_open_node = node;
}
}
return cheapest_open_node;
}
void Path::open_node(Node* node)
{
// Find the node in the list of closed nodes
auto it = std::find(m_closed_nodes.begin(), m_closed_nodes.end(), node);
if(it != m_closed_nodes.end())
{
node->open = true;
m_open_nodes.push_back(node);
m_closed_nodes.erase(it);
}
}
void Path::close_node(Node* node)
{
// Find the node in the list of open nodes
auto it = std::find(m_open_nodes.begin(), m_open_nodes.end(), node);
if(it != m_open_nodes.end())
{
node->open = false;
m_closed_nodes.push_back(node);
m_open_nodes.erase(it);
}
}
bool Path::Node::update_costs(Node* adjacent_node)
{
int32 new_g = adjacent_node->g + 1;
int32 new_f = new_g + h;
if(new_f < f || f == -1)
{
g = new_g;
f = new_f;
previous_node = adjacent_node;
return true;
}
return false;
}
Path::~Path()
{
for(Node* node : m_open_nodes)
{
delete node;
}
for(Node* node : m_closed_nodes)
{
delete node;
}
}
</code></pre>
|
[] |
[
{
"body": "<p><strong>Node-count limit</strong>:</p>\n<pre><code>for(uint8 node_count = 0; node_count < NODE_COUNT_PER_CALL; node_count++)\n</code></pre>\n<p>A <code>uint8</code> may be too small (especially if we want to find a complete path in one call).</p>\n<p>It would be nice to specify a maximum number of nodes to search when calling the function (maybe a function argument that defaults to <code>NODE_COUNT_PER_CALL</code>).</p>\n<p>A time-based limit might be more useful in some situations (e.g. providing a consistent framerate on a variety of hardware).</p>\n<hr />\n<p><strong>Don't call <code>new</code> directly</strong>:</p>\n<p>We should use a <code>std::unique_ptr</code> instead of doing manual memory management of <code>Node</code>s.</p>\n<p>(However, see below...)</p>\n<hr />\n<p><strong>Handle edge cases</strong>:</p>\n<p><code>TileIndex adjacent_tile_index = current_node->tile_index + ScriptMap::GetTileIndex(x, y);</code></p>\n<p>Presumably there are map edges, so at some point the <code>-1</code> and <code>+1</code> added to the x and y are not valid. Does this (and the rest of the algorithm) work correctly in those cases?</p>\n<hr />\n<p><strong>Wrong data structures</strong>!</p>\n<p>This A* implementation stores <code>Node</code>s in a flat <code>vector</code>, which means we have to do linear searches to check the search frontier and visited nodes, and to find the cheapest node (see <code>get_node()</code>, <code>cheapest_open_node()</code> etc.). This is going to be horribly slow for larger maps.</p>\n<p>We should use a <code>std::unordered_map</code> for the visited nodes (with the <code>tile_index</code> as the key), and a <code>std::priority_queue</code> to store the search frontier, so that we can quickly access the cheapest node.</p>\n<p>(It's usually easier to store "open" and "closed" nodes in a single map.)</p>\n<p>(Note that with these changes it will probably faster to store the previous <code>tile_index</code>, instead of doing extra memory allocation and storing a pointer).</p>\n<hr />\n<p><strong>Inaccessible nodes</strong>?</p>\n<p>What happens when the destination is inaccessible? It looks like we'll call <code>Node* cheapest_open_node = m_open_nodes.front();</code> on an empty <code>m_open_nodes</code> and cause undefined behaviour (e.g. a crash).</p>\n<p>Note that we really have three return states: "still searching", "search complete - path found", "search complete - path not found". Perhaps we need to return an <code>enum</code> from <code>find()</code> instead of a bool.</p>\n<p>Do we need to worry about the start node being inaccessible?</p>\n<p>What do we really need in terms of accessibility? Is it correct to find a path up to a destination that isn't buildable or a road, even if we can't move onto the final tile?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T20:08:35.733",
"Id": "490438",
"Score": "0",
"body": "Thanks for such a detailed reply, it's very much appreciated!\n\nNode-count limit: I like the idea of specifying the count when calling the function, and I'll look into time-based limits.\n\nHandle edge cases: I'll double check this and fix if necessary. I believe ScriptTile::IsBuildable will fail on edges, so it may be ok.\n\nInaccessible nodes: Your points make sense here, returning enum I think is the right approach. As far as inaccessibility, this path finder is currently just for roads (something I should specify more clearly), so if the route can't be found the AI should abandon it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T20:16:48.400",
"Id": "490441",
"Score": "0",
"body": "Don't call new directly and Wrong data structures!: I especially appreciate your comments here. I haven't used std::unordered_map or std::priority_queue before, so I'm going to spend some time and see if I can implement it this way instead. Will post a follow-up question with the revised code. Thanks again!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T12:34:31.400",
"Id": "250035",
"ParentId": "250017",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "250035",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T20:34:41.853",
"Id": "250017",
"Score": "7",
"Tags": [
"c++",
"algorithm"
],
"Title": "AI for OpenTTD - A* Path Finder"
}
|
250017
|
<p>I am trying to see if anyone can help me in making this Excel VBA code a little faster in rendering the data from the weather site I am using. Maybe instead of getting all 14 days it includes in the site, could I get help in getting just 10 days? Any help is much appreciated. Thanks!</p>
<pre><code>Sub MiamiWeather()
Dim HTTP As Object, HTML As Object, i As Integer, j As Integer
Set HTML = CreateObject("HTMLFILE")
Set HTTP = CreateObject("MSXML2.XMLHTTP")
myURL = "https://weather.com/weather/tenday/l/3881cd527264bc7c99b6b541473c0085e75aa026b6bd99658c56ad9bb55bd96e"
HTTP.Open "GET", myURL, False
HTTP.send
HTML.body.innerHTML = HTTP.responseText
Set objCollection = HTML.getElementsByTagName("p")
i = 0
Do While i < objCollection.Length And j < 20
If objCollection(i).getAttribute("data-testid") = "wxPhrase" Then
j = j + 1
Range("A" & j) = objCollection(i).PreviousSibling.PreviousSibling.FirstChild.innerText
Range("B" & j) = objCollection(i).PreviousSibling.FirstChild.innerText
End If
i = i + 1
Loop
Set HTML = Nothing
Set HTTP = Nothing
End Sub
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T00:26:51.503",
"Id": "490366",
"Score": "0",
"body": "If you want to load fewer days just add a condition on the loop:\n\nDo While i < objCollection.Length And j < 10"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T16:27:58.133",
"Id": "490522",
"Score": "1",
"body": "Using some simple timing code (e.g. `Debug.Print \"Section:\"; (Timer - stTime)*1000;\"ms\"`) I ran and profiled your code. About 50% of the running time is spent in that While loop, 30% is spent loading the HTML document from the HTTP response, the other 20% spent in the Get request. Consequently I'd say the best optimisations come from the while loop, and you may want to profile that in more detail. It's true, stopping after j = 10 rather than 14 saves ~ 25% of the loop time, however looping over all `<p>` elements is wasteful and you may want to try `getElementsByClassName` to narrow the search"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T23:56:14.300",
"Id": "490765",
"Score": "0",
"body": "Thanks for timing the code, Greedo. I was working with a code that had getElementsByClassName, but it stopped giving me the first date in the forecast of today's forecast of the summary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-04T00:21:31.150",
"Id": "490767",
"Score": "0",
"body": "Could I easily change the code to getElementsByClassName?"
}
] |
[
{
"body": "<p>The real question here is how to get only the <code>p</code> tags with a <code>data-testid</code> with the value of <code>wxPhrase</code>. This can be done using <code>querySelectorAll()</code>.</p>\n<blockquote>\n<p>Document.querySelectorAll("p[data-testid='wxPhrase']")</p>\n</blockquote>\n<p>See <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll\" rel=\"nofollow noreferrer\">Document.querySelectorAll()</a>.</p>\n<p>You will need to add a reference to the Microsoft HTML Object Library and declare you document variable as <code>HTMLDocument</code>.</p>\n<blockquote>\n<p>Dim Document As HTMLDocument</p>\n</blockquote>\n<p><img src=\"https://i.stack.imgur.com/6IJSc.png\" alt=\"Reference Window\" /></p>\n<p>Loading the values into an Array will offer you the best performance. It will not make a noticeable difference if you return 10 days or all the days of the month.</p>\n<h2>Refactored Code</h2>\n<pre><code>Sub MiamiWeather()\n Dim Data As Variant\n Data = MiamiWeatherData\n \n Range("A1:B1").Value = Array("Date", "Tempature")\n Range("A2").Resize(UBound(Data), 2).Value = Data\n \nEnd Sub\n\nFunction MiamiWeatherData()\n Const URL = "https://weather.com/weather/tenday/l/3881cd527264bc7c99b6b541473c0085e75aa026b6bd99658c56ad9bb55bd96e"\n Dim responseText As String\n With CreateObject("MSXML2.XMLHTTP")\n .Open "GET", URL, False\n .send\n responseText = .responseText\n End With\n \n Dim Document As HTMLDocument\n Set Document = CreateObject("HTMLFILE")\n Document.body.innerHTML = responseText\n\n Dim Children As IHTMLDOMChildrenCollection\n Set Children = Document.querySelectorAll("p[data-testid='wxPhrase']")\n Dim Results As Variant\n ReDim Results(1 To Children.Length, 1 To 2)\n Dim r As Long\n \n For r = 0 To Children.Length - 1\n Results(r + 1, 1) = Children(r).PreviousSibling.PreviousSibling.FirstChild.innerText\n Results(r + 1, 2) = Children(r).PreviousSibling.FirstChild.innerText\n Next\n \n MiamiWeatherData = Results\nEnd Function\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T20:46:50.270",
"Id": "503784",
"Score": "0",
"body": "I think you forgot to swop out your late-bound htmlfile for early bound New MSHTML.HTMLDocument"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T21:48:06.707",
"Id": "503789",
"Score": "0",
"body": "@QHarr I didn't bother adding a reference to the to `Microsoft XML, v?.0`. I'm referencing `Microsoft HTML Object Library` so that I will have intellisense for the HTML elements."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T22:37:10.867",
"Id": "503794",
"Score": "0",
"body": "I mean I think this _Set Document = CreateObject(\"HTMLFILE\")_ should be _Set Document = New MSHTML.HTMLDocument_ to stick with early binding. `"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-08T20:05:53.620",
"Id": "250378",
"ParentId": "250018",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-29T23:23:48.553",
"Id": "250018",
"Score": "2",
"Tags": [
"vba",
"excel",
"web-scraping"
],
"Title": "Excel VBA code that displays a 14 day weather forecast"
}
|
250018
|
<p>I have this Javascript which call the web api to see the available folder and then the available files. Any comment or code review on my code?</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> var divFolder = document.getElementById("rootFolder");
var divFiles = document.getElementById("files");
function createFolderElement(data) {
var li = document.createElement("div");
li.setAttribute('data-id', data.filePathId);
li.setAttribute('class', "folder");
divFolder.appendChild(li);
li.innerHTML = data.folderName
}
function createFileElement(data) {
debugger
var li = document.createElement("div");
li.setAttribute('data-id', data.id);
li.setAttribute('class', "file");
divFiles.appendChild(li);
li.innerHTML = data.fileName
}
async function fetchFolder(parentId) {
document.getElementById('spinner').style.display = 'block'
divFolder.innerHTML = ''
const response = await fetch(`https://localhost:44371/api/file/folder/${parentId}`);
if (!response.ok) {
const message = `An error has occured: ${response.status}`;
$("div.message").text(message);
$("div.message").addClass("message alert alert-warning");
//throw new Error(message);
}
const files = await response.json();
if (files.length > 0) {
files.forEach((data) => {
createFolderElement(data)
})
createFolderEventListener();
document.getElementById('spinner').style.display = 'none'
}
}
async function fetchFiles(filePathId) {
document.getElementById('spinner').style.display = 'block'
divFolder.innerHTML = ''
const response = await fetch(`https://localhost:44371/api/file/files/${filePathId}`);
if (!response.ok) {
const message = `An error has occured: ${response.status}`;
$("div.message").text(message);
$("div.message").addClass("message alert alert-warning");
//throw new Error(message);
}
const folders = await response.json();
debugger
if (folders.length > 0) {
folders.forEach((data) => {
createFileElement(data)
})
createFileEventListener();
}
document.getElementById('spinner').style.display = 'none'
}
function createFolderEventListener() {
const myfolder = document.getElementsByClassName("folder");
[...myfolder].forEach(function (element) {
element.addEventListener("click", function () {
fetchFolder(element.dataset.id);
fetchFiles(element.dataset.id);
});
});
};
function createFileEventListener() {
const myfolder = document.getElementsByClassName("file");
[...myfolder].forEach(function (element) {
element.addEventListener("click", function () {
downloadPdf(element.dataset.id, element.textContent)
});
});
};
$(function () {
document.getElementById('spinner').style.display = 'none'
fetchFolder(1);
})</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code> div.folder {
border: 1px solid black;
margin: 2px;
cursor: pointer
}
div.file {
border: 1px solid black;
margin: 2px;
cursor: pointer
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="message"></div>
<img src="~/img/loading.gif" id="spinner" />
<div id="rootFolder"></div>
<div id="files"></div></code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T01:09:13.243",
"Id": "490369",
"Score": "1",
"body": "Can you give a bit more details and background information on what all's going on so we have some more context to work with? See [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask) - thanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T02:17:11.260",
"Id": "490371",
"Score": "0",
"body": "@CertainPerformance, sorry, what background information should I include?"
}
] |
[
{
"body": "<p><strong>Prefer modern syntax</strong> You're using a few ES2015+ features already, including <code>async</code>/<code>await</code>. If you're going to write a script containing modern syntax (<em>which you should</em> - it can make code much easier to read and write), best to use it <em>everywhere</em>. In particular:</p>\n<ul>\n<li><p>Use <code>const</code> (or <code>let</code> when you need to reassign) instead of <code>var</code>. <code>var</code> has too many problems to be worth using nowadays, such as an unintuitive function scope (instead of block scope), hoisting, and implicitly creating properties on the global object when on the top level. (Use the <a href=\"https://eslint.org/docs/rules/no-var\" rel=\"nofollow noreferrer\"><code>no-var</code></a> linting rule.)</p>\n</li>\n<li><p>In ES2015+, iterators are available. Utilizing these can make code significantly more concise. For example:</p>\n<pre><code>const myfolder = document.getElementsByClassName("folder");\n[...myfolder].forEach(function(element) {\n</code></pre>\n<p>can be</p>\n<pre><code>for (const element of document.querySelectorAll('.folder')) {\n</code></pre>\n</li>\n</ul>\n<p><strong>jQuery or not?</strong> You're using a bit of jQuery, and a lot of vanilla JS DOM manipulation. This is odd, stylistically. One would usually expect, if jQuery is used, for it to be used <em>everywhere</em> that it can be, at least regarding the DOM. But jQuery doesn't really provide anything that can't be done just as easily in vanilla JS, so you could remove jQuery as a dependency entirely too, if you wished. (That's what I'd choose, but it's up to you.)</p>\n<p><strong>Attributes</strong> 2 things:</p>\n<ul>\n<li><p>When you want to assign to a <code>data-</code> attribute, consider using <code>dataset</code> instead of the more verbose <code>setAttribute</code>:</p>\n<pre><code>li.setAttribute('data-id', data.filePathId);\n</code></pre>\n<p>can be</p>\n<pre><code>li.dataset.id = data.filePathId;\n</code></pre>\n</li>\n<li><p>Classes can be also be set with dot notation, with <code>className</code>:</p>\n<pre><code>li.setAttribute('class', "folder");\n</code></pre>\n<p>can be</p>\n<pre><code>li.className = 'folder';\n</code></pre>\n</li>\n</ul>\n<p><strong>Avoid direct insertion of HTML markup</strong> You have:</p>\n<pre><code>$("div.message").text(message);\n</code></pre>\n<p>That's a good way to do things - assign <em>text</em> to the text content of an element. But elsewhere, you have</p>\n<pre><code>li.innerHTML = data.folderName\n</code></pre>\n<p>That can result in arbitrary code execution. It can also result in formatting problems relating to HTML entities. It sounds very likely that you're expecting <code>folderName</code> to only contain a plain non-HTML string, in which case you should set <em>only the text</em> of the <code><li></code>:</p>\n<pre><code>li.textContent = data.folderName;\n</code></pre>\n<p>Even though the folder name from the API response is almost certainly trustworthy, using <code>textContent</code> instead of <code>innerHTML</code> is a good habit to get into.</p>\n<p><strong>Semicolons</strong> Sometimes you're using semicolons when they're needed, and sometimes you aren't. To be stylistically consistent, best to choose one style - either use them wherever appropriate, or don't use them at all. Note that if you don't use them at all, unless you're an expert, you may well eventually run into problems due to <a href=\"https://stackoverflow.com/questions/2846283/what-are-the-rules-for-javascripts-automatic-semicolon-insertion-asi\">Automatic Semicolon Insertion</a>. (I'd recommend using semicolons.) To enforce a particular style on your code, use <a href=\"https://eslint.org/docs/rules/semi\" rel=\"nofollow noreferrer\">a linter</a>.</p>\n<p><strong>fetchFolder and fetchFiles errors</strong> If either the <code>fetchFolder</code> or <code>fetchFiles</code> request fails, there are 2 problems:</p>\n<ul>\n<li>You don't return or throw if the response is not OK. As a result, the <code>await response.json();</code> will throw. The control flow is odd.</li>\n<li>You show the spinner at the beginning of the request, but if there's an error, the code will never get to the end of the function where the spinner is hidden again.</li>\n</ul>\n<p>The two functions also do very similar things - they show the spinner, do a fetch, and on error, show an error element to the user. Make things more DRY by creating a wrapper function around them.</p>\n<p>Or, you could also consider using <code>Promise.all</code> - wait for <em>both</em> requests to complete before updating the UI, to make things look more natural to the user.</p>\n<pre><code>const fetchPath = (path) => {\n const response = await fetch(`https://localhost:44371/api/${path}`);\n if (!response.ok) {\n throw new Error(response.status);\n }\n return response.json();\n};\nconst fetchFolderAndFiles = (id) => {\n const spinner = document.getElementById('spinner');\n spinner.style.display = 'block';\n divFolder.textContent = '';\n await Promise.all([\n fetchPath(`files/${id}`),\n fetchPath(`folder/${id}`),\n ])\n .then(([files, folders]) => {\n showFiles(files);\n showFolders(folders);\n })\n .catch((error) => {\n const message = `An error has occured: ${error.message}`;\n const messageElm = document.querySelector('div.message');\n messageElm.textContent = message;\n messageElm.className = 'message alert alert-warning';\n })\n .finally(() => {\n spinner.style.display = 'block';\n });\n};\n</code></pre>\n<p><strong>Don't check array length before iterating</strong> There's no need for</p>\n<pre><code>if (folders.length > 0) {\n folders.forEach((data) => {\n</code></pre>\n<p>If the array is empty, no iterations will occur anyway. Surrounding the <code>forEach</code> in another <code>if</code> statement increases indentation unnecessarily and makes more unnecessary cognitive overhead.</p>\n<p><strong>Duplicate listener bug</strong> Every time <code>fetchFolder</code> is called, you also call <code>createFolderEventListener</code>, which does:</p>\n<pre><code>const myfolder = document.getElementsByClassName("folder");\n[...myfolder].forEach(function (element) {\n element.addEventListener("click", function () {\n</code></pre>\n<p>So every time a folder is clicked, you're adding additional listeners to <em>every</em> folder element on the page. This will result in many unnecessary requests, and possibly more strange behavior.</p>\n<p>Only add a listener to a folder if the folder doesn't already have a listener. Or, even better, add only a <strong>single</strong> listener, to a parent element, and utilize event delegation:</p>\n<pre><code>document.addEventListener('click', (e) => {\n if (!e.target.matches('.folder')) {\n return;\n }\n const { id } = e.target.dataset;\n fetchFolder(\n fetchFiles(id);\n );\n});\n</code></pre>\n<p>Run that <em>once</em>, on pageload, and then you can remove <code>createFolderEventListener</code>.</p>\n<p><strong>Do the same thing</strong> for <code>createFileEventListener</code>, which has the same problem.</p>\n<p><strong>Precise variable names</strong> You have:</p>\n<pre><code>var divFiles = document.getElementById("files");\n</code></pre>\n<p>and</p>\n<pre><code>function createFileEventListener() {\n const myfolder = document.getElementsByClassName("file");\n</code></pre>\n<p>(<code>createFileEventListener</code> should probably be removed entirely, but if it isn't, make sure to change <code>myfolder</code> to <code>myfile</code>)</p>\n<p>Precise variable names make code easier to read and helps prevent bugs. A variable name should probably only be plural if it refers to a <em>collection</em>. Otherwise, it should be singular. Similarly, a collection should have a plural variable name. Maybe call it <code>filesContainer</code> instead of <code>divFiles</code>, and <code>fileDivs</code> instead of <code>myfolder</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-09T00:34:45.537",
"Id": "491288",
"Score": "0",
"body": "Thanks a lot for the comprehensive review. Appreciate it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-09T01:24:23.523",
"Id": "491291",
"Score": "0",
"body": "For these two lines, I can't avoid to use `var` right? `var divFolder = document.getElementById(\"rootFolder\");\n var divFiles = document.getElementById(\"files\");`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-09T01:26:32.587",
"Id": "491292",
"Score": "1",
"body": "Sure you can, you can always avoid `var`. Use `const` instead"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-09T01:33:22.287",
"Id": "491293",
"Score": "0",
"body": "I will also move certain variable to the class variable like the spinner. `const spinner = document.getElementById('spinner').style.display;`"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-08T15:20:18.573",
"Id": "250369",
"ParentId": "250019",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "250369",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T01:07:27.820",
"Id": "250019",
"Score": "4",
"Tags": [
"javascript",
"jquery"
],
"Title": "Javascript to show folder and files by calling Web Api"
}
|
250019
|
<p>I wanted an easy way to import a large database of crystallographic values into a program I'm working on. I installed Selenium and put together a simple script to scrape space groups and coordinates. There are a total of 230 space groups with a varying number of coordinates and possible translations to consider. <a href="https://i.stack.imgur.com/Zugj6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Zugj6.png" alt="each group is displayed like this on a separate page" /></a></p>
<p>Creating a dictionary to organize all space groups and letters seemed like the best way to go about it, and so this is what I came up with:</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import re, os
class SetOptions:
def __init__(self, wyckoff, view, window):
self.wyckoff=wyckoff
self.driver_path='/usr/local/bin/chromedriver'
# Driver options
self.options=Options()
self.options.headless = view
self.options.add_argument(window)
self.driver = webdriver.Chrome(options=self.options, executable_path=self.driver_path)
# Strings found between the coordinate set on each page
self.html_indices = ['Coordinates', 'specific']
def scrape_positions(self, group, start, stop):
space_groups = {}
self.driver.get("https://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-wp-list?gnum=%s" %(group))
self.driver.find_element_by_xpath("/html/body/table[2]/tbody/tr/td[2]/form/table[2]/tbody/tr/td[1]/input").click()
raw_html=self.driver.page_source
# Strip all html
stripped_html=re.sub('<[^>]+>', '', raw_html)
# Split string data between identifier strings
unsorted_pos = stripped_html.split(start)[1].split(stop)[0]
# Parse translations, coordinates, letters, and multiplicities into line by line string
sorted_pos = os.linesep.join([s for s in unsorted_pos.splitlines() if s])
# Separate letter/multiplicity/symmetry strings from coordinate strings
letters = re.sub(r'\(.*?\)', '', sorted_pos)
regex = re.compile(".*?\((.*?)\)")
# Check for the presence of translations and index that count
centring_count = letters.split().count('+')
# If present, parse translations separately as they will always occur before coordinates
c_centring=[c for c in re.findall(regex, sorted_pos)[:centring_count][::-1]]
# Once translations are removed from parenthetical strings only coordinate sets remain
pos = [[pos] for pos in re.findall(regex, sorted_pos)[centring_count:][::-1]]
# Join letter/multiplicity strings, discard sym strings
letters=[s[:s.find(next(filter(str.isalpha, s)))+1]
for s in letters.split() if s[0].isnumeric()][::-1]
# if translations are present append the data to the end of letter/position lists
if c_centring:
base = centring_count
letters.append('translation')
pos.append(c_centring)
else:
base=1
# Add each letter/multiplicity pair as keys with their corresponding coordinates
for let in letters:
index=[int(re.findall(r"\d+", let)[0])//base # add translations last
if letters.index(let) < len(letters)-1 else len(pos)][0]
space_groups.update({let: pos[:index][::-1]})
pos=pos[index:]
return space_groups
def update_groups(self, index_1, index_2):
for i in range(index_1, index_2):
self.wyckoff.update({i: self.scrape_positions(i, *self.html_indices)})
# Print string data that is easily copied and pasted into a text editor
return str(self.wyckoff).replace("['","[").replace("']","]")
#--------------------------------------------------------------------------
wyckoff = {}
print(SetOptions(wyckoff, True, "--window-size=1920, 1200").update_groups(166,167))
</code></pre>
<p>Output:</p>
<pre><code>> {166: {'3a': [[0,0,0]], '3b': [[0,0,1/2]], '6c': [[0,0,z], [0,0,-z]],
> '9d': [[1/2,0,1/2], [0,1/2,1/2], [1/2,1/2,1/2]], '9e':
> [[1/2,0,0], [0,1/2,0], [1/2,1/2,0]], '18f': [[x,0,0], [0,x,0],
> [-x,-x,0], [-x,0,0], [0,-x,0], [x,x,0]], '18g': [[x,0,1/2],
> [0,x,1/2], [-x,-x,1/2], [-x,0,1/2], [0,-x,1/2], [x,x,1/2]], '18h':
> [[x,-x,z],[x,2x,z], [-2x,-x,z], [-x,x,-z], [2x,x,-z], [-x,-2x,-z]],
> '36i':[[x,y,z], [-y,x-y,z], [-x+y,-x,z], [y,x,-z], [x-y,-y,-z],
> [-x,-x+y,-z], [-x,-y,-z], [y,-x+y,-z], [x-y,x,-z], [-y,-x,z],
> [-x+y,y,z], [x,x-y,z]], 'translation': [[1/3,2/3,2/3', '2/3,1/3,1/3',
> '0,0,0]]}}
</code></pre>
<p>Any feedback is welcome as I'm sure there are better approaches.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T02:31:54.843",
"Id": "250021",
"Score": "1",
"Tags": [
"python-3.x"
],
"Title": "First attempt at a python webscrape"
}
|
250021
|
<p>I tried to write Candy Land game in Haskell as a step to work on something bigger than those toy programs/functions I used to write. I wrote myself a python version first, with a functional mindset before I started working on the actual Haskell version, and it was a breeze and easy and I got it to work in a little bit more than one hour. After that I started writing my Haskell version and it was not pleasant at all. The code I am posting here took me multiple coding sessions and I don't even have all the features I had in my python version.</p>
<p>This is the current state of the game:</p>
<ol>
<li>it doesn't support interactive play.</li>
<li>it doesn't shuffle the cards yet. I googled shuffling in Haskell before I set out to write my own version but I didn't find any library that's simple and concise, except for System.Random.Shuffle but I haven't figured out how to install it. (I am using Haskell platform)</li>
<li>Since the game is deterministic once the deck is shuffled, the game itself right now is only a simulation of the play rather an interactive play.</li>
</ol>
<p>I want to use this as an example to seek advises in building applications in Haskell.</p>
<ol>
<li>What is the best way to model the game? I used <code>StateT</code> over <code>ReaderT</code> with all mutable states in <code>StateT</code>, which is pretty much an equivalent of an imperative programming langague <code>class</code>. Some part of gets bloated and clumsy, for example <code>turn</code> function.</li>
<li>I tried to model all data using types, but I am not sure if I modeled things efficiently.</li>
</ol>
<p>Please feel free to share your opinion/suggestion/critism on any part of the program. I appreciate your feedback.</p>
<pre><code>import qualified Control.Monad.Trans.Reader as R
import qualified Control.Monad.Trans.State as S
import Control.Monad.Trans.Class (lift)
import qualified Data.Map as M
import qualified Data.Array as A
import qualified System.Random as Rand
data Color
= Red
| Purple
| Blue
| Yellow
| Orange
| Green
deriving (Show, Eq, Ord)
colors = [Red, Purple, Blue, Yellow, Orange, Green]
data SpecialFood
= Cupcake
| Icecream
| Gummystar
| Gingerbreadman
| Lollipop
| Popsicle
| Chocolate
deriving (Show, Eq, Ord)
foods =
[ Cupcake, Icecream, Gummystar
, Gingerbreadman, Lollipop, Popsicle, Chocolate
]
data Path
= PPeppermint
| PGummybear
deriving Show
data Tile
= TStart
| TRegular Color
| TPassStart Color Path
| TPassEnd Color Path
| TLicorice Color
| TSpecial SpecialFood
| TRainbow
deriving Show
tileHasColor :: Color -> Tile -> Bool
tileHasColor _ TStart = False
tileHasColor c1 (TRegular c2) = c1 == c2
tileHasColor c1 (TPassStart c2 _) = c1 == c2
tileHasColor c1 (TPassEnd c2 _) = c1 == c2
tileHasColor c1 (TLicorice c2) = c1 == c2
tileHasColor _ (TSpecial _) = False
tileHasColor _ TRainbow = True
tileIsFood :: SpecialFood -> Tile -> Bool
tileIsFood food (TSpecial fd) = food == fd
tileIsFood food _ = False
data Player
= PRed
| PBlue
| PGreen
| PYellow
deriving (Show, Eq, Ord)
data Card
= CSingle Color
| CDouble Color
| CSpecial SpecialFood
deriving Show
data Board
= Board
{ allTiles :: A.Array Int Tile
, colorTiles :: M.Map Color [Int]
, specialTiles :: M.Map SpecialFood Int
} deriving Show
lastTile :: Board -> Int
lastTile board = snd $ A.bounds $ allTiles board
mkTileArray :: [Tile] -> A.Array Int Tile
mkTileArray ts = A.array (0, len-1) $ zip [0..] ts
where len = length ts
mkColorTileMap :: [Tile] -> M.Map Color [Int]
mkColorTileMap ts = M.fromList $ zip colors $ map mkColorPosList colors
where
mkColorPosList c = [ i | (i, t) <- zip [0..] ts, tileHasColor c t]
mkSpecialTileMap :: [Tile] -> M.Map SpecialFood Int
mkSpecialTileMap ts = M.fromList foodPosList
where
foodPosList =
[ (fd, head pos)
| fd <- foods
, let pos = [ i | (i, t) <- zip [0..] ts, tileIsFood fd t]
, length pos == 1
]
mkBoard :: [Tile] -> Board
mkBoard ts = Board arr colorMap foodMap
where
arr = mkTileArray ts
colorMap = mkColorTileMap ts
foodMap = mkSpecialTileMap ts
type GameMove = Int -> Int
moveBeyond pos = filter (>pos)
move :: Monad m => Card -> R.ReaderT Board m GameMove
move (CSingle c) = do
board <- R.ask
return $ \pos ->
if pos == lastTile board
then pos
else
case fmap (moveBeyond pos) $ M.lookup c (colorTiles board) of
Nothing -> lastTile board -- or pos, depending on the moving rule
Just [] -> lastTile board
Just (x:_) -> x
move (CDouble c) = do
movef <- move (CSingle c)
return $ \pos -> let nextPos = movef pos in movef nextPos
move (CSpecial food) = do
board <- R.ask
return $ \pos ->
if pos == lastTile board
then pos
else
case M.lookup food (specialTiles board) of
Nothing -> pos
Just x -> x
-- I did not take advantage of the certain patterns
-- in the Candy Land game board to create the tiles list.
tiles :: [Tile]
tiles =
[ TStart
, TRegular Red
, TRegular Purple
, TRegular Yellow
, TPassStart Blue PPeppermint
-- large number of code was omitted here to save space.
, TRegular Green
, TRainbow
]
gameBoard = mkBoard tiles
type Deck = [Card]
standardDeck = singleCards ++ doubleCards1 ++ doubleCards2 ++ specialCards
where
singleCards = take 36 $ cycle $ map CSingle colors
doubleCards1 = take 16 $ cycle $ map CDouble [Red, Purple, Yellow, Blue]
doubleCards2 = take 12 $ cycle $ map CDouble [Orange, Green]
specialCards = map CSpecial foods
shuffle :: Deck -> Deck
shuffle = id -- a placeholder function
data PlayerProgress
= PlayerProgress
{ pPosition :: Int
, pWaits :: Int
} deriving Show
initPlayer :: PlayerProgress
initPlayer = PlayerProgress { pPosition=0, pWaits=0 }
data Game
= Game
{ gProgress :: M.Map Player PlayerProgress
, gState :: GameState
, gDeck :: Deck
, gTurns :: [Player]
} deriving Show
data GameState
= GContinue
| GWonBy Player
| GTerminated String
deriving Show
terminate :: String -> S.StateT Game (R.ReaderT Board IO) ()
terminate err = S.get >>= \g -> S.put $ g { gState=GTerminated err }
winner :: Player -> S.StateT Game (R.ReaderT Board IO) ()
winner p = S.get >>= \g -> S.put $ g { gState=GWonBy p }
drawCard :: S.StateT Game (R.ReaderT Board IO) (Maybe Card)
drawCard = do
g <- S.get
case gDeck g of
[] -> return Nothing
(c:cs) -> do
S.put $ g { gDeck=cs }
return (Just c)
logGame :: String -> S.StateT Game (R.ReaderT Board IO) ()
logGame s = lift $ lift $ putStrLn s
turn :: S.StateT Game (R.ReaderT Board IO) ()
turn = do
g <- S.get
case gState g of
GContinue -> case gDeck g of
[] -> terminate "out of cards!"
(c:cards) -> case gTurns g of
[] -> terminate "out of players! huh?"
(p:players) -> case M.lookup p (gProgress g) of
Nothing -> terminate "Who is this? How did the game even started?"
(Just (PlayerProgress pos wait)) -> if wait > 0
then
do
logGame $ (show p) ++ " has to wait!"
S.put $ g
{ gProgress=M.insert p (PlayerProgress pos (wait-1)) (gProgress g)
, gDeck=cards
, gTurns=players
}
else
do
mf <- lift $ move c
board <- lift $ R.ask
let pos' = mf pos
logGame $ (show p) ++ " moves from " ++ show pos ++ " to " ++ show pos'
S.put $ g
{ gProgress=M.insert p (PlayerProgress pos' 0) (gProgress g)
, gDeck=cards
, gTurns=players
}
if pos' == lastTile board
then winner p
else return ()
-- if the game state is not continue, do nothing
_ -> return ()
startGame :: [Player] -> Deck -> Game
startGame players deck =
Game { gProgress=M.fromList $ zip players $ map (const initPlayer) players
, gState=GContinue
, gDeck=deck
, gTurns=cycle players
}
play :: Game -> (R.ReaderT Board IO) ()
play g = do
(_, g') <- S.runStateT turn g
case gState g' of
GTerminated s -> lift $ putStrLn s
GWonBy winner -> lift $ putStrLn $ "We got a winner!" ++ show winner
GContinue -> play g'
playCandyLand :: Board -> Deck -> [Player] -> IO ()
playCandyLand _ _ [] = putStrLn "cannot play without any players"
playCandyLand board deck players = do
putStrLn "Starting Candy Land..."
let
initGame = startGame players deck
R.runReaderT (play initGame) board
</code></pre>
<p>After the program is loaded in GHCi, you can run the following to show the simulated result:</p>
<pre><code>playCandyLand (mkBoard tiles) standardDeck [PRed, PBlue]
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T03:40:50.653",
"Id": "250023",
"Score": "2",
"Tags": [
"game",
"haskell"
],
"Title": "Candy Land in Haskell"
}
|
250023
|
<p><strong>Note: I have a working solution, my question is about optimization and other approaches.</strong></p>
<h2>Problem Description</h2>
<p>Hello, I'm re-writing an old program I made that solves <a href="https://en.wikipedia.org/wiki/Nonogram" rel="noreferrer">nonograms</a>.
As part of solving it, I generate (for some of the lines) an array of all possible ways to fit the numbers in.</p>
<p>I want to create a piece of code, that will iterate all the positions in which I can put the spaces, for example: if there's a line with size <code>5</code>, and the numbers are <code>1, 1</code>, there are multiple ways do order the numbers, like <code>1-1--, 1--1-, 1---1, --1-1, ...</code> (<code>-</code> is a white box, while <code>1</code> will be black).</p>
<h2>Problem Breakdown</h2>
<p>So if we look at the example above, we can describe the options like this:</p>
<ol>
<li><p>The total size is 5, and we have two <code>1</code>, therefore we have <code>2</code> white boxes to play around with (1 must be between the numbers), I have another function that calculates that "free space".</p>
</li>
<li><p>We can index the possible places for the spaces this way: <code>[0]</code> <code>1</code> <code>[1]</code> <code>1</code> <code>[2]</code>, meaning the spaces can go in each of the <code>[indexes]</code>.</p>
</li>
<li><p>All the options of placing the spaces can be solved with nested loops, but since the "free space" and the possible indexes are dynamic, this is not an option.</p>
</li>
<li><p>For solution I try to create "dynamic" nested loops, with any range and depth, the question is:</p>
</li>
</ol>
<p><strong>Is there a more efficient way of doing so?</strong></p>
<h2>Possible Solution</h2>
<p>The scope my question refers to is not related specifically to solving a nonorgram or even a specific language, but since I'm writing this in C++, I will post my attempt for a code that does so:</p>
<pre><code>#include <vector>
#include <iostream>
using namespace std;
int main() {
int iterators_number = 3; // Number of iterators, bubble sort for example uses 2, note: this is not for bubble sorting.
int iterators_range = 3; // The maximum value for the iterators values, can be the size of the array for example.
int move_index;
vector<int> options_iteration(iterators_number, 0);
while (true) {
for (int i = 0; i < iterators_number; i++) cout << options_iteration[i] << " ";
cout << endl;
for (move_index = iterators_number - 1;
(move_index >= 0) && (options_iteration[move_index] > iterators_range - 1); move_index--);
if (move_index < 0) break;
int new_value = options_iteration[move_index] + 1;
for (; move_index < iterators_number; move_index++) options_iteration[move_index] = new_value;
}
return 0;
}
</code></pre>
<p>Output:</p>
<pre><code>0 0 0
0 0 1
0 0 2
0 0 3
0 1 1
0 1 2
0 1 3
0 2 2
0 2 3
0 3 3
1 1 1
1 1 2
1 1 3
1 2 2
1 2 3
1 3 3
2 2 2
2 2 3
2 3 3
3 3 3
</code></pre>
<p>If anyone is interested in the full implementation, once it's done and fully documented, I will upload it to my <a href="https://github.com/UriyaHarpeness" rel="noreferrer">GitHub account</a>.</p>
<p>Thanks in advance for the helpers and commentators.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T08:18:44.597",
"Id": "490378",
"Score": "0",
"body": "simply using `'\\n'` compared to `std::endl` makes your program much faster"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T08:23:43.533",
"Id": "490379",
"Score": "0",
"body": "This is not part of the question, this is just so people can test it out their selves."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T08:25:28.577",
"Id": "490380",
"Score": "2",
"body": "I am writing a review for you. I just got rid of using `std::endl` early on as it is much slower than printing a new line (`'\\n'`). That's why I believed it is good for you to know"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T08:26:44.763",
"Id": "490381",
"Score": "0",
"body": "Thank you very much, my real code does not print for each iteration, this is for easy testing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T08:44:55.837",
"Id": "490382",
"Score": "0",
"body": "I tested your code with `iterators_number = 2` and `iterators_range = 3`. There is repetition in the output, is this fine?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T08:55:24.203",
"Id": "490383",
"Score": "0",
"body": "@AryanParekh, sorry, updated the code, it got mixed up when I took only this piece of code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T09:25:58.340",
"Id": "490385",
"Score": "0",
"body": "error when trying `iterators_number = 5` and `iterators_range = 2`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T09:42:16.753",
"Id": "490386",
"Score": "0",
"body": "@AryanParekh sorry again, another name was replaced, the two were mixed, fixed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T17:38:35.507",
"Id": "490427",
"Score": "0",
"body": "If you have a lot of memory available, some sort of dynamic programming I think could be more performant, just as a suggestion of an alternative approach. I think this may even be sensible for nonograms, since the numbers are relatively small so you're likely to get many chances to reuse your previously computed results\n\nWith your approach with iterators I think it's well done, I don't really see a chance for any significant improvements, ultimately it seems to me like it has complexity in the number of possible permutations, you can't say fairer then that."
}
] |
[
{
"body": "<h2>Overall Observations</h2>\n<p>The more code you provide the better the reviews you will get. There are 2 statements, 1 in the question and 1 in the comments after the question that almost make it off-topic for the Code Review site:</p>\n<ol>\n<li><code>... my real code does not print for each iteration, this is for easy testing.</code></li>\n<li><code>I have another function that calculates that "free space".</code></li>\n</ol>\n<p>As provided in the question the code is almost unreadable and therefore would be a problem for maintenance. If I were an teacher grading this code the best grade I can give it is a C (70%) because it compiles and runs. The variable names are meaningful. In a professional environment if I were your manager we would have a long talk in private about why it is important to make the code more readable.</p>\n<p>In a professional environment you are very unlikely to be the only one maintaining the code for multiple reasons:</p>\n<ol>\n<li>You may get promoted and not assigned to maintain the code anymore.</li>\n<li>You may quit and get another job.</li>\n<li>A bug may exist in the code that needs to be fixed and you are assigned to a higher priority project so someone else will be assigned to fix the code.</li>\n</ol>\n<p>There are more reasons than just the 3 above. For all these reasons I will be addressing coding style here.</p>\n<h2>Possible Optimizations</h2>\n<p>The first rule of optimization is don't optimize, the second is find all the bottlenecks in the code (bottlenecks being functions that slow down the code). The primary way to optimize C++ code is to use the built in compiler optimization using the -O through -O3 compiler command lines. This will generally produce very fast code. It will be very difficult to provide optimizations for this code as currently presented, but if you are compiling for debug one possible optimization might be to use the C++ iterators provided for each of the container classes such as <code>vector</code>.</p>\n<p>You might also want to make the variables <code>iterators_number</code> and <code>iterators_range</code> constants since they don't change.</p>\n<pre><code> const int iterators_number = 3;\n const int iterators_range = 3;\n</code></pre>\n<h2>Avoid <code>using namespace std;</code></h2>\n<p>If you are coding professionally you probably should get out of the habit of using the <code>using namespace std;</code> statement. The code will more clearly define where <code>cout</code> and other identifiers are coming from (<code>std::cin</code>, <code>std::cout</code>). As you start using namespaces in your code it is better to identify where each function comes from because there may be function name collisions from different namespaces. The identifier<code>cout</code> you may override within your own classes, and you may override the operator <code><<</code> in your own classes as well. This <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">stack overflow question</a> discusses this in more detail.</p>\n<h2>Declare Variable as Necessary</h2>\n<p>As far as I can tell the variable <code>move_index</code> does not need to maintain it's value between iterations of the <code>while (true)</code> loop so it should be declared within the loop, the declaration should include the initialization of the variable in almost all cases, but definitely in this case.</p>\n<h2>Don't Use One line <code>for</code> Loops or <code>if</code> Statements</h2>\n<p>The code contains this line:</p>\n<pre><code> for (int i = 0; i < iterators_number; i++) cout << options_iteration[i] << " ";\n</code></pre>\n<p>On my first time through the code I missed the fact that the for loop had an action. This code should be on 2 lines at least but preferably 4. 2 lines:</p>\n<pre><code> for (int i = 0; i < iterators_number; i++)\n cout << options_iteration[i] << " ";\n</code></pre>\n<p>Why 4 lines? One of the easiest mistakes to make when maintaining code is to add a statement to a for loop or if statement without adding the braces necessary to make it part of the loop. So when creating new code it is better to add the to begin with:</p>\n<pre><code> for (int i = 0; i < iterators_number; i++)\n {\n std::cout << options_iteration[i] << " ";\n }\n</code></pre>\n<p>I didn't come up with this, it was forced on me by a company coding standard, however, I saw the value of it having made that kind of mistake a number of times.</p>\n<p>This version of the code is slightly longer but muc more readable and easier to maintain:</p>\n<pre><code>#include <vector>\n#include <iostream>\n\nint main() {\n int iterators_number = 3; // Number of iterators, bubble sort for example uses 2, note: this is not for bubble sorting.\n int iterators_range = 3; // The maximum value for the iterators values, can be the size of the array for example.\n\n std::vector<int> options_iteration(iterators_number, 0);\n\n while (true) {\n for (int i = 0; i < iterators_number; i++)\n {\n std::cout << options_iteration[i] << " ";\n }\n std::cout << std::endl;\n\n int move_index = iterators_number - 1;\n for ( ;\n (move_index >= 0) && (options_iteration[move_index] > iterators_range - 1);\n move_index--)\n ;\n if (move_index < 0)\n break;\n\n int new_value = options_iteration[move_index] + 1;\n for ( ; move_index < iterators_number; move_index++)\n {\n options_iteration[move_index] = new_value;\n }\n }\n\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T14:12:53.003",
"Id": "490410",
"Score": "0",
"body": "I don't agree with the comments of things that i have set as out of scope, like the definitions inline with value of the iterators, or the free space function. I can post the full implementation, but it won't be of much value, so the scope needs to be narrowed down. As for the other comments, thank you, appreciate it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T14:30:48.883",
"Id": "490411",
"Score": "0",
"body": "If the question was completely off-topic I would not have answered it, I would have down voted and voted to close (it takes 5 votes from the community to close a question)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T17:48:15.837",
"Id": "490428",
"Score": "2",
"body": "@UriyaHarpeness Everything you post here is fair game. Note that the answers are also not only going to be seen by you, but also by many others, and we don't want to teach people that it's OK to have suboptimal code if you just say \"it's out of scope\"."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T13:29:45.930",
"Id": "250038",
"ParentId": "250024",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T08:05:50.857",
"Id": "250024",
"Score": "6",
"Tags": [
"c++",
"performance",
"algorithm",
"combinatorics"
],
"Title": "Combinatorics, C++ and optimization"
}
|
250024
|
<p>I understand that creating public properties that control private fields is good practice because of coupling and encapsulation, although lately I have seen it as such a waste of boilerplate code for a simple entity class like below.</p>
<p>Take this class for instance,</p>
<pre><code>public class PersonEntity
{
private string _firstName;
private string _lastName;
private int _age;
public class PersonEntity(string firstName, string lastName, int age)
{
_firstName = firstName;
_lastName = lastName;
_age = age;
}
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
public int Age
{
get { return _age; }
set { _age = value; }
}
}
</code></pre>
<p>If all I am using is the property, is it okay to refactor the class to look something like this?</p>
<pre><code>public class PersonEntity
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public class PersonEntity(string firstName, stirng lastName, int age)
{
FirstName = firstName;
LastName = lastName;
Age = age;
}
}
</code></pre>
<p>Or maybe even this is more simple (using object initialization to construct):</p>
<pre><code>public class PersonEntity
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
</code></pre>
<p>Which one should I implement if all I want to use the entity for is to map data from a database, and use it as a model to write to the database at a later date than when it was created?</p>
<p>Which versions should I use, when should I use them, and for what reasons should I use each one?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T09:10:00.290",
"Id": "490384",
"Score": "10",
"body": "The `public T Name { get; set; }` properties are called [Auto-Implemented Properties](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/auto-implemented-properties). The compiler creates the private backing field for you so they are just a convenience. I'd say 100% use it for simple properties like you've shown."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T10:59:26.427",
"Id": "490487",
"Score": "0",
"body": "Note that auto-implemented properties were added to C# 3.0. So you may see needlessly-explicit members in code that was written to target earlier C# versions, or by people who learned C# then and never bothered to update their knowledge."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T22:33:29.483",
"Id": "490559",
"Score": "0",
"body": "Actually that is not really encapsulation but pseudo object orientation. I would refactor it like you mentioned it."
}
] |
[
{
"body": "<p>There is a special use case when the (slightly modified) second approach could be beneficial. Namely when you want to create <strong>immutable objects</strong>.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public sealed class PersonEntity\n{\n public string FirstName { get; }\n public string LastName { get; }\n public int Age { get; }\n\n public PersonEntity(string firstName, string lastName, int age)\n {\n FirstName = firstName;\n LastName = lastName;\n Age = age;\n }\n}\n</code></pre>\n<p>By removing the setters you are not allowing the consumer of the class to alter its data after creation. In case of concurrency immutable structures can be shared safely between multiple workers without extra syncronization.</p>\n<p>You can define <strong>with method(s)</strong> to this class as an extension to provide copy with alternative value functionality.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public PersonEntity WithFirstName(string firstName)\n{\n return new PersonEntity(firstName, LastName, Age);\n}\n\npublic PersonEntity WithLastName(string lastName)\n{\n return new PersonEntity(FirstName, lastName, Age);\n}\n\npublic PersonEntity WithAge(int age)\n{\n return new PersonEntity(FirstName, LastName, age);\n}\n</code></pre>\n<p>Of course you can make it a bit more generic:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public PersonEntity With(string firstname = null, string lastName = null, int? age = null)\n{\n return new PersonEntity(\n firstName ?? this.FirstName, \n lastName ?? this.LastName, \n age ?? this.Age);\n\n}\n</code></pre>\n<p>Usage sample:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>var xy = new PersonEntity("x", "y", 15);\nvar xz = xy.With(lastName: "y");\nvar xz25 = xz.With(age: 25);\n</code></pre>\n<hr />\n<p><strong>UPDATE</strong>: C# 9's record<br />\nIn C# 9 there will be a new construction called <a href=\"https://anthonygiretti.com/2020/06/17/introducing-c-9-records/\" rel=\"noreferrer\">record</a>.</p>\n<p>Declaration</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public record PersonEntity\n{\n public string FirstName { get; init; }\n public string LastName { get; init; }\n public int Age { get; init; }\n}\n</code></pre>\n<p>Usage</p>\n<pre class=\"lang-cs prettyprint-override\"><code>var xy = new PersonEntity { FirstName = "x", LastName = "y", Age = 15 }; \nvar xz = xy with { LastName = "y" };\nvar xz25 = xz with { Age = 25 };\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T15:49:08.693",
"Id": "490416",
"Score": "0",
"body": "@symaps Thanks for spotted a typo. :D"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T18:33:10.223",
"Id": "490430",
"Score": "3",
"body": "+1 for the record suggestion, but do note that the behaviour of records is fundamentally different (they provide value equality instead of reference equality)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T11:17:34.980",
"Id": "250030",
"ParentId": "250025",
"Score": "12"
}
},
{
"body": "<p>The refactor with an explicit constructor is a drop-in replacement for the original code and would be the direction I would go.</p>\n<p>The code requiring object initialization requires a change to how objects are constructed and may break code elsewhere in the project.</p>\n<p>In my opinion, I wouldn't bother changing it unless and until another change is needed. Although the code is unnecessarily verbose, it is easily understood and does not have any other code smells of concern. I wouldn't consider this refactoring a good use of time. I would instead focus on other refactorings that can provide a bigger benefit.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T17:22:57.447",
"Id": "250047",
"ParentId": "250025",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T08:31:25.470",
"Id": "250025",
"Score": "9",
"Tags": [
"c#"
],
"Title": "Clearing up property and field confusion in C#?"
}
|
250025
|
<p>I have some use-cases where I want the behaviour of the build-in <code>any()</code> function to be slightly different, namely to return <code>True</code> if the iterable is empty.</p>
<p>Therefore I came up with the following override:</p>
<pre><code>_any = any # Alias built-in any.
def any(iterable, *, default=False):
"""Generalization of the built-in any() function."""
if not default:
return _any(iterable)
count = 0
for count, item in enumerate(iterable, start=1):
if item:
return True
return count == 0
</code></pre>
<p>The code I used to test this is:</p>
<pre><code>EMPTY_TUPLE = ()
FALSEY_TUPLE = (False, None, 0, '')
TRUEY_TUPLE = (False, None, 1, '')
def empty_iterables():
"""Yields empty iterables."""
yield list(EMPTY_TUPLE)
yield EMPTY_TUPLE
yield {item: item for item in EMPTY_TUPLE}
yield set(EMPTY_TUPLE)
yield (i for i in EMPTY_TUPLE)
def falsey_iterables():
"""Yields iterables that any() should assert as False."""
yield list(FALSEY_TUPLE)
yield FALSEY_TUPLE
yield {item: item for item in FALSEY_TUPLE}
yield set(FALSEY_TUPLE)
yield (i for i in FALSEY_TUPLE)
def truey_iterables():
"""Yields iterables that any() should assert as True."""
yield list(TRUEY_TUPLE)
yield TRUEY_TUPLE
yield {item: item for item in TRUEY_TUPLE}
yield set(TRUEY_TUPLE)
yield (i for i in TRUEY_TUPLE)
def test():
"""Tests the custom any() function."""
# Built-in behaviour.
for iterable in empty_iterables():
assert any(iterable) is False
for iterable in falsey_iterables():
assert any(iterable) is False
for iterable in truey_iterables():
assert any(iterable) is True
# Custom behaviour.
for iterable in empty_iterables():
assert any(iterable, default=True) is True
for iterable in falsey_iterables():
assert any(iterable, default=True) is False
for iterable in truey_iterables():
assert any(iterable, default=True) is True
if __name__ == '__main__':
test()
</code></pre>
<p>I wonder whether there's a more elegant way to implement the custom <code>any()</code> function with the aforementioned behaviour.</p>
<p><strong>Use case</strong></p>
<p>I have a custom monitoring system, that determines the state of a system using check records from a MariaDB database. I use peewee as an ORM:</p>
<pre><code>def check_customer_system(system):
"""Returns the customer online check for the respective system."""
end = datetime.now()
start = end - CUSTOMER_INTERVAL
condition = OnlineCheck.system == system
condition &= OnlineCheck.timestamp >= start
condition &= OnlineCheck.timestamp <= end
query = OnlineCheck.select().where(condition)
if query:
return any(online_check.online for online_check in query)
raise NotChecked(system, OnlineCheck)
</code></pre>
<p>In the current implementation, I need to check, whether the amount of records in the query in non-empty by doing <code>if query:</code>.
However, this will execute the query an load all records into RAM, which I want to avoid. Peewee has the optional <code>.iterator()</code> method on queries, which will return an iterator, that will not load all records into RAM at once. However, if I use that, <code>if query:</code> will always be <code>True</code> since it's testing the truth value of a generator object then.
Hence, I came up with the idea to implement a function, that returns <code>True</code> if any value of an iterable is <code>True</code> or the iterable is empty.</p>
<p>And I just realized that this is indeed an XY-Problem, since I'd loose the ability to distinguish between a checked and a non-checked system.
Thanks @Eric Duminil.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T14:04:32.007",
"Id": "490408",
"Score": "0",
"body": "any reason for `start=1`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T14:08:02.453",
"Id": "490409",
"Score": "3",
"body": "@hjpotter92 To distinguish empty input from single-element input."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T15:19:28.020",
"Id": "490414",
"Score": "2",
"body": "You've misspelt [truthy](https://www.lexico.com/definition/truthy)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T07:26:10.293",
"Id": "490473",
"Score": "4",
"body": "It looks like a [XY problem](https://en.wikipedia.org/wiki/XY_problem). We shouldn't be reviewing this code, because its specs are broken, and no implementation can save it. We should be looking at the code using your custom `any`, to see how the logic can be modified."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T09:39:11.933",
"Id": "490479",
"Score": "1",
"body": "@EricDuminil I clarified the use case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T09:43:53.757",
"Id": "490480",
"Score": "3",
"body": "@RichardNeumann: Interesting, thanks. The question now becomes completely different, though. I'm not sure if it should be a new question, now that you've already got long answers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T10:56:21.513",
"Id": "490486",
"Score": "0",
"body": "@EricDuminil Hmm, what did you mean with the specs being broken?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T11:03:46.090",
"Id": "490490",
"Score": "0",
"body": "@superbrain `any` is a well defined, very important mathematical concept. You cannot simply redefine it and make it return wrong results for empty sets. If you do, you get contradictory results really fast, and your code will become buggy in many unexpected places. It doesn't result from a wrong implementation, but from the wrong specs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T11:19:36.103",
"Id": "490491",
"Score": "0",
"body": "@EricDuminil Ah, ok. I thought you meant the spec itself being broken somehow, not the spec disagreeing with something else (the normal `any`). I agree as written it's bad/wrong (said so in my answer), but I think the problem is just the name, not the behavior. So I'd say their implementation of the latter is fit for review (particularly because the question is about \"a more elegant way to implement [...] the aforementioned behaviour\")."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T14:20:45.267",
"Id": "490505",
"Score": "0",
"body": "What is `online_check.online`? Does it use custom python logic, or could it be written as an SQL query too?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T10:17:42.130",
"Id": "490588",
"Score": "0",
"body": "It's a boolean field of a record."
}
] |
[
{
"body": "<p>I really think this is a bad idea. A function called <code>any</code> returning <code>True</code> if there not only isn't anything <em>true</em> but even not anything <em>at all</em>... that's just wrong. It sure isn't a "generalization". Shadowing the built-in is not a good idea, either. Maybe just call yours <code>any_or_empty</code> (without a default)?</p>\n<p>For the emptiness check, the counting seems like overkill and I think a Boolean is clearer (and probably faster, due to not going through <code>enumerate</code>):</p>\n<pre><code> empty = True\n\n for item in iterable:\n if item:\n return True\n empty = False\n\n return empty\n</code></pre>\n<p>Or with a sentinel, to get rid of the assignment in the loop:</p>\n<pre><code> item = sentinel = object()\n\n for item in iterable:\n if item:\n return True\n\n return item is sentinel\n</code></pre>\n<p>For best speed, you could just handle the first item yourself and then let the built-in handle the rest:</p>\n<pre><code>def any(iterable, *, default=False):\n """Modification of the built-in any() function."""\n\n it = iter(iterable)\n sentinel = object()\n first = next(it, sentinel)\n if first is sentinel:\n return default\n return bool(first) or _any(it)\n</code></pre>\n<p>Your test code uses the words "truey" and "falsey". That's not Python terminology. See the Python docs, <a href=\"https://www.google.com/search?q=site%3Adocs.python.org+%22truey%22+OR+%22falsey%22\" rel=\"noreferrer\">you'll never find those words</a>. It's true and false, as you can for example see at <a href=\"https://docs.python.org/3/reference/compound_stmts.html#if\" rel=\"noreferrer\"><code>if</code></a>, <a href=\"https://docs.python.org/3/reference/expressions.html#booleans\" rel=\"noreferrer\">Boolean operations</a> and <a href=\"https://docs.python.org/3/library/stdtypes.html#truth-value-testing\" rel=\"noreferrer\">Truth Value Testing</a>.</p>\n<p>The name <code>falsey_iterables</code> is ambiguous if not misleading, as it doesn't yield any false iterables. They're all true. They just don't <em>contain</em> anything true. I'd suggest <code>iterables_without_trues</code>. And <code>iterables_with_true</code> instead of <code>truey_iterables</code> for consistency.</p>\n<p>Did you have this idea because <code>next</code>, <code>min</code> and <code>max</code> offer a <code>default</code> parameter? In their cases it makes sense, as they rather <em>need</em> non-empty inputs. And meaningful defaults are possible there, for example <code>min</code> with <code>default=float('inf')</code> could be a useful default for the code using the result.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T15:07:03.510",
"Id": "490413",
"Score": "0",
"body": "Thanks for the review. Also thanks for the review of the testing code, though it was not, what this review was about. I'll definitely change the name of the custom `any()`, since on second thought, a function called \"any\" should indeed never return `True` on an empty input."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T15:33:03.077",
"Id": "490415",
"Score": "0",
"body": "And now I'm curious why someone voted that \"This answer is not useful\"..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T16:03:20.450",
"Id": "490418",
"Score": "0",
"body": "You've got a recursive implementation. If you have an iterable of 100 false values, you'll use 100 stack frames, pealing off one value from the head of `iterable` each time. You probably wanted to call `_any(it)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T16:08:56.800",
"Id": "490419",
"Score": "4",
"body": "@AJNeufeld Ah yes, thanks. As stated, the intention was to \"let the built-in handle the rest\". Fixed. Proves the point that we shouldn't shadow the built-in :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T01:26:22.817",
"Id": "490462",
"Score": "1",
"body": "Not overriding a core builtin and handing over the non-empty case to the builtin are both excellent suggestions for maintainability. Fewer surprises (for anyone already familiar with `any`) and less code overall."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T14:36:01.393",
"Id": "250040",
"ParentId": "250036",
"Score": "13"
}
},
{
"body": "<h1>Any and All</h1>\n<p>If you are going to override <code>any(...)</code> to return a custom result when given an empty iterable, you should also override <code>all(...)</code> to return a custom result as well, for consistency.</p>\n<h1>Detecting the Empty Iterable</h1>\n<p>This code:</p>\n<pre><code> count = 0\n\n for count, item in enumerate(iterable, start=1):\n if item:\n return True\n\n return count == 0\n</code></pre>\n<p>relies on <code>count</code> being reassigned to a non-zero value by the <code>for count ... in enumerable(..., start=1)</code> loop. This has two inefficiencies. First, it is repeatedly assigning values to <code>count</code>. Second, it creates and abandons <code>int</code> objects (once it has gone beyond the range of interned <code>int</code> values), which are only used for their "non equality to zero". A flag could eliminate this second inefficiency:</p>\n<pre><code> is_empty = True\n\n for item in iterable:\n if item:\n return True\n is_empty = False\n\n return is_empty\n</code></pre>\n<p>But this still leaves the first inefficiency: repeated assignments to <code>is_empty</code>.</p>\n<p>Better would be to extract the first value from the iterable. If that fails, then the iterable was empty.</p>\n<pre><code>_any = any\n_all = all\n\ndef any(iterable, *, default=False):\n """Generalization of the built-in any() function."""\n\n if not isinstance(default, bool):\n raise TypeError("Default must be a boolean value")\n\n try:\n it = iter(iterable)\n return bool(next(it)) or _any(it)\n\n except StopIteration:\n return default\n\n\ndef all(iterable, *, default=True):\n """Generalization of the built-in all() function."""\n\n if not isinstance(default, bool):\n raise TypeError("Default must be a boolean value")\n\n try:\n it = iter(iterable)\n return bool(next(it)) and _all(it)\n\n except StopIteration:\n return default\n</code></pre>\n<h1>Testing</h1>\n<p><code>empty_iterables()</code>, <code>falsey_iterables()</code> and <code>truey_iterables()</code> is confusing. It took me a while to determine that you were creating a series of different kinds of test iterables: a <code>list</code>, a <code>tuple</code>, a <code>dict</code>, a <code>set</code>, and a generator expression. Moreover, it is code duplications. All 3 functions are generating the same things, just with different values.</p>\n<p>This would be clearer:</p>\n<pre><code>from typing import Iterable, Any\n\ndef test_iterables_of(*values: Any) -> Iterable[Iterable[Any]]:\n """\n Generate various types of collections of the given values.\n\n Returns a list, tuple, dictionary, set, and generator expression,\n each containing all of the values.\n """\n\n yield list(values)\n yield tuple(values)\n yield dict((val, val) for val in values)\n yield set(values)\n yield (val for val in values) # Generator\n</code></pre>\n<p>And you could use like:</p>\n<pre><code> for iterable in test_iterables_of():\n assert any(iterable, default=True) is True\n\n for iterable in test_iterables_of(False, None, 0, ''):\n assert any(iterable, default=True) is False\n</code></pre>\n<h2>Dictionary Key 0 / False</h2>\n<p>Just a note: Your dictionaries of <code>FALSEY_TUPLE</code> values have only 3 entries, not 4, because the key <code>False</code> and the key <code>0</code> are actually the same key.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T16:34:16.180",
"Id": "490422",
"Score": "1",
"body": "I'd say there was another inefficiency, the `enumerate` iterator being another layer on top of the underlying iterator (creating the ints is part of that, but not all). The assignment in the loop can btw be avoided rather easily, although I didn't think of it at first, either :-) (just added that to my answer)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T08:38:27.937",
"Id": "490476",
"Score": "0",
"body": "If `any` is now broken, the solution isn't to break `all` too for consistency, is it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T21:56:36.790",
"Id": "490553",
"Score": "0",
"body": "@EricDuminil I'm not sure why you feel this is \"breaking\" `any`. The built-in function doesn't support keyword arguments; with no `default=` argument, the upgraded function behaves the same way as the built-in function. If this was submitted as a PEP to the design team, they might very well consider adding the `default` keyword to `any()` and `all()`. Where these upgrades can be \"break\" is forward compatibility; if other keyword arguments were added in Python 3.9 or Python 4.x, this upgrade would, break those. I agree the question update does make this whole mess an XY-Problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T22:30:05.150",
"Id": "490558",
"Score": "1",
"body": "@AJNeufeld The way I see it, an `any` function which returns `True` for an empty set is broken *by design*, even with an extra argument, even if the implementation is correct and if it doesn't break backward compatibility. The corresponding `all`, should, I guess, return `False` for empty collections, which would contradict [vacuous truth](https://en.wikipedia.org/wiki/Vacuous_truth), among others. No amount of documentation could save the surprising bugs coming out of this design."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T23:00:24.193",
"Id": "490562",
"Score": "0",
"body": "@EricDuminil The built-in `all(())` returns `True`. Writing `all((), default=True)` is clearer, because the \"surprising\" value is called out in the function arguments, instead of hidden away is some documentation. This default would actually be very useful in the real world. Cell-phone transmit power control is approximately `turn_power_down = any(received_power_down_flags, default=True)`. If any base station is saying \"turn down your power\", the cell phone turns power down ... but if it can't hear any base station flags, it still must turn its power down so it doesn't become a jammer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T09:54:52.563",
"Id": "490583",
"Score": "1",
"body": "We might have to agree to disagree, then. `all(())` returning `True` is the expected value. The surprising value would be `False`, and I don't see how it would be clear for `all((), default=True)` to return `False`. Your cell phone power example is interesting, but a better function name should be chosen (`any_or_empty` was proposed in another answer, so a modified `all` could be called `all_but_not_empty`). ∃ and ∀ are so important and ubiquitous in math, if you insist on redefining them, you might as well say that 1 = 2."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T15:59:34.957",
"Id": "250042",
"ParentId": "250036",
"Score": "9"
}
},
{
"body": "<h3>Benchmarks and a faster solution</h3>\n<p>Code including the solutions at the end. And note I also have an image further down that might be worth checking out before/while reading.</p>\n<p><strong>Empty iterable</strong></p>\n<p>First an empty iterable, as that's what motivated the question in the first place, and perhaps that also suggests that that happens non-negligibly often in what the OP is doing:</p>\n<pre><code>iterable = [] number = 2,000,000 = how often each function is run\n1.26 1.25 1.23 original\n0.65 0.65 0.65 loop_bool\n0.86 0.86 0.86 loop_sentinel\n1.00 1.00 1.01 default_and_builtin\n1.30 1.33 1.32 try_and_builtin\n0.73 0.72 0.75 for_and_builtin\n0.74 0.73 0.75 for_and_builtin2\n</code></pre>\n<p>The two simpler loop solutions are faster than the original, as they save the cost of <code>enumerate</code> creation. Slowest is the solution with <code>try</code>, as "<a href=\"https://docs.python.org/3/faq/design.html#how-fast-are-exceptions\" rel=\"nofollow noreferrer\">catching an exception is expensive</a>". The other solution using the built-in <code>any</code> instead of looping, the one trying <code>next</code> with a default and then checking that, is faster, but still faster is the <code>for_and_builtin</code> solution:</p>\n<pre><code>def any(iterable, *, default=False):\n it = iter(iterable)\n for first in it:\n return bool(first) or _any(it)\n return default\n</code></pre>\n<p>Its slightly less pretty variant <code>for_and_builtin2</code> is equally fast, as the difference is only in the loop body, which doesn't come into play yet:</p>\n<pre><code>def any(iterable, *, default=False):\n it = iter(iterable)\n for first in it:\n return True if first else _any(it)\n return default\n</code></pre>\n<p><strong>One-element iterables</strong></p>\n<pre><code>iterable = [False] number = 2,000,000 iterable = [True]\n 1.35 1.36 1.38 original 1.26 1.24 1.24 \n 0.73 0.75 0.73 loop_bool 0.70 0.69 0.68 \n 0.93 0.95 0.93 loop_sentinel 0.87 0.89 0.88 \n 1.34 1.36 1.36 default_and_builtin 1.22 1.20 1.21 \n 1.12 1.13 1.11 try_and_builtin 1.02 0.99 0.99 \n 1.05 1.07 1.07 for_and_builtin 0.95 0.95 0.95 \n 0.87 0.89 0.88 for_and_builtin2 0.79 0.76 0.79 \n</code></pre>\n<p>All got slower, except <code>try_and_builtin</code>, which got <em>faster</em> since it doesn't pay the heavy price of catching an exception anymore. Still slightly slower than <code>for_and_builtin</code>, though. And <code>for_and_builtin2</code> was impacted far less and remains the second-fastest solution.</p>\n<p><strong>Two elements</strong></p>\n<p>Not much change here.</p>\n<pre><code> [False, False] number = 2,000,000 [False, True] \n1.42 1.43 1.42 original 1.35 1.32 1.39\n0.77 0.78 0.79 loop_bool 0.74 0.77 0.75\n0.96 0.92 0.95 loop_sentinel 0.91 0.92 0.90\n1.32 1.30 1.32 default_and_builtin 1.29 1.32 1.35\n1.11 1.11 1.08 try_and_builtin 1.09 1.10 1.09\n1.06 1.03 1.06 for_and_builtin 1.05 1.06 1.05\n0.91 0.89 0.86 for_and_builtin2 0.86 0.88 0.86\n</code></pre>\n<p><strong>Long iterables</strong></p>\n<p>At ten elements, the faster loop solutions are still competitive, but in the long runs, they become a lot slower than the solutions making the built-in <code>any</code> do the hard work. Of the three loop solutions, <code>loop_sentinel</code> becomes the fastest, as it has the least to do in each iteration. The three built-in users become equally fast.</p>\n<pre><code>iterable = [False] * 10**1 number = 2,000,000\n2.03 2.02 2.02 original\n1.25 1.25 1.24 loop_bool\n1.30 1.26 1.26 loop_sentinel\n1.43 1.42 1.37 default_and_builtin\n1.19 1.17 1.19 try_and_builtin\n1.18 1.15 1.13 for_and_builtin\n0.96 0.96 0.99 for_and_builtin2\n\niterable = [False] * 10**2 number = 200,000\n0.86 0.85 0.86 original\n0.59 0.59 0.59 loop_bool\n0.41 0.40 0.40 loop_sentinel\n0.21 0.21 0.21 default_and_builtin\n0.19 0.19 0.19 try_and_builtin\n0.18 0.19 0.19 for_and_builtin\n0.17 0.16 0.17 for_and_builtin2\n\niterable = [False] * 10**3 number = 20,000\n0.93 0.93 0.93 original\n0.52 0.51 0.53 loop_bool\n0.32 0.32 0.32 loop_sentinel\n0.09 0.09 0.09 default_and_builtin\n0.09 0.09 0.09 try_and_builtin\n0.09 0.09 0.09 for_and_builtin\n0.09 0.09 0.09 for_and_builtin2\n\niterable = [False] * 10**6 number = 20\n1.01 0.99 1.01 original\n0.53 0.54 0.51 loop_bool\n0.32 0.32 0.32 loop_sentinel\n0.08 0.08 0.08 default_and_builtin\n0.08 0.08 0.08 try_and_builtin\n0.08 0.08 0.08 for_and_builtin\n0.08 0.08 0.08 for_and_builtin2\n\n</code></pre>\n<p>Then again, how likely does the iterable have a million false elements but not a single true element? Probably rather unlikely. If we assume that every element has a 50% chance to be true, then there's only a one-in-a-million chance that there's no true element in the first 20 elements (if the iterable even is that long). So let's have a better look at <code>[False] * n</code> for <code>n</code> from 0 to 20:</p>\n<p><a href=\"https://i.stack.imgur.com/izUAl.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/izUAl.png\" alt=\"closer look at 0 to 20 elements\" /></a></p>\n<p>Full benchmark code (for the textual outputs):</p>\n<pre><code>from timeit import repeat\nfrom functools import partial\n\n_any = any # Alias built-in any.\n\ndef original(iterable, *, default=False):\n if not default:\n return _any(iterable)\n count = 0\n for count, item in enumerate(iterable, start=1):\n if item:\n return True\n return count == 0\n\ndef loop_bool(iterable, *, default=False):\n if not default:\n return _any(iterable)\n empty = True\n for item in iterable:\n if item:\n return True\n empty = False\n return empty\n\ndef loop_sentinel(iterable, *, default=False):\n if not default:\n return _any(iterable)\n item = sentinel = object()\n for item in iterable:\n if item:\n return True\n return item is sentinel\n\ndef default_and_builtin(iterable, *, default=False):\n it = iter(iterable)\n sentinel = object()\n first = next(it, sentinel)\n if first is sentinel:\n return default\n return bool(first) or _any(it)\n\ndef try_and_builtin(iterable, *, default=False):\n try:\n it = iter(iterable)\n return bool(next(it)) or _any(it)\n except StopIteration:\n return default\n\ndef for_and_builtin(iterable, *, default=False):\n it = iter(iterable)\n for first in it:\n return bool(first) or _any(it)\n return default\n\ndef for_and_builtin2(iterable, *, default=False):\n it = iter(iterable)\n for first in it:\n return True if first else _any(it)\n return default\n\nfuncs = original, loop_bool, loop_sentinel, default_and_builtin, try_and_builtin, for_and_builtin, for_and_builtin2\n\nnum = 2 * 10**6\ntests = [\n ('[]', num),\n ('[False]', num),\n ('[True]', num),\n ('[False, False]', num),\n ('[False, True]', num),\n ('[False] * 10**1', num // 10**0),\n ('[False] * 10**2', num // 10**1),\n ('[False] * 10**3', num // 10**2),\n ('[False] * 10**6', num // 10**5),\n ]\n\nfor iterable, number in tests:\n print('iterable =', iterable, f' {number = :,}')\n iterable = eval(iterable)\n times = [[] for _ in funcs]\n for _ in range(3):\n for func, ts in zip(funcs, times):\n t = min(repeat(partial(func, iterable, default=True), number=number))\n ts.append(t)\n for func, ts in zip(funcs, times):\n print(*('%.2f' % t for t in ts), func.__name__, sep=' ')\n print()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T20:23:11.097",
"Id": "250053",
"ParentId": "250036",
"Score": "7"
}
},
{
"body": "<p>NOTE: Since you provided more information about your actual problem, this answer will be very different to the already existing answers. Their pieces of advice are still valid : you really shouldn't break <code>any()</code>.</p>\n<h1>Your actual problem</h1>\n<blockquote>\n<p>However, this will execute the query an load all records into RAM, which I want to avoid</p>\n</blockquote>\n<p>As mentioned in this <a href=\"https://stackoverflow.com/a/31715766/6419007\">answer</a>, you could simply call Peewee's <a href=\"http://docs.peewee-orm.com/en/latest/peewee/api.html?highlight=exists#SelectBase.exists\" rel=\"nofollow noreferrer\"><code>query.exists()</code></a> to know if there's at least one record returned by this query.</p>\n<p>The <a href=\"https://github.com/coleifer/peewee/blob/master/peewee.py#L2178\" rel=\"nofollow noreferrer\">source code</a> makes it clear it retrieves at most 1 record from the DB, and only returns a boolean:</p>\n<pre><code>@database_required\ndef exists(self, database):\n clone = self.columns(SQL('1'))\n clone._limit = 1\n clone._offset = None\n return bool(clone.scalar())\n</code></pre>\n<p>I tried a small example on my laptop:</p>\n<pre><code>query = Movie.select().where((Movie.year > 1950) & (Movie.year < 1960))\nquery.exists()\n</code></pre>\n<p>Here's the corresponding Postgres log (please notice <code>LIMIT 1</code>):</p>\n<blockquote>\n<p>SELECT 1 FROM "movies" AS "t1" WHERE (("t1"."year" > 1950) AND ("t1"."year" < 1960)) LIMIT 1</p>\n</blockquote>\n<p>Asking for the number of corresponding records with <code>query.count()</code> also doesn't retrieve every row:</p>\n<blockquote>\n<p>SELECT COUNT(1) FROM (SELECT 1 FROM "movies" AS "t1" WHERE (("t1"."year" > 1950) AND ("t1"."year" < 1960))) AS "_wrapped"</p>\n</blockquote>\n<p>Only when I iterate over every row does peewee send a complete query:</p>\n<pre><code>for movie in query:\n print(movie.title)\n</code></pre>\n<blockquote>\n<p>SELECT "t1"."id", "t1"."title", "t1"."imdb_id", "t1"."year", "t1"."seen", "t1"."rating" FROM "movies" AS "t1" WHERE (("t1"."year" > 1950) AND ("t1"."year" < 1960))</p>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T13:48:47.993",
"Id": "250075",
"ParentId": "250036",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "250040",
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T13:04:57.093",
"Id": "250036",
"Score": "8",
"Tags": [
"python",
"python-3.x",
"database"
],
"Title": "Generalization of any() function with switchable default parameter for empty iterables"
}
|
250036
|
<p>I stumbled upon this <a href="https://www.codewars.com/kata/5b2f3cf991c74687ab000082" rel="nofollow noreferrer">kata</a>; the aim is to count how many epoqs it takes for n forward-counters and m backward-counters to all be equal.</p>
<blockquote>
<p>In the beginning, all the planets start with 0.</p>
<p>There are two types of planets: forward-counting planets, and
backward-counting planets. Every second, the display number on each
forward-counting planet will increase by one, and the display number
for each backward-counting planet will decrease by one.</p>
<p>Each planet has it's own special number, let's call it the planet's x,
for now. It is the highest number that the planet can display. The
lowest is 0.</p>
<p>Instead of becoming negative, the display number for a
backward-counting planet would wrap to it's x.</p>
<p>Instead of becoming greater than x, the display number for a
forward-counting planet would wrap back to 0.</p>
</blockquote>
<p>This code works and seem 'clean' but times out when the amount of counters gets too large. How can I optimize this code?</p>
<pre><code>class Counter:
def __init__(self, name):
self.name = name
self.modulo = name + 1
class ForwardCounter(Counter):
def __init__(self, name):
super().__init__(name)
def count(self, epoq):
return (self.name + epoq) % self.modulo
class BackwardCounter(Counter):
def __init__(self, name):
super().__init__(name)
def count(self, epoq):
return (self.name - epoq) % self.modulo
def unifier(retrograde,prograde):
counters = [BackwardCounter(x) for x in retrograde]
counters += [ForwardCounter(x) for x in prograde]
epoq = 1
while True:
first = counter[0].count(epoq)
if all(first == rest.count(epoq) for rest in counter[1:]):
break
epoq += 1
return epoq
</code></pre>
<p>Tests:</p>
<pre><code>test.assert_equals(unifier([25,8], [24,7]), 1402)
test.assert_equals(unifier([1,2,3,4], [6,7,8,9,10]), 27720)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T16:41:18.433",
"Id": "490423",
"Score": "5",
"body": "Thou shalt not bruteforce. Study the underlying math; it is not that complicated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T08:50:04.603",
"Id": "490703",
"Score": "1",
"body": "I still haven't found the algorithm. On the plus side, I studied modular arithmetic. ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T10:33:45.337",
"Id": "490712",
"Score": "1",
"body": "Your code as posted doesn't work. `NameError: name 'counter' is not defined`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T10:44:42.017",
"Id": "490713",
"Score": "1",
"body": "Your code doesn't pass the kata's test case - `unifier([6,9], [2,4,7])` doesn't output anything when it's meant to output 840."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T15:47:05.997",
"Id": "490725",
"Score": "0",
"body": "Did you really have to close the question? I guess I'll reopen, thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T16:43:35.103",
"Id": "490732",
"Score": "0",
"body": "To reopen the question you can [edit] your code to fix these issues. This will notify users that your question has been fixed and we can undo the past 6 hours."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T15:58:48.140",
"Id": "250041",
"Score": "1",
"Tags": [
"python"
],
"Title": "Planetary Alignment"
}
|
250041
|
<p>Folks,</p>
<p>I have a big question about how .NET dependency injection "native/default" works on a <code>Service Worker</code> scope.</p>
<p>We need to resolve a service(<code>Scoped:IMyRepository</code>) on constructor of an <code>MediatR</code> Handler, but we have an error at runtime, please see:</p>
<p>PS: I create a <a href="https://github.com/igorgomeslima/DependencyInjection.WorkerService.X.WebApi" rel="nofollow noreferrer">little repo on GitHub</a> with the solution described on this question.</p>
<p><strong>[Shared.csproj]</strong></p>
<p><em>Repository Folder</em></p>
<pre><code>using System;
namespace Shared.Repository
{
public interface IMyRepository
{
void Add();
}
public class MyRepository : IMyRepository
{
public void Add()
{
throw new NotImplementedException();
}
}
}
</code></pre>
<p><em>MediatR Folder</em></p>
<pre><code>using MediatR;
using System.Threading;
using Shared.Repository;
using System.Threading.Tasks;
namespace Shared.MediatR
{
public class PingQuery : IRequest<string> { }
public class PingQueryHandler : IRequestHandler<PingQuery, string>
{
readonly IMyRepository _myRepository;
public PingQueryHandler(IMyRepository myRepository)
{
_myRepository = myRepository;
}
public Task<string> Handle(PingQuery request, CancellationToken cancellationToken)
{
return Task.FromResult("Pong");
}
}
}
</code></pre>
<p><strong>[WorkerService.csproj]</strong></p>
<p><em>WorkerService.cs</em></p>
<pre><code>using MediatR;
using Shared.MediatR;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace WorkerService
{
public class Worker : BackgroundService
{
readonly IMediator _mediator;
readonly ILogger<Worker> _logger;
public Worker(ILogger<Worker> logger, IMediator mediator)
{
_logger = logger;
_mediator = mediator;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
var result = await _mediator.Send(new PingQuery());
_logger.LogInformation("MediatR result: {result}", result);
await Task.Delay(1000, stoppingToken);
}
}
}
}
</code></pre>
<p><em>Program.cs</em></p>
<pre><code>using MediatR;
using Shared.MediatR;
using Shared.Repository;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace WorkerService
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddMediatR(typeof(PingQuery));
services.AddScoped<IMyRepository, MyRepository>();
services.AddHostedService<Worker>(); <- Singleton Resolution
});
}
}
</code></pre>
<p>With this configuration, we got the following error:</p>
<blockquote>
<p>[Exception Unhandled]
System.InvalidOperationException: 'Error constructing handler for request of type
MediatR.IRequestHandler`2[Shared.MediatR.PingQuery,System.String]. Register your handlers with the
container. See the samples in GitHub for examples.'</p>
</blockquote>
<blockquote>
<p>[Inner Exception]
InvalidOperationException: Cannot resolve
'MediatR.IRequestHandler`2[Shared.MediatR.PingQuery,System.String]' from root provider because it
requires scoped service 'Shared.Repository.IMyRepository'.</p>
</blockquote>
<p><a href="https://i.stack.imgur.com/1JPMT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1JPMT.png" alt="Worker ServiceCollection" /></a></p>
<p>And now comes the other part of the question. If we make this same "configuration" on a Web Application project, the D.I can solve (Scoped:<code>IMyRepository</code>).</p>
<p>Like:</p>
<p><strong>[WebApi.csproj]</strong></p>
<p><em>Program.cs</em> (I decided resolve the dependencies(<code>MediatR</code>, <code>IMyRepository</code>) in this class, just to give a closer look to the "Worker Service" D.I resolution)</p>
<pre><code>using MediatR;
using Shared.MediatR;
using Shared.Repository;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace WebApi
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddMediatR(typeof(PingQuery));
services.AddScoped<IMyRepository, MyRepository>();
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
</code></pre>
<p><em>Startup.cs</em></p>
<pre><code>using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace WebApi
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
/*Omitted for brevity*/
}
}
}
</code></pre>
<p><a href="https://i.stack.imgur.com/5pooo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5pooo.png" alt="Web Application ServiceCollection" /></a></p>
<p><em>WeatherForecastController.cs</em></p>
<pre><code>using MediatR;
using Shared.MediatR;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApi.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
readonly IMediator _mediator;
public WeatherForecastController(IMediator mediator)
{
_mediator = mediator;
}
[HttpGet]
public async Task<string> Get()
{
return await _mediator.Send(new PingQuery());
}
}
}
</code></pre>
<p>When we call the <code>HttpGet</code> of the <code>Controller</code> above, the D.I has been resolved on <code>PingQueryHandler</code>:</p>
<p><a href="https://i.stack.imgur.com/odJLx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/odJLx.png" alt="PingQueryHandler D.I solved" /></a></p>
<p>Why? I looked for similar cases, and most likely it involves the way the <code>Worker Service</code> solves the D.I (without creating scope), as mentioned <a href="https://docs.microsoft.com/pt-br/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-3.1&tabs=visual-studio#consuming-a-scoped-service-in-a-background-task" rel="nofollow noreferrer">here</a>, and Jimmy Bogard(MediatR) mentions that MediatR needs the dependencies resolved in a scope <a href="https://github.com/jbogard/MediatR/issues/240#issuecomment-370062681" rel="nofollow noreferrer">here</a>.</p>
<p>Is there a way to resolve this? Does anyone know the reason for the difference in dependecy injection between project types?</p>
<p>The solution would be to inject <code>IServiceScopeFactory</code> to solve my dependency, like mentioned on this <a href="https://stackoverflow.com/a/57123359/2145555">S.O answer</a>? I don't know if this applies to a <code>Service Worker</code> too...</p>
<p>I'm a little confused now, and I would like to understand how things work, any help is welcome :)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T14:38:38.050",
"Id": "502338",
"Score": "1",
"body": "Ahoy! Unfortunately this question is _off-topic_ because this site is for reviewing **working** code that the poster understands fully. Please [take the tour](https://codereview.stackexchange.com/tour) and read up at our [help center](https://codereview.stackexchange.com/help/on-topic). When the code works and is understood by you then feel free to [edit] the post to include it for a review."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T16:27:03.257",
"Id": "250043",
"Score": "1",
"Tags": [
"dependency-injection",
"asp.net-web-api",
".net-core",
"mediator"
],
"Title": ".NET Core Dependency Injection - Worker Service x Web Api"
}
|
250043
|
<p>I have a component that shows the status of a customer's billing plan. There are about seven different states it can be in, with about six props each (I've simplified it down to two for this example). I'm trying to create an enum that I can get the props from, to be used like this:</p>
<pre><code><PlanCard {...PlanCardProps.TrialPlan} />
</code></pre>
<p>But I'm trying to give it proper typing. The names just feel wonky here though. I hate using "type" as part of the name of a type, but given that the enum is called PlanCardProps, I just didn't know what to call the typing for the object literal and for its values.</p>
<p>Is there a better way of naming this?</p>
<pre><code>export type PlanCardPropsType = {
header: string;
ctaText: string;
};
type PlanCardPropsEnum = {
[key: string]: PlanCardPropsType;
};
export const PlanCardProps: PlanCardPropsEnum = {
TrialPlan: {
header: 'x',
ctaText: 'click here'
},
NoPlan: {
header: 'y',
ctaText: 'cancel'
}
};
</code></pre>
|
[] |
[
{
"body": "<p>Given that:</p>\n<ul>\n<li><code>PlanCardPropsEnum</code> is only referenced once, in the type definition of <code>PlanCardProps</code></li>\n<li><code>PlanCardPropsEnum</code> is not exported</li>\n<li>The exported object is absolutely constant (right?)</li>\n<li>The exported object is <em>not</em> props, but a <em>container</em> for different possible props</li>\n</ul>\n<p>I would refactor it to:</p>\n<ul>\n<li>Rename the exported object to UPPER_SNAKE_CASE, which is acceptable for absolute constants/enums. Maybe call it <code>AVAILABLE_PLAN_CARD_PROPS</code>, since it's not props itself, but a container around multiple props. Or you could call it <code>ALL_PLAN_CARD_PROPS</code>.</li>\n<li>Remove <code>PlanCardPropsEnum</code> completely. TypeScript can <em>already</em> automatically infer the type of the object to have values of <code>{ header: string; ctaText: string; };</code>, <em>and</em> you probably shouldn't type as <code>[key: string]</code> because you only have "around six props each" - you'd want only those particular props to be referenceable on the object, and for any other property accesses to throw a TS error.</li>\n<li>Then, <code>PlanCardPropsType</code> can be renamed to <code>PlanCardProps</code>:</li>\n</ul>\n<pre><code>export type PlanCardProps = {\n header: string;\n ctaText: string;\n};\n\n// This could also be called AvailablePlanCardProps\n// now that its name doesn't collide with another's\nexport const AVAILABLE_PLAN_CARD_PROPS = {\n TrialPlan: {\n header: 'x',\n ctaText: 'click here'\n },\n NoPlan: {\n header: 'y',\n ctaText: 'cancel'\n }\n};\n</code></pre>\n<p>It can often be good to avoid explicit typing - better to let TS automatically infer types. This cuts down on code that needs to be read.</p>\n<p>It's unfortunate that <code>props</code> is plural; if it were singular, it would be easier to come up with a good name to distinguish the collection from the individual.</p>\n<p>Note that "enum" is a keyword with a <a href=\"https://www.typescriptlang.org/docs/handbook/enums.html\" rel=\"nofollow noreferrer\">specific meaning</a> in TS. Probably best only to refer to actual TS enums as "enum", else you may confuse people.</p>\n<p>If you're worried about possibly making a typo and, for example, mis-typing <code>headrr</code> instead of <code>header</code>, you could define the object first (so that all the keys get included in the type, without repetition), then assign the object to another variable whose type is a Record of those keys and the <code>PlanCardProps</code>:</p>\n<pre><code>export type PlanCardProps = {\n header: string;\n ctaText: string;\n};\n\n// Ensure that the values of the exported object match PlanCardProps:\ntype Keys = keyof typeof AVAILABLE_PLAN_CARD_PROPS_INITIAL;\nexport const AVAILABLE_PLAN_CARD_PROPS: Record<Keys, PlanCardProps> = AVAILABLE_PLAN_CARD_PROPS_INITIAL;\n</code></pre>\n<p>This will throw a TS error if you make a typo.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T18:57:53.767",
"Id": "250050",
"ParentId": "250044",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T16:41:26.613",
"Id": "250044",
"Score": "2",
"Tags": [
"typescript"
],
"Title": "How would I name these types in a way that's accurate and not redundant?"
}
|
250044
|
<p>I am grouping lists within list together given they have one element in common.</p>
<p>My input data is</p>
<pre><code>[[1, 2], [3, 4], [5, 6], [1, 2, 7], [8, 2], [9, 5]]
</code></pre>
<p>My output is:</p>
<pre><code>[[1, 2], [1, 2, 7], [8, 2], [3, 4], [5, 6], [9, 5]]
</code></pre>
<p>The code I am using to accomplish this is:</p>
<pre><code>mylist = [[1, 2], [3, 4], [5, 6], [1, 2, 7], [8, 2], [9, 5]]
temp_result = list()
for i in range(len(mylist)):
temp_result.append(mylist[i])
for j in range(i + 1, len(mylist)):
if (set(mylist[i]) & set(mylist[j])):
temp_result.append(mylist[j])
result = []
for elem in temp_result:
if elem not in result:
result.append(elem)
print(result)
</code></pre>
<p>However, something tells me that this code can be improved a lot. Can someone please help me out?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T19:28:29.970",
"Id": "490434",
"Score": "1",
"body": "Looks more like sorting rather then grouping"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T21:19:43.567",
"Id": "490445",
"Score": "0",
"body": "@OlvinRoght yes you are right. Let me rename."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T21:37:41.963",
"Id": "490446",
"Score": "0",
"body": "What is the expected output of `[1,3], [3,2], [1,2]`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T21:46:56.520",
"Id": "490449",
"Score": "0",
"body": "The output of `[[1, 3], [3, 2], [1, 2]]` is same."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T02:21:42.370",
"Id": "490463",
"Score": "0",
"body": "should it not be `[[1, 2], [1, 3], [3, 2]]` since it is _technically_ sort?"
}
] |
[
{
"body": "<p>Here's one way to approach the problem. There is a rule, or predicate, that determines whether list items should be grouped together. Use the predicate to partition the list into two parts, those that pass the predicate and those that fail. The ones that pass become grouped together in the result. The ones that fail get processed with a new predicate to see if any of them should be grouped. Repeat until there aren't any items left.</p>\n<p>The code below matches the output of the code in the question. The predicate is true for any item that has an element in common with the first item in the sequence (the intersection is not empty).</p>\n<p>The code is written to be understandable, not to be clever or concise.</p>\n<pre><code>def partition(predicate, sequence):\n """Return a list of sequence items that pass the predicate and a list\n of sequence items that do not pass the predicate.\n """\n pass_predicate = []\n fail_predicate = []\n\n for item in sequence:\n if predicate(item):\n pass_predicate.append(item)\n else:\n fail_predicate.append(item)\n\n return pass_predicate, fail_predicate\n\n\ndef group(sequence):\n """Groups items in the sequence that have elements in common.\n """\n result = []\n \n while sequence:\n predicate = set(sequence[0]).intersection\n\n passed, failed = partition(predicate, sequence)\n\n result.extend(passed)\n sequence = failed\n \n return result\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-04T01:42:31.023",
"Id": "490770",
"Score": "1",
"body": "This keeps `[[1, 2], [2, 3], [999], [3]]` as is, without moving `[3]` next to `[2, 3]`. I think it should."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-04T02:19:43.350",
"Id": "490771",
"Score": "0",
"body": "@superbrain, yeah the problem isn't well specified. As a counter example to yours, for input `[[1, 2], [3, 4], [5, 6], [1, 2, 7], [8, 2], [9, 5], [7, 10]]` the original code keeps the `[7, 10]` at the end instead of grouping it with the `[1, 2, 7]`. Is it supposed to look for common elements with the union of all items in the group? or just with the first item in the group? You think the former, I thought the later, and the original code does neither."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T23:07:22.960",
"Id": "250165",
"ParentId": "250048",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "250165",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T17:39:32.857",
"Id": "250048",
"Score": "-1",
"Tags": [
"python",
"python-3.x"
],
"Title": "sorting lists within list together given they have at least one common element"
}
|
250048
|
<p>This is a Google foobar question. The gist of it is that I have to find the shortest path from top left to bottom right in a 2d array of 1's and 0's, where I can only traverse on 0's. However, the twist is that I can change one 1 to a 0. My code works for the first three test cases, but it fails the final two (not sure if it's an edge case or it's pure inefficiency).</p>
<p>My current solution is to test every possible array (switch every possible 1 to a 0) and then run BFS on each one.</p>
<p>How can I optimize my code further? Thanks! If you want, here's the <a href="https://codereview.stackexchange.com/questions/153242/shortest-path-for-google-foobar-prepare-the-bunnies-escape">full text</a> of the problem.</p>
<pre><code>import java.lang.Integer;
import java.lang.String;
import java.util.Arrays;
import java.lang.Math;
import java.util.LinkedList;
import java.util.Queue;
public class Solution {
public static void main (String[] args)
{
int[][]x = {{0, 1, 1, 0}, {0, 0, 0, 1}, {1, 1, 0, 0}, {1, 1, 1, 0}};
System.out.println(solution(x));
}
public static int solution(int[][] map) {
int w = map[0].length;
int h = map.length;
if(w==1&h==1)
return 1;
int[][] m = map;
int min = minPath(m,w,h);
//System.out.println(min);
for (int i = 0; i<w; i++)
{
for (int j = 0; j<h;j++)
{
if(m[j][i]==1)
{
m[j][i] = 0;
min = Math.min(min, minPath(m,w,h));
if(min==w+h-1)
return min;
m[j][i] = 1;
}
}
}
return min;
}
public static int minPath(int[][]m, int w, int h)
{
int[][] d = new int[h][w];
d[0][0] = 1;
Queue<String> q = new LinkedList<>();
q.add(0 + "," + 0);
while(!q.isEmpty())
{
String x = q.remove();
int i = Integer.parseInt(x.split(",")[0]);
int j = Integer.parseInt(x.split(",")[1]);
if (i==h-2&&j==w-1 || i==h-1&&j==w-2)
return ++d[i][j];
if(i>1&&d[i-1][j]==0&&m[i-1][j]==0)
{
d[i-1][j] = d[i][j] + 1;
q.add(i-1+","+j);
}
if(j>1&&d[i][j-1]==0&&m[i][j-1]==0)
{
d[i][j-1] = d[i][j] + 1;
q.add(i+","+(j-1));
}
if(i<h-1&&d[i+1][j]==0&&m[i+1][j]==0)
{
d[i+1][j] = d[i][j] + 1;
q.add(i+1+","+j);
}
if(j<w-1&&d[i][j+1]==0&&m[i][j+1]==0)
{
d[i][j+1] = d[i][j] + 1;
q.add(i+","+(j+1));
}
}
return 1600;
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T23:28:07.703",
"Id": "250060",
"Score": "2",
"Tags": [
"java"
],
"Title": "How can I optimize this Java 2D Array BFS?"
}
|
250060
|
<p>I was trying to solve <a href="http://www.usaco.org/index.php?page=viewproblem2&cpid=988" rel="nofollow noreferrer">this</a> problem with Python 3.8. I couldn't find a way other than to brute-force calculate all the possible permutations then check which permutation was valid. The program works fine, but as it's <code>O(n!)</code> time complexity (I think) it takes extraordinarily long when the input has a length of, say, 1000.</p>
<p>My code:</p>
<pre><code>from itertools import permutations as permute
fin = open("photo.in", "r")
fout = open("photo.out", "w+")
useless, line = fin.readlines()
nums = [int(i) for i in line.split(" ")]
def main(nums):
foo = [i+1 for i in range(len(nums)+1)]
bar = permute(foo)
for permutation in bar:
boo = False
for i in range(1, len(permutation)):
if permutation[i]+permutation[i-1] != nums[i-1]:
boo = False
break
else:
boo = True
if boo:
return permutation
final = " ".join([str(i) for i in main(nums)])
fout.write(final)
fin.close()
fout.close()
</code></pre>
<p>I'm not sure how to optimize this code. Should I create my own permutation generator function and then check along the way instead of getting the whole thing at once? Or is there an algorithm that I'm not seeing?</p>
<p>A short problem description:
Given a list <em>N</em> of length <em>n</em> integers, find a permutation of the numbers 1 through <em>n</em>+1 in which every element of the permutation plus the next one is equal to the corresponding number of <em>N</em>.</p>
<p>Edit: The generator approach did not work.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T00:19:24.197",
"Id": "490460",
"Score": "4",
"body": "_Or is there an algorithm that I'm not seeing?_ - Yes there is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T00:20:33.967",
"Id": "490461",
"Score": "0",
"body": "@vnp Can you give me a hint as to what I'm missing?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T02:30:29.440",
"Id": "490464",
"Score": "3",
"body": "you have \\$ n \\$ equations and \\$ n \\$ variables (the last equation being \\$ a_1 + a_2 + \\cdots = \\dfrac{n (n+1)}{2} \\$)."
}
] |
[
{
"body": "<p><strong>No need to compute permutations</strong></p>\n<p>As you are provided all the <code>b1,b2,…,bN−1</code> values, the problem boils down to finding the first value <code>a1</code> and everything can be computed from there. In particular, you have only <code>N</code> different values to try. We can try see them like this:</p>\n<pre><code>n = 5\nb_array = [4, 6, 7, 6]\nfor a in range(1, n+1):\n a_array = [a]\n for b in b_array:\n a = b - a\n a_array.append(a)\n print(a_array)\n</code></pre>\n<p>which gives</p>\n<pre><code>[1, 3, 3, 4, 2] # Duplicate 3\n[2, 2, 4, 3, 3] # Duplicate 2\n[3, 1, 5, 2, 4] # Looks good\n[4, 0, 6, 1, 5] # 6 is out of range\n[5, -1, 7, 0, 6] # -1, 7, 6, 0 are out of range\n</code></pre>\n<p>Because we go with increasing values of <code>a1</code>, the first candidate that does match is the expected solution (the "lexicographically minimum").</p>\n<p>Thus, you could just try to get rid of the impossible solution and you'll find the correct one:</p>\n<pre><code>def get_solution(n, b_array):\n for a in range(1, n+1):\n a_array = [a]\n for b in b_array:\n a = b -a\n if 0 < a <= n and a not in a_array: # To be performed with a set for O(1) check\n a_array.append(a)\n else:\n break\n else: # No break\n return a_array\n\nn = 5\nb_array = [4, 6, 7, 6]\nprint(get_solution(n, b_array))\n</code></pre>\n<p>This solution is O(n*n): n attempts (or maybe n/2 on average) which iterate over n elements (or maybe n/2 on average).</p>\n<p>It would be nice to find an O(n) solution (which is the best expectable solution).</p>\n<p><strong>Mathematical observations</strong></p>\n<p>We have: <code>bi = ai + ai+1</code> which means <code>ai+1 = bi - ai</code> which is the property we've used previously.\nFrom there, we can also compute: <code>ai+2 = bi+1 - ai+1 = bi+1 - bi + ai</code>.\nIt doesn't look very interesting at first but it means that when if you try to increase/decrease <code>ai</code> from a fixed value, the value <code>ai+2</code> will vary accordingly (and so will the value of <code>ai+4</code>, <code>ai+6</code>, etc).</p>\n<p>This can be observed in the options we generated previously:</p>\n<pre><code>[1, 3, 3, 4, 2] # Duplicate 3\n[2, 2, 4, 3, 3] # Duplicate 2\n[3, 1, 5, 2, 4] # Looks good\n[4, 0, 6, 1, 5] # 6 is out of range\n[5, -1, 7, 0, 6] # -1, 7, 6, 0 are out of range\n ^______^_________always +2 from column 1 to 3\n ^____________^___always +1 from column 1 to 5\n ^_____^______always +1 from column 2 to 4\n\n</code></pre>\n<p>Note: this property hold when we take every other column but not when we take 2 consecutives values because <code>ai+2 - ai = bi+1 - bi</code> is a fixed value (which is convenient) while <code>ai+1 - a1 = bi - 2*ai</code> depends on the value of <code>ai</code>.</p>\n<p>How could this help us ?</p>\n<p>Well, in your case, we can see that a3 = a1 + 2 which tells us straightaway that a1 can't be 4 or above. With a bigger list, this would provide us a smaller range to check for <code>a1</code> (both from the starting limit and the ending limit).</p>\n<p>Similarly, we can get stronger constraints on <code>a2</code>.</p>\n<hr />\n<p><strong>My final version of the code</strong></p>\n<p>In case it can be useful, here is my implementation. It doesn't use all the excellent ideas from hjpotter92's answers:</p>\n<pre><code># https://codereview.stackexchange.com/questions/250061/efficient-permutation-checking-for-usaco-photoshoot-python\n# http://www.usaco.org/index.php?page=viewproblem2&cpid=988\nimport random\n\ndef generate_b_array(a_array):\n """Generate 'b' array from the 'a' array."""\n return [previous + current for previous, current in zip(a_array, a_array[1:])]\n\n\ndef generate_problem(n):\n """Generate a problem of size n."""\n # TODO: It is a bit trickier than this, we may generate solutions which\n # are not the lexicographical minimum:\n # For instance, both [4, 3, 2, 1] and [3, 4, 1, 2] lead to b being [7, 5, 3]\n # But only the second one is an acceptable solution\n # This issue gets less and less common as n increases.\n a = list(range(1, n+1))\n random.shuffle(a)\n return a, generate_b_array(a)\n\n\ndef get_solution_naive(b_array):\n """This is the most straight-forward solution: generate and check."""\n n = len(b_array) + 1\n expected_set = set(range(1, n+1))\n for a in range(1, n+1):\n a_array = [a]\n for b in b_array:\n a = b -a\n a_array.append(a)\n if set(a_array) == expected_set:\n return a_array\n\n\ndef get_solution_naive_early_stop(b_array):\n """Smarter (?) solution: trying to stop when generated data is not valid."""\n n = len(b_array) + 1\n for a in range(1, n+1):\n a_array = [a]\n for b in b_array:\n a = b -a\n if 0 < a <= n and a not in a_array:\n a_array.append(a)\n else:\n break\n else: # No break\n return a_array\n\n\ndef get_solution_naive_early_stop_set(b_array):\n """Smarter (?) solution: trying to stop when generated data is not valid, using the most appropriate data structure."""\n n = len(b_array) + 1\n for a in range(1, n+1):\n a_array = [a]\n a_set = set(a_array)\n for b in b_array:\n a = b -a\n if 0 < a <= n and a not in a_set:\n a_array.append(a)\n a_set.add(a)\n else:\n break\n else: # No break\n return a_array\n\n\ndef get_solution(b_array):\n """Optimised solution: rely on mathematical observation to limit the number of values checked."""\n n = len(b_array) + 1\n\n # Use properties on alternate indices to restrict values to look for for a1\n b_diff = [current - previous for previous, current in zip(b_array, b_array[1:])]\n\n delta_from_a1 = [0]\n for delta in b_diff[::2]:\n delta_from_a1.append(delta + delta_from_a1[-1])\n min_delta_a1, max_delta_a1 = min(delta_from_a1), max(delta_from_a1)\n delta_from_a2 = [0]\n for delta in b_diff[1::2]:\n delta_from_a2.append(delta + delta_from_a2[-1])\n min_delta_a2, max_delta_a2 = min(delta_from_a2), max(delta_from_a2)\n\n # We want: 0 < a_n <= N for all n\n # With a_n = a_1 + delta_n, we want: -delta_n < a_1 <= N - delta_n for all n\n # In particular:\n # -min(delta) < a_1 <= N - max(delta)\n a1_min1 = 1 - min_delta_a1\n a1_max1 = n - max_delta_a1\n\n # We want: 0 < a_n <= N for all n\n # With a_n = a_2 + delta_n and a2 = b1 - a1, we want:\n # 0 < b_1 - a_1 + delta_n <= N for all n\n # - delta_n - b_1 < - a_1 <= N - delta_n - b_1\n # delta_n + b_1 > a_1 >= delta_n + b_1 - N\n # In particular :\n # max(delta) + b-1 - N <= a_1 < min(delta) + b_1 \n a1_min2 = max_delta_a2 + b_array[0] - n\n a1_max2 = min_delta_a2 + b_array[0] - 1\n\n a1_min = max(1, a1_min1, a1_min2)\n a1_max = min(n, a1_max1, a1_max2)\n # print("min", a1_min, 1, a1_min1, a1_min2)\n # print("max", a1_max, n, a1_max1, a1_max2)\n\n expected_set = set(range(1, n+1))\n for a in range(a1_min, a1_max+1):\n a_array = [a]\n for b in b_array:\n a = b -a\n a_array.append(a)\n if set(a_array) == expected_set:\n return a_array\n\n\n\ndef check_solution(a, b):\n """Test all implementations on a given problem."""\n # TODO: Some performance benchmarking could be added here.\n a1 = get_solution_naive(b)\n a2 = get_solution_naive_early_stop(b)\n a3 = get_solution_naive_early_stop_set(b)\n a4 = get_solution(b)\n if a1 != a:\n print("a1", a, a1, b)\n if a2 != a:\n print("a2", a, a2, b)\n if a3 != a:\n print("a3", a, a3, b)\n if a4 != a:\n print("a4", a, a3, b)\n\n\ndef perform_tests():\n """Perform tests (hardcoded & randomly generated)."""\n a, b = [3, 1, 5, 2, 4], [4, 6, 7, 6]\n check_solution(a, b)\n\n a, b = [6, 3, 10, 4, 2, 1, 8, 7, 5, 9], [9, 13, 14, 6, 3, 9, 15, 12, 14]\n check_solution(a, b)\n\n a, b = [12, 5, 9, 6, 14, 10, 15, 13, 2, 7, 1, 8, 19, 11, 16, 20, 4, 18, 17, 3], [17, 14, 15, 20, 24, 25, 28, 15, 9, 8, 9, 27, 30, 27, 36, 24, 22, 35, 20]\n check_solution(a, b)\n\n # This case leads to more iterations than most other cases\n a = [137, 187, 70, 179, 198, 106, 156, 10, 144, 105, 196, 171, 89, 164, 186, 41, 165, 55, 114, 138, 101, 8, 75, 185, 174, 81, 158, 126, 181, 30, 178, 85, 180, 76, 28, 56, 62, 119, 193, 45, 94, 109, 172, 169, 149, 79, 189, 100, 125, 131, 57, 32, 139, 14, 27, 152, 47, 15, 147, 95, 39, 112, 118, 151, 38, 26, 175, 11, 200, 1, 161, 120, 63, 115, 12, 60, 129, 80, 7, 33, 192, 166, 123, 13, 23, 84, 116, 6, 163, 16, 52, 5, 18, 71, 154, 78, 69, 3, 49, 121, 199, 159, 72, 86, 36, 54, 92, 97, 35, 34, 150, 173, 168, 130, 190, 141, 99, 17, 87, 134, 20, 155, 111, 153, 170, 102, 31, 135, 9, 194, 50, 4, 128, 140, 143, 184, 40, 110, 191, 98, 44, 195, 58, 24, 65, 74, 64, 22, 197, 188, 113, 142, 136, 107, 103, 83, 19, 145, 53, 68, 167, 59, 177, 21, 182, 2, 122, 176, 117, 51, 48, 67, 183, 61, 82, 42, 124, 37, 93, 162, 73, 148, 127, 66, 146, 29, 91, 108, 160, 157, 104, 25, 132, 43, 96, 88, 46, 77, 133, 90]\n b = [324, 257, 249, 377, 304, 262, 166, 154, 249, 301, 367, 260, 253, 350, 227, 206, 220, 169, 252, 239, 109, 83, 260, 359, 255, 239, 284, 307, 211, 208, 263, 265, 256, 104, 84, 118, 181, 312, 238, 139, 203, 281, 341, 318, 228, 268, 289, 225, 256, 188, 89, 171, 153, 41, 179, 199, 62, 162, 242, 134, 151, 230, 269, 189, 64, 201, 186, 211, 201, 162, 281, 183, 178, 127, 72, 189, 209, 87, 40, 225, 358, 289, 136, 36, 107, 200, 122, 169, 179, 68, 57, 23, 89, 225, 232, 147, 72, 52, 170, 320, 358, 231, 158, 122, 90, 146, 189, 132, 69, 184, 323, 341, 298, 320, 331, 240, 116, 104, 221, 154, 175, 266, 264, 323, 272, 133, 166, 144, 203, 244, 54, 132, 268, 283, 327, 224, 150, 301, 289, 142, 239, 253, 82, 89, 139, 138, 86, 219, 385, 301, 255, 278, 243, 210, 186, 102, 164, 198, 121, 235, 226, 236, 198, 203, 184, 124, 298, 293, 168, 99, 115, 250, 244, 143, 124, 166, 161, 130, 255, 235, 221, 275, 193, 212, 175, 120, 199, 268, 317, 261, 129, 157, 175, 139, 184, 134, 123, 210, 223]\n check_solution(a, b)\n\n lengths = [3, 4, 5, 10, 15, 20, 100, 200, 500]\n lengths = [10, 10, 10, 10, 10, 15, 15, 20, 100, 200, 500]\n for i in lengths:\n a, b = generate_problem(i)\n check_solution(a, b)\n\nperform_tests()\n\n</code></pre>\n<hr />\n<p>The code review itself</p>\n<p>Here are a few comments which could help you:</p>\n<ul>\n<li>write functions</li>\n<li>write tests for your functions: this is particularly easy here for 2 reasons:\n* you are provided a valid test case\n* new test cases are fairly easy to generate</li>\n</ul>\n<p>Writing functions will help you to write easier to maintain code. Also, for the algorithmic challenges, it will help you to focus on the algorithm itself instead of dealing with input/output. Also, it helps to test various implementations, to test them, to compare them (both in correctness and in performances)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T11:00:19.763",
"Id": "490489",
"Score": "1",
"body": "I'm not convinced your solution is O(n^2). It rather looks like O(n^3) to me. Or does `0 < a <= n and a not in a_array` average O(1) somehow?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T13:05:21.857",
"Id": "490496",
"Score": "0",
"body": "Oh, I meant to perform this with a set but forgot. I'll try to fix this, thanks for the comment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T14:34:20.190",
"Id": "490510",
"Score": "0",
"body": "We can also compute the sum of the first and last a-value, as every a-value gets into b twice, except those two. I don't see how to take advantage of it, though. And I suspect O(n) isn't possible or at least hard to achieve, since otherwise I'd expect a limit higher than 1000."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T16:24:09.357",
"Id": "490521",
"Score": "0",
"body": "Well, it turns out that I was thinking about this problem in the wrong way. Thank you so much bro!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T21:21:58.727",
"Id": "490679",
"Score": "0",
"body": "@superbrain The implementation I've provided is probably very close to O(n). The pre-computation ensures that the loop actually goes through a small number of iterations (almost always 1) but I can't prove it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T22:22:25.753",
"Id": "490683",
"Score": "0",
"body": "Your checks like `a1 != a` aren't right. I tried replacing your `random.shuffle(a)` with the non-random shuffle `a[1::2], a[::2] = a[:n//2], a[n//2:][::-1]` and then those checks failed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T09:09:02.700",
"Id": "490705",
"Score": "0",
"body": "Thanks for your comment, I'll give it a try!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T10:33:02.587",
"Id": "490711",
"Score": "0",
"body": "@superbrain After a check, it actually corresponds to the issue hilighted in the comment of the `generate_problem` function. I guess this could get fixed somehow but it was good enough for most usages."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T08:51:57.477",
"Id": "250067",
"ParentId": "250061",
"Score": "4"
}
},
{
"body": "<h2>Mathematical approach</h2>\n<p>Let us assume the following notation:</p>\n<p><span class=\"math-container\">$$ \\mathbb{B} = \\sum_{i = 1}^{n - 1} b_i = b_1 + b_2 + \\cdots + b_{n-1} $$</span></p>\n<p>As mentioned earlier in comments, you have set of interdependent equations as follows:</p>\n<p><span class=\"math-container\">$$\n\\begin{align}\nb_1 &= a_1 + a_2 \\\\\nb_2 &= a_2 + a_3 \\\\\nb_3 &= a_3 + a_4 \\\\\n\\vdots \\\\\nb_{n - 1} &= a_{n - 1} + a_n \\\\\n\\end{align}\n$$</span></p>\n<p>The above is <span class=\"math-container\">\\$ n - 1 \\$</span> sets of equations, and the last equation you can derive from those is:</p>\n<p><span class=\"math-container\">$$\n\\begin{align}\n\\sum_{i = 1}^{n - 1} b_i &= \\sum_{i = 1}^{n} a_i + \\sum_{j = 2}^{n - 1} a_j \\\\\n\\implies \\mathbb{B} + (a_1 + a_n) &= 2 \\times \\left( \\sum_{i = 1}^{n} a_i \n\\right) \\\\\n\\implies a_1 + a_n &= 2 \\times \\left( \\dfrac{n (n + 1)}{2} \\right) - \\mathbb{B} \\\\\n&= \\left( n \\cdot (n + 1) \\right) - \\mathbb{B} \\tag{1}\n\\end{align}\n$$</span></p>\n<hr />\n<p>Now, let's see what happens if we try the summation with a slight variation:</p>\n<p><span class=\"math-container\">$$\n\\begin{align}\n\\sum_{i = 1}^{n - 1} \\left[ (-1)^{i + 1} \\cdot b_i \\right] &= b_1 - b_2 + b_3 - \\cdots \\cdots (-1)^{n - 2} b_{n - 1} \\\\\n&= (a_1 + a_2) - (a_2 + a_3) + (a_3 + a_4) - \\cdots \\cdots + (-1)^n (a_{n - 1} + a_n) \\\\\n&= a_1 + (-1)^{n} a_n \\tag{2}\n\\end{align}\n$$</span></p>\n<p>Now, there would be 2 cases; 1 is fairly straight to solve:</p>\n<h3>Case 1: <span class=\"math-container\">\\$ n \\$</span> is odd</h3>\n<p>The equation 2 becomes: <span class=\"math-container\">$$ a_1 - a_n = \\sum_{i = 1}^{n - 1} \\left[ (-1)^{i + 1} \\cdot b_i \\right] $$</span></p>\n<p>giving you the direct result (adding equation to above):</p>\n<p><span class=\"math-container\">$$\na_1 = \\dfrac{1}{2} \\left( \\sum_{i = 1}^{n - 1} \\left[ (-1)^{i + 1} \\cdot b_i \\right] + n^2 + n - \\mathbb{B} \\right)\n$$</span></p>\n<h3>Case 2: <span class=\"math-container\">\\$ n \\$</span> is even</h3>\n<p>This gives you the same result as equation 1, therefore the replacement operation from <a href=\"https://codereview.stackexchange.com/a/250067/12240\">SylvainD's answer</a> comes into play. I'll leave this for the programming specific solution.</p>\n<hr />\n<h2>Program/code review</h2>\n<ol>\n<li><p>Use the names of variables which are closer to words used in problem statement. This makes it easier to go through code and question at the same time.</p>\n</li>\n<li><p>The <code>photo.in</code> serves no purpose once it has been read, use a contextual open for this:</p>\n<pre><code>with open("photo.in", "r") as file_in:\n num_cows = int(file_in.readline())\n summations = map(int, file_in.readline().split(" "))\n</code></pre>\n</li>\n<li><p>Same as above, the <code>photo.out</code> serves no purpose until you want to write:</p>\n<pre><code>with open("photo.out", "w+") as file_out:\n file_out.write(" ".join(output_string))\n</code></pre>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T16:21:35.640",
"Id": "490520",
"Score": "0",
"body": "oh man, thanks a ton for the file reading suggestion at the end bro! you rock!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T15:09:15.450",
"Id": "250082",
"ParentId": "250061",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "250082",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T23:43:48.987",
"Id": "250061",
"Score": "7",
"Tags": [
"python",
"combinatorics",
"complexity"
],
"Title": "Best Algorithm for solving USACO: Photoshoot - Python"
}
|
250061
|
<p>Is this script sufficient enough to validate user email input?</p>
<pre><code><?php
//1 DATABASE CONNECTION
$dbHost = "HOST";
$dbUser = "USER";
$dbPassword = "PASSWORD";
$dbName = "DATABASE";
try {
$dsn = "mysql:host=" . $dbHost . ";dbname=" . $dbName;
$pdo = new PDO($dsn, $dbUser, $dbPassword);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "DB Connection Failed: " . $e->getMessage();
exit(0);
}
//1 END
//2 ADD EMAIL TO DATABASE
//set date and time
date_default_timezone_set('America/Los_Angeles');
$timestamp = strtotime('NOW');
$dateTime = date('Ymd-His', $timestamp);
//variable to store ipv4 address
$userIP4 = gethostbyname($_SERVER['REMOTE_ADDR']);
//storing ip6 could be something like: "bin2hex(inet_pton($_SERVER['REMOTE_ADDR']));" but I couldn't figure out if the output was correct, because it looked nothing like an ipv6 address.....
if(filter_var($userIP4, FILTER_VALIDATE_IP)) {
//yes it's valid IPv4
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$email = htmlspecialchars($_POST['email']); //convert special characters to HTML entities (&,",<,>)
$Temail = trim($email); //trim spaces on ends
//allow international characters
if(preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^/", $Temail)) {
//prevents invalid email addresses
header("Location: invalid.html");
exit (0);
} else {
//Check Email Domain MX Record
$email_host = strtolower(substr(strrchr($Temail, "@"), 1));
if (!checkdnsrr($email_host, "MX")) {
header("Location: invalid.html");
exit (0);
} else {
//Prevent users from inputting a specific domain...
$notallowed = [
'mydomain.com',
];
$parts = explode('@', $Temail); //Separate string by @ characters (there should be only one)
$domain = array_pop($parts); //Remove and return the last part, which should be the domain
if ( ! in_array($domain, $notallowed)) {
//checks database to make sure the email is not a duplicate
$stmt1 = $pdo->prepare("SELECT * FROM emailTable WHERE email=?");
$stmt1->execute([$Temail]);
$user = $stmt1->fetch();
if($user) {
//prevents adding a duplicate email
header("Location: duplicate.html");
exit (0);
} else {
//generate Activation code
$Acode = md5(time().$Temail);
//send verification email
$emailfrom = 'no-reply@mydomain.com';
$fromname = 'MY NAME';
$subject = 'Confirm Your Email Subscription';
$emailbody = "
<html>
<body style='background-color: #000; padding: 15px;'>
<table style='background-color: #222;'>
<tr style='background-color: #333; padding: 15px; font-size: 1.3rem;'>
<td><h2 style='color: #FFF;' align='center'>Please Verify Subscription</h2></td>
</tr>
<tr>
<td style='color: #FFF; font-size: 1.1rem;' align='center'>
<br/>
<br/>
If you didn't sign up for my email list, simply delete this message. You will not be added unless you push the button below.
<br/>
<br/>
</td>
</tr>
<tr>
<td style='color: #FFF; font-size: 1.3rem;' align='center'>
<button style='background-color: #000; width: 6rem; height: 2rem;'><a href='https://www.MYDOMAIN.com/verify.php?acode=$Acode' style='color: #F00; text-decoration: none; font-size:1rem;'>VERIFY</a></button>
<br/>
<br/>
</td>
</tr>
<tr>
<td style='color: #FFF; font-size: 1.1rem;' align='center'>
<font style='font-size:0.8rem;'>This email was automatically generated from a mailbox that is not monitored.</font>
</td>
</tr>
</table>
</body>
</html>";
$headers = "Reply-To: MY NAME <no-reply@MYDOMAIN.com>\r\n";
$headers .= "Return-Path: MY NAME <no-reply@MYDOMAIN.com>\r\n";
$headers .= "From: MY NAME <no-reply@MYDOMAIN.com>\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=UTF-8\r\n";
$headers .= "X-Priority: 3\r\n";
$headers .= "X-Mailer: PHP". phpversion() ."\r\n" ;
$params = '-f ' . $emailfrom;
$send = mail($Temail, $subject, $emailbody, $headers, $params); // $send should be TRUE if the mail function is called correctly
if($send) {
//add the new email and other data to the database
$sql = "INSERT INTO emailTable (IP4, datetime, email, acode) VALUES (:IP4, :datetime, :email, :acode)";
$stmt2 = $pdo->prepare($sql);
$stmt2->execute(['IP4' => $userIP4, 'datetime' => $dateTime, 'email' => $Temail, 'acode' => $Acode]);
$userIP4 = "";
$dateTime = "";
$Temail = "";
$Acode = "";
header("Location: success.html");
exit (0);
} else {
header("Location: invalid.html");
exit (0);
}
}
} else {
header("Location: notallowed.html");
exit (0);
}
}
}
} else {
header("Location: invalid.html");
exit (0);
}
} else {
header("Location: invalid.html");
exit (0);
}
//2 END
?>
</code></pre>
<h2>Security threats in mind:</h2>
<p><strong>1. SQL Injections!!! ---</strong> Solutions: Prepared Statements (PDO), using only UTF-8, and including <em>"$bpdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);"</em> in the database connection</p>
<p><strong>2. XSS Attacks!!! ---</strong> Solutions: htmlspecialchars(), Content-Security Policy (placed in htaccess):</p>
<pre><code><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>
</code></pre>
<p><strong>3. OS Command Attacks!!! ---</strong> Solutions: Striping whitespace <em>(not necessary with emails)</em>, validating against a whitelist of permitted values.</p>
<p><strong>4. DOS Attacks!!! ---</strong> Solution: <em>None implemented.</em> I'm unsure if any additional precaution is necessary, since there are no login possibilities on my website.</p>
<p><strong>5. PHP Email Injection!!! ---</strong> Solution: A Regular Expression (the one I have is mostly designed to allow for international characters).</p>
<p>Additionally, I use an <strong>SSL Certificate, SiteLock Security- Essential, CloudFlare CDN</strong>, and have implemented a <strong>DMARC Policy in my DNS</strong> (something I'll be fine tuning for the foreseeable future).</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T03:33:30.623",
"Id": "490466",
"Score": "0",
"body": "`htmlspecialchars` is nonsense. Use this function to sanitize data to be written to a HTML document. You're not doing that anywhere..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T03:41:15.753",
"Id": "490467",
"Score": "0",
"body": "@slepic Which function should I be using? Could you elaborate in my htmlspecialchars is nonsense?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T03:48:32.327",
"Id": "490468",
"Score": "1",
"body": "You should let PDO handle it for you. No extra treatment Is necesary. Further down you do regex check anyway. And that regex basically rules out all HTML entities anyway... Use htmlspecialchars really only before outputting a value into HTML."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T04:20:46.947",
"Id": "490469",
"Score": "0",
"body": "@slepic I understand! Thank you, I'll make that change. Is there anything else that you'd recommend?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T04:35:17.773",
"Id": "490470",
"Score": "1",
"body": "Unfortunately i am short on time So ill leave that to others. Maybe just one more note, you should not show pdo exception message to the client, that belongs to a server side log."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T04:41:15.550",
"Id": "490471",
"Score": "1",
"body": "Oh btw i just noticed you posted two versions of this question https://codereview.stackexchange.com/questions/250058/php-email-verification-sanitizing-email-input-for-database-table you better remove one of them or you're leaving the decision which one will be closed as duplicate to the moderators..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T10:03:27.320",
"Id": "490483",
"Score": "0",
"body": "@slepic PDO has *absolutely* nothing to do with HTML and doesn't handle any. So I don't really get why did you mention it in your otherwise correct comment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T13:15:25.467",
"Id": "490497",
"Score": "0",
"body": "@YourCommonSense Maybe I didn't say it the best way. I meant let PDO handle SQL injection and let the email adress be html escaped only where outputted into HTML which is not anywhere in the OPs provided code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T01:53:35.810",
"Id": "490694",
"Score": "1",
"body": "[What you may and may not do after receiving answers](https://codereview.meta.stackexchange.com/a/1765)"
}
] |
[
{
"body": "<p>First and foremost, regardless of any real or imaginary security issue, this code is a <strong>pain in the eye</strong>. It's nearly impossible to get the gist of it and to answer the actual question because the code is constantly shifting out of sight and the vast amount of HTML gets in the way in the midst of the supposedly email verification code. Useless verifications also add to that.</p>\n<p>You should really rewrite your code first, in order to make it readable. After all, it's sort of a security issue as well - in such a wilderness it's easy to overlook a real issue. <em>Give your code some love</em>:</p>\n<ul>\n<li>move the database connection into a <strong>separate file</strong> and then just include it. By the way, <a href=\"https://phpdelusions.net/pdo_examples/connect_to_mysql\" rel=\"noreferrer\">here is how to do it properly</a>. Right now your PDO connection is a <strong>security issue</strong> because revealing the system error message to the outside world is <a href=\"https://owasp.org/www-community/Improper_Error_Handling\" rel=\"noreferrer\">not a minor one</a></li>\n<li>create a function to send emails, put all this <code>$headers .= "From: MY NAME <no-reply@MYDOMAIN.com>\\r\\n";</code> business there. then put the function itself into a separate file and then just include it.</li>\n<li>move the code to send the actual email into a function and put this function at the bottom of the code. So it won't distract a reader from the main algorithm.</li>\n<li>get rid of the useless code. Checking REMOTE_ADDR makes no sense, there is no situation when it would be invalid. htmlspecialchars is also useless here. and clearing your variables, i.e. <code>$userIP4 = "";</code> as well</li>\n<li>get rid of that stepladder of a code. Given your conditions stop the execution anyway - why not to just test for the negative result and stop the execution?</li>\n</ul>\n<p>So instead of</p>\n<pre><code>if (condition) {\n if (condition2) {\n do something;\n } else {\n display error;\n die;\n } \n} else {\n display error;\n die;\n}\n</code></pre>\n<p>just write</p>\n<pre><code>if (!condition) {\n display error;\n die;\n}\nif (!condition2) {\n display error;\n die;\n}\ndo something;\n</code></pre>\n<p>After making your code suitable for the review, you are welcome to ask a new question regarding your security concerns. By far I was able to spot at least one.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T09:41:58.590",
"Id": "250069",
"ParentId": "250062",
"Score": "5"
}
},
{
"body": "<ul>\n<li><p>Regarding db connection and error handling, please read <a href=\"https://codereview.stackexchange.com/a/227420/141885\">this answer</a>. You must not ever reveal system-generated error details to your end users -- these details are for you and no one else. I recommend a <code>require</code> call, but not before the user's submission qualifies for its usage.</p>\n</li>\n<li><p>There is absolutely no reason that should need to mutate or sanitize the incoming email address. You might like to whitespace <code>trim()</code>, but honestly, who is actually going make the mistake of adding a rogue space? I never have ...ever.</p>\n</li>\n<li><p>For consistency, I always write my negative/failure/false conditional branches before positive/success/true branches. This way, you (or other developers) will know that the lower the script progresses, the more successful the flow has been and additional resources can be initialized/declared.</p>\n</li>\n<li><p>Do not generate the timestamp for the db row in php. You don't even need to mention it in your sql. Set your <code>emailTable</code>'s <code>datetime</code> column to <code>DEFAULT</code> to <code>CURRENT_TIMESTAMP</code>. <a href=\"https://stackoverflow.com/q/168736/2943403\">https://stackoverflow.com/q/168736/2943403</a></p>\n</li>\n<li><p>If the expectation is to permit multibyte characters in email addresses (<code>//allow international characters</code>), your regex is missing the <code>u</code>nicode flag. That said, I do not recommend using regex to try to parse/validate an email address because as your validation pattern improves its accuracy, the readability and maintainability plummets. I recommend <code>filter_var()</code> <a href=\"https://stackoverflow.com/q/12026842/2943403\">https://stackoverflow.com/q/12026842/2943403</a></p>\n</li>\n<li><p><code>$email_host</code> already contains the domain, so don't perform surgery again with <code>explode()</code>/<code>array_pop()</code>.</p>\n</li>\n<li><p><code>SELECT * FROM emailTable WHERE email=?</code> is asking for too much data. You only need the <code>COUNT()</code>, not the row's data. This way, you fetch the count only (which will be zero or one), so the condition is very simple and readable.</p>\n</li>\n<li><p>If you want to DRY out the "header & die" lines, you could create a small helper function that receives the Location text, then calls the <code>header()</code>, then <code>die()</code>s.</p>\n</li>\n<li><p>I would recommend using <code><<<HTML ... HTML;</code> (<code>HEREDOC</code>) syntax so that you can use double quotes in your markup and inline variables. Alternatively, you could use <code>sprintf()</code>, but that is less compelling with just one variable.</p>\n</li>\n<li><p><s>Since <code>$headers</code> lines are all delimited by <code>\\r\\n</code>, </s>I recommend, creating an array of lines<s>, then <code>implode()</code>ing with <code>\\r\\n</code> to be more DRY</s>. The fourth parameter of <code>mail()</code> is the header data which can receive an array.</p>\n</li>\n<li><p>I do not recommend the native <code>mail()</code>. I always build PHPMailer into all of my projects for ease of use and functionality.</p>\n</li>\n<li><p>I am concerned about the ambiguity if <code>invalid.html</code>. If <code>mail()</code> fails, then the user won't know if there is something that they can fix or not.</p>\n</li>\n<li><p><code>$userIP4 = ""; $dateTime = ""; $Temail = ""; $Acode = "";</code> this is all useless nonsense, just omit all of it.</p>\n</li>\n<li><p>Comb through your script and search for single-use variables. When you see a declared variable only used one time, then you don't need to declare it.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T16:19:34.647",
"Id": "490628",
"Score": "0",
"body": "`There is absolutely no reason that should need to mutate or sanitize the incoming email address` Shouldn't all incoming user input be treated as potentially malicious?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T16:20:12.623",
"Id": "490629",
"Score": "1",
"body": "Validate: Yes. Sanitize: No. If it is a valid email address then proceed; if it is anything else kill the process."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T16:23:04.833",
"Id": "490630",
"Score": "0",
"body": "My problem with `filter_var` is that it does not allow international characters. What additions can I include with `filter_var` to allow for them?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T16:23:44.543",
"Id": "490631",
"Score": "0",
"body": "Hmm... good question. I haven't researched this."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T10:48:24.703",
"Id": "250072",
"ParentId": "250062",
"Score": "3"
}
},
{
"body": "<h2>Unnecessary information disclosure</h2>\n<p>Don't do this:</p>\n<pre><code>$headers .= "X-Mailer: PHP". phpversion() ."\\r\\n" ;\n</code></pre>\n<p>This will show up in the mail headers and be visible by the recipient. It's nobody's business what version of PHP you're running. In case you're running a version of PHP that has vulnerabilities, this provides hackers with insight into your systems for a tailored exploit. Just don't copy-paste code without understanding the implications...</p>\n<h2>IPv4 & IPv6</h2>\n<p>I don't understand the point of gethostbyname. You already have the IP address, so you can store it.</p>\n<p>Are you sure your server isn't reachable on the Internet over IPv6 ? You might want to test your site over IPv6 by adding an entry to your DNS configuration eg ipv6.yoursite.com with one AAAA record, and no A record.</p>\n<h2>Randomization</h2>\n<p>The verification code is not really <strong>random</strong>:</p>\n<pre><code>$Acode = md5(time().$Temail);\n</code></pre>\n<blockquote>\n<p>time — Return current Unix timestamp</p>\n</blockquote>\n<p>Someone (a hacker) who knows your formula will be able to bruteforce the verification code because it follows a predictable pattern. You have many better options to generate reasonably random strings.</p>\n<h2>Misc</h2>\n<p>I would probably reorder some code, for example save the record to database before sending the mail. If the database crashes for some reason or the connection is lost, you've already sent an E-mail with a verification code that is not recorded anywhere and will not work - which is confusing for the user. If the record was not saved for some reason, notify the user that there was an error (and notify yourself too), and don't proceed further.</p>\n<p>The sending of the mail is probably less likely to crash, because it usually goes to a mail queue to be handled by the MTA on your server.</p>\n<p>It's possible that the mail doesn't arrive or was discarded or spam-trapped, so it should be possible for the user to request a new code after some time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T21:41:50.390",
"Id": "490549",
"Score": "2",
"body": "Even [uniqid](https://www.php.net/manual/en/function.uniqid) could be sufficient here (with some caveats), because we do not need \"cryptographically secure values\". But the doc also says \"This function does not guarantee uniqueness of return value\", so consider adding additional entropy. Actually random_bytes is a better option."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T21:42:01.657",
"Id": "490550",
"Score": "0",
"body": "\"it should be possible for the user to request a new code after some time,\" Thank you Anonymous. I didn't include it in this post, but I use an hourly cronjob to check the table for rows where a record has gone unverified for 24 hours or more. The cronjob then runs another php file and deletes the 'expired' records. I'm cleaning up my code and plan to make another post that is easier to read and includes everything I have. :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T21:19:17.150",
"Id": "250096",
"ParentId": "250062",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "250069",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T01:07:46.457",
"Id": "250062",
"Score": "3",
"Tags": [
"php",
"html",
"validation",
"email",
"sql-injection"
],
"Title": "Email Validation in PHP"
}
|
250062
|
<p>I have written an accumulate function similar to <a href="https://en.cppreference.com/w/cpp/algorithm/accumulate" rel="noreferrer">std::accumulate</a> that works on a <a href="https://en.cppreference.com/w/cpp/container/array" rel="noreferrer">std::array</a>. The goal is to remove the loop using fold expressions.</p>
<p>This code currently works in c++17:</p>
<pre><code>#include <array>
template<class U, class F>
class array_accumulate_helper
{
public:
array_accumulate_helper(U& u, F f)
: r(u), f(f)
{
}
array_accumulate_helper& operator<<(const U& u)
{
r = f(r, u);
return *this;
}
private:
F f;
U& r;
};
template<class U, std::size_t N, class F, std::size_t... Is>
constexpr U array_accumulate_impl(const std::array<U, N>& u, U r, F f, std::index_sequence<Is...>)
{
array_accumulate_helper h(r, f);
(h << ... << u[Is]);
return r;
}
template<class U, std::size_t N, class F>
constexpr U accumulate(const std::array<U, N>& u, U r, F f)
{
return array_accumulate_impl(u, r, f, std::make_index_sequence<N>());
}
template<class U, std::size_t N>
constexpr U accumulate(const std::array<U, N>& u)
{
return accumulate(u, {}, [](const U& a, const U& b) { return a + b; });
}
</code></pre>
<p>Is it possible to rewrite <code>array_accumulate_impl</code> using a fold expression that doesn't use <code>array_accumulate_helper</code>?</p>
<p>I can use a fold expression with an operator.
ie. using <code><<</code> in <code>array_accumulate_impl</code> above.</p>
<p>I have been unable to write one using a function recursively.
ie. for a <code>std::array<int, 3></code> it should expand to:</p>
<pre><code>f(f(f(r, a[0]), a[1]), a[2]);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T07:50:53.130",
"Id": "490474",
"Score": "1",
"body": "Can you add a `main` that exercises the code a little? I couldn't get it to work without making the member functions in `array_accumulate_helper` `constexpr` too. [example](https://godbolt.org/z/Mf7KdK)"
}
] |
[
{
"body": "<p>Unfortunately c++ <a href=\"https://en.cppreference.com/w/cpp/language/fold\" rel=\"noreferrer\">fold expression</a> supports only binary operators: "any of the following 32 binary operators: + - * / % ^ & | = < > << >> += -= <em>= /= %= ^= &= |= <<= >>= == != <= >= && || , .</em> ->*." So you can't call your custom function in pack expansion without using a wrapper.</p>\n<p>But if your function accepts a variadic number of arguments you can use std::apply</p>\n<pre><code>static constexpr std::array arr{ 1, 2, 3, 4, 5, 6, 7};\n\nstatic constexpr auto sum = [](auto&&... items) {\n return (... + items);\n};\n\nstatic constexpr auto accumulate = [](auto&& fn, const auto& u) {\n return std::apply([fn = std::forward<decltype(fn)>(fn)](auto... item) { return fn(item...); }, u);\n};\n\nconstexpr auto result = accumulate(sum, arr);\n</code></pre>\n<p>Example <a href=\"https://godbolt.org/z/foc866\" rel=\"noreferrer\">here</a>.</p>\n<p>Otherwise, you can take advantage of the comma operator:</p>\n<pre><code>static constexpr std::array arr{ 1, 2, 3, 4, 5, 6, 7};\n\nstatic constexpr auto accumulate_impl = [](const auto& a, auto init, auto&& fn) {\n return std::apply([fn = std::forward<decltype(fn)>(fn), &init](auto... items) {\n ((void)(init = fn(std::move(init), items)), ...);\n return init;\n }, a);\n};\n\ntemplate<class U, std::size_t N>\nstatic constexpr U accumulate(const std::array<U, N>& u) {\n return accumulate_impl(u, U{}, [](auto&& a, auto&& b){return a+b;});\n}\n\nstatic constexpr auto result = accumulate(arr);\n</code></pre>\n<p>Example <a href=\"https://godbolt.org/z/4rWPef\" rel=\"noreferrer\">here</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T03:38:14.640",
"Id": "490572",
"Score": "0",
"body": "Also worthwhile: [std::plus<void>](//en.cppreference.com/w/cpp/utility/functional/plus_void)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T16:42:44.967",
"Id": "490635",
"Score": "0",
"body": "Nice. Thanks for expanding my knowledge."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T15:41:03.633",
"Id": "250084",
"ParentId": "250063",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "250084",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T03:11:22.063",
"Id": "250063",
"Score": "5",
"Tags": [
"c++",
"fold"
],
"Title": "fold expressions using a function recursively"
}
|
250063
|
<p>I've recently been learning C on my own, and I thought I'd try my hand at writing a graph implementation.</p>
<pre class="lang-c prettyprint-override"><code>// graph.h
#ifndef GRAPH_H
#define GRAPH_H
#include <stdlib.h>
#include <string.h>
typedef struct node node_t;
typedef struct node {
int value;
node_t **links;
int links_count;
} node_t;
node_t *create_node(int value);
void destroy_node(node_t *node);
void link_nodes(node_t *first_node, node_t *second_node);
void unlink_nodes(node_t *first_node, node_t *second_node);
#endif /* GRAPH_H */
</code></pre>
<pre class="lang-c prettyprint-override"><code>// graph.c
#include "graph.h"
static void remove_link(node_t *node, int index) {
// If the index is out of bounds, return early
if (index >= node->links_count || index < 0) return;
// Move links down the array, overwriting the link's index
for (int i = index; i < node->links_count - 1; i++) {
node->links[i] = node->links[i + 1];
}
// Get rid of the dangling pointer
node->links[node->links_count - 1] = NULL;
if (node->links_count == 1) {
// If this is the only link, deallocate arrays
free(node->links);
node->links = NULL;
} else {
// Otherwise, shrink them
node->links = realloc(node->links, sizeof(node_t *) * --node->links_count);
}
}
static void increase_link_space(node_t *node) {
if (node->links_count == 0) {
// If there isn't an array, create one
node->links = malloc(sizeof(node_t *));
} else {
// Otherwise, expand it
node->links = realloc(node->links, sizeof(node_t *) * (node->links_count + 1));
}
}
node_t *create_node(int value) {
// Allocate memory for the node
node_t *node = malloc(sizeof(node_t));
if (node == NULL) exit(-1);
node->links_count = 0;
node->value = value;
return node;
}
void destroy_node(node_t *node) {
// Remove all links to and from other nodes
// For each link in this node...
for (int i = 0; i < node->links_count; i++) {
// For each link in the link...
for (int j = 0; j < node->links[i]->links_count; j++) {
// If a link matches the original node (i.e. loopback)...
if (node->links[i]->links[j] == node) {
// Remove the link and break
remove_link(node->links[i]->links[j], j);
break;
}
}
}
// Free up malloc'd memory
free(node->links);
free(node);
}
void link_nodes(node_t *first_node, node_t *second_node) {
// Create space for the new link
increase_link_space(first_node);
increase_link_space(second_node);
// Link the first node to the second node
first_node->links[first_node->links_count] = second_node;
// Link the second node to the first
second_node->links[second_node->links_count] = first_node;
}
void unlink_nodes(node_t *first_node, node_t *second_node) {
// The index of second_node in first_node's links
int first_index = -1;
// The index of first_node in second_node's links
int second_index = -1;
// Search through first_node->links
for (int i = 0; i < first_node->links_count; i++) {
if (first_node->links[i] == second_node) {
first_index = i;
break;
}
}
// If no match was found, return
if (first_index < 0) return;
// Search through second_node->links
for (int i = 0; i < second_node->links_count; i++) {
if (second_node->links[i] == first_node) {
second_index = i;
break;
}
}
// We don't need a second check, because as long as the program is using node_t correctly, one-way links won't exist.
// Even if a one-way link exists, remove_link has a check for out-of-bounds (including negative) indices.
// Remove the found indices
remove_link(first_node, first_index);
remove_link(second_node, second_index);
}
</code></pre>
<p>Here's a test program:</p>
<pre class="lang-c prettyprint-override"><code>#include "graph.h"
int main(void) {
node_t *first_node = create_node(5);
node_t *second_node = create_node(7);
node_t *third_node = create_node(3);
/*
3
7
5
*/
link_nodes(first_node, second_node);
link_nodes(first_node, third_node);
/*
3
^ 7
| ^
->5<-----|
*/
destroy_node(third_node);
/*
7
^
5<-----|
*/
unlink_nodes(first_node, second_node);
/*
7
5
*/
destroy_node(first_node);
destroy_node(second_node);
}
</code></pre>
<p>This is my first data structure implementation, so any and all tips/criticism would be really helpful.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T08:38:15.420",
"Id": "490475",
"Score": "0",
"body": "Can you show a usage example so that reviewers can easily test it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T15:42:54.443",
"Id": "490518",
"Score": "0",
"body": "@L.F. I've now added one."
}
] |
[
{
"body": "<h1>Only <code>#include</code> what you need, where you need it</h1>\n<p>In <code>graph.h</code>, you <code>#include</code> <code><stdlib.h></code> and <code><string.h></code>, but you don't use anything from those headers inside <code>graph.h</code> itself, so you should not <code>#include</code> anything there. Instead, in <code>graph.c</code>, you need to <code>#include <stdlib.h></code> in order to use <code>malloc()</code> and <code>free()</code>, but you don't need anything else.</p>\n<h1>Avoid unnecessary forward declarations</h1>\n<p>You are doing a <code>typedef struct node node_t</code> twice. The first one was needed to be able to write <code>node_t</code> inside the definition of <code>struct node</code>. But you can avoid this by just writing:</p>\n<pre><code>typedef struct node {\n int value;\n struct node **links;\n int links_count;\n} node_t;\n</code></pre>\n<p>This avoids the duplication (GCC will warn about it if you compile with <code>-std=c99 -pedantic</code>).</p>\n<h1>Improve <code>struct</code> packing</h1>\n<p>On a 64-bit machine, your <code>struct node</code> will use 24 bytes, but you can reduce that to only 16 bytes by writing:</p>\n<pre><code>typdef struct node {\n int value;\n int links_count;\n node_t **links;\n} node_t;\n</code></pre>\n<p>This is because the ints are only 4 bytes, but pointers are 8 bytes, and need to be aligned to 8 bytes.</p>\n<h1>Remove redundant comments</h1>\n<p>Comments should be added when the code itself is not clear on its own. However, just repeating in English exactly what a C statement does is not helpful. For example, in <code>destroy_node()</code>, I would only keep the first comment:</p>\n<pre><code>void destroy_node(node_t *node) {\n // Remove all links to and from other nodes\n for (int i = 0; i < node->links_count; i++) {\n for (int j = 0; j < node->links[i]->links_count; j++) {\n if (node->links[i]->links[j] == node) {\n remove_link(node->links[i]->links[j], j);\n break;\n }\n }\n }\n\n free(node->links);\n free(node);\n}\n</code></pre>\n<h1>Optimizing link addition/removal</h1>\n<p>Adding a link is potentially slow, because you reallocate just enough for one more link at a time. Since <code>realloc()</code> might not be able to grow the allocation in-place, this means your link addition becomes <span class=\"math-container\">\\$\\mathcal{O}(D^2)\\$</span>, where <span class=\"math-container\">\\$D\\$</span> is the average number of links per node. A common trick to reduce the overhead from memory allocation is to double the size of the array whenever it is full, so the more links you have the less often you have to reallocate it.</p>\n<p>Removal has a similar performance problem, because you have to scan the list of links to find a match, and then in the node that you linked to you have to do the same. Furthermore, when deleting a link, you are shifting all remaining elements in the array <code>links</code> by one.</p>\n<p>Depending on how often you add or remove links, you might have different ways to optimize this. For example, if you rarely remove links, then I would just optimize how you remove an element from an array: instead of shifting down the remaining elements, just copy the last element into the place of the deleted element. If you often remove links, then you might benefit from keeping the array <code>links</code> sorted, so that looking up a link is <span class=\"math-container\">\\$\\mathcal{O}(\\log D)\\$</span>. The drawback is of course that inserting a link becomes more complicated, but for large, dense graphs this should be much faster. You can also consider only sorting the array right before you need to search it. Have a look at these standard C functions that help you do binary searches:</p>\n<ul>\n<li><a href=\"https://en.cppreference.com/w/c/algorithm/qsort\" rel=\"nofollow noreferrer\"><code>qsort()</code></a></li>\n<li><a href=\"https://en.cppreference.com/w/c/algorithm/bsearch\" rel=\"nofollow noreferrer\"><code>bsearch()</code></a></li>\n</ul>\n<p>Another thing to think about is whether you really need both nodes have a link to each other. You could also treat it as a directed graph, and then you don't need to keep links in sync.</p>\n<h1>Use <code>size_t</code> for counts, sizes and array indices</h1>\n<p>An <code>int</code> might not be large enough to handle all possible array sizes. Use a <code>size_t</code> instead, it is guaranteed to be able to uniquely index all elements of an array that fit inside the memory accessible to your program. This means changing the type of <code>links_count</code>, and using <code>size_t i</code> in <code>for</code>-loops. Avoid using <code>-1</code> as a special value indicating that you didn't find an element, instead use the fact that <code>links_count</code> is an index that doesn't point to a valid element, or use a separate variable to keep track of whether you found an element or not.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T19:57:21.340",
"Id": "490539",
"Score": "0",
"body": "Thank you for the thorough review! The `<string.h>` include was a remnant from when I used to store strings before I genericised the structure; I guess I forgot to remove it. The way I'm attempting to use this requires bidirectional links. What do you mean by \"use the fact that `links_count` is an index that doesn't point to a valid element\"?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T20:12:49.713",
"Id": "490543",
"Score": "1",
"body": "Instead of using `int first_index = -1`, you can write `size_t first_index = first_node->link_count`, and then check if you didn't find a match like so: `if (first_index == first_node->link_count) return`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T20:19:23.847",
"Id": "490545",
"Score": "0",
"body": "I see. Wouldn't that be less efficient since it involves a dereference? (I'm genuinely asking; I don't know if such a difference would even be important.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T20:42:50.183",
"Id": "490546",
"Score": "1",
"body": "You already use `first_node->link_count` in the `for`-statement. The compiler can see that it only needs to read the value once, and can keep it in a register."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T21:12:23.900",
"Id": "490547",
"Score": "0",
"body": "Ah, neat. Thanks for clarifying!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T19:50:24.847",
"Id": "250093",
"ParentId": "250064",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "250093",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T06:50:28.973",
"Id": "250064",
"Score": "4",
"Tags": [
"c",
"graph"
],
"Title": "Graph implementation in C"
}
|
250064
|
<p>In order to get more accustomed with classes in Python, I have written a genetic algorithm, which takes a level with a start and end point and searches for a route (not necessarily the optimal one). The output shows the basic level and when a solution has been found, the level with the route:</p>
<pre><code>Level:
############
O....#.....#
#.#.#.#.#..#
#........#.O
############
Solution:
############
O*...#.****#
#*#*#*#*#**#
#********#**
############
</code></pre>
<p>I would be interested in improvements of the structure of the code (i.e. not of the algorithm itself, only if there is an error), as I would like to improve my general knowledge of programming in Python.</p>
<p>There are some issues I am aware of:</p>
<ul>
<li>The parameters at the beginning could be written as enums, but I couldn't convince myself what the advantage would be (apart from polluting the global namespace?) I thought that the more concise way of writing "N" or "WALL" instead of "Direction.N" or "Object.Wall" added to the readability of the code.</li>
<li>Class "Level": In principle, I would prefer that the attributes are read-only, but I am not sure how to define this properly. Also, I don't see the point of writing getters and setters here.</li>
<li>In the same class, I didn't want to write __move_dict and __text_map twice in test_route and print_route, so I defined it as class variables. I am not sure if this is idiomatic at all.</li>
<li>Similarly, test_route and print_route share the same code. I have been thinking if it would be possible to abstract away somehow the common loop, but I have no idea how to do this in Python.</li>
</ul>
<pre><code>""""Simple implementation of a genetic algorithm:
Searching for a possible route from a given start point
to an end point."""
import random
from dataclasses import dataclass
from typing import List
from collections import namedtuple
from operator import attrgetter
# PARAMETERS
# direction constants
N = 0
E = 1
S = 2
W = 3
# level constants
EMPTY = 0
WALL = 1
DOOR = 2
L1 = [[WALL, WALL, WALL, WALL, WALL, WALL, WALL, WALL, WALL, WALL, WALL, WALL],
[DOOR, EMPTY, EMPTY, EMPTY, EMPTY, WALL, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, WALL],
[WALL, EMPTY, WALL, EMPTY, WALL, EMPTY, WALL, EMPTY, WALL, EMPTY, EMPTY, WALL],
[WALL, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, WALL, EMPTY, DOOR],
[WALL, WALL, WALL, WALL, WALL, WALL, WALL, WALL, WALL, WALL, WALL, WALL]]
L1_WIDTH = 12
L1_HEIGHT = 5
# DATATYPES
Point = namedtuple("Point", "x y")
@dataclass
class Level:
"""Class for representing a level with a start and end point."""
map: list
width: int
height: int
start: Point
end: Point
__move_dict = {N: Point(0, 1),
E: Point(1, 0),
S: Point(0, -1),
W: Point(-1, 0)}
__text_map = {WALL: "#", EMPTY: ".", DOOR: "O"}
def test_route(self, genome):
"""Test a route encoded in a genome and return the final distance to the exit."""
def distance(point_a, point_b):
return abs(point_a.x - point_b.x) + abs(point_a.y - point_b.y)
position = self.start
for gene in genome.genes:
delta = self.__move_dict[gene]
new_pos = Point(position.x + delta.x,
position.y + delta.y)
if 0 <= new_pos.x < self.width:
if 0 <= new_pos.y < self.height:
if self.map[new_pos.y][new_pos.x] != WALL:
position = new_pos
if position == self.end:
break
return 1 / (1 + distance(position, self.end))
def print_level(self):
"""Print a text representation of a level."""
for row in self.map:
print("".join((self.__text_map[elem] for elem in row)))
def print_route(self, genome):
"""Print the route through the level."""
text_level = []
for row in self.map:
text_level.append([self.__text_map[elem] for elem in row])
position = self.start
for gene in genome.genes:
delta = self.__move_dict[gene]
new_pos = Point(position.x + delta.x,
position.y + delta.y)
if 0 <= new_pos.x < self.width:
if 0 <= new_pos.y < self.height:
if self.map[new_pos.y][new_pos.x] != WALL:
position = new_pos
text_level[new_pos.y][new_pos.x] = "*"
if position == self.end:
break
for row in text_level:
print("".join(row))
@dataclass
class Genome:
"""Class for representing the genome of running through a level."""
fitness: float
genes: List[int]
class GenomePool:
"""Class implementing the genetic algorithm."""
def __init__(self, level, pool_size, num_genes, crossover_rate, mutation_rate):
self.__level = level
self.__pool_size = pool_size
self.__num_genes = num_genes
self.__crossover_rate = crossover_rate
self.__mutation_rate = mutation_rate
self.__pool = [Genome(0, [random.randint(0, 3) for i in range(0, num_genes)])
for _ in range(self.__pool_size)]
self.__update_fitness()
def __select_genome(self):
"""Do a roulette wheel selection and return a genome."""
total_fitness = sum((genome.fitness for genome in self.__pool))
cut = random.uniform(0, total_fitness)
partial_fitness = 0
idx = 0
while partial_fitness < cut:
partial_fitness += self.__pool[idx].fitness
idx += 1
return self.__pool[idx] if idx < len(self.__pool) else self.__pool[self.__pool_size - 1]
def __crossover(self, mother, father):
"""Do a crossover of two genomes and return an offspring."""
if random.random() > self.__crossover_rate:
return mother
crossover_point = int(random.uniform(0, self.__num_genes))
offspring = Genome(0, [])
offspring.genes = mother.genes[0:crossover_point] + father.genes[crossover_point:]
return offspring
def __mutate(self, genome):
for i in range(self.__num_genes):
if random.random() < self.__mutation_rate:
genome.genes[i] = int(round(random.uniform(0, 3)))
def __update_fitness(self):
"""Update the fitness score of each genome."""
for genome in self.__pool:
genome.fitness = self.__level.test_route(genome)
def get_best_genome(self):
"""Return the genome with the best fitness."""
sorted_pool = sorted(self.__pool, key=attrgetter("fitness"), reverse=True)
return sorted_pool[0]
def run(self, verbose=False):
"""Run the genetic algorithm until a solution has been found."""
iteration = 0
while all((x.fitness != 1 for x in self.__pool)):
if verbose:
best_fitness = self.get_best_genome().fitness
print(f"Iteration {iteration}: Best fitness = {best_fitness}")
iteration += 1
self.step()
def step(self):
"""Run one time step of the evolution."""
new_pool = []
for i in range(self.__pool_size):
mother = self.__select_genome()
father = self.__select_genome()
offspring = self.__crossover(mother, father)
self.__mutate(offspring)
new_pool.append(offspring)
self.__pool = new_pool
self.__update_fitness()
def main():
level_one = Level(L1, L1_WIDTH, L1_HEIGHT, start=Point(0, 1),
end=Point(11, 3))
print("Level:")
level_one.print_level()
genome_pool = GenomePool(level_one, pool_size=30, num_genes=70,
crossover_rate=0.7, mutation_rate=0.01)
genome_pool.run()
print()
print("Solution:")
level_one.print_route(genome_pool.get_best_genome())
if __name__ == "__main__":
main()
</code></pre>
|
[] |
[
{
"body": "<h1>Answers to your questions</h1>\n<blockquote>\n<p>The parameters at the beginning could be written as enums, but I couldn't convince myself what the advantage would be (apart from polluting the global namespace?) I thought that the more concise way of writing "N" or "WALL" instead of "Direction.N" or "Object.Wall" added to the readability of the code.</p>\n</blockquote>\n<p>Enums are generally a good idea, since they have some nice properties. In particular, they are in their own distinctive class, and you cannot accidentily compare an enum with something that is not an enum. For example, in your code, both <code>E</code> and <code>WALL</code> are just <code>1</code>, so <code>E == WALL</code> will result in <code>True</code>, which is not what you would expect. So I would definitely use enums here.</p>\n<p>Now, you are right that using enums results in more verbose code. But, you can still create variables with short names that you assign enums to, and get the best of both worlds. For example:</p>\n<pre><code>class Tile(enum.Enum):\n EMPTY = 0\n WALL = 1\n DOOR = 2\n\nEMPTY = Tile.EMPTY\nWALL = Tile.WALL\nDOOR = Tile.DOOR\n\nL1 = [[WALL, WALL, ...], [DOOR, EMPTY, ...], ...]\n</code></pre>\n<p>Note that enums in Python don't require you to have numeric values, you can do the following:</p>\n<pre><code>class Direction(enum.Enum):\n N = Point(0, 1)\n E = Point(1, 0)\n S = Point(0, -1)\n W = Point(-1, 0)\n\nclass Tile(enum.Enum):\n EMPTY = "."\n WALL = "#"\n DOOR = "O"\n</code></pre>\n<p>This then avoids the need for <code>__move_dict</code> and <code>__text_map</code>.</p>\n<blockquote>\n<p>Class "Level": In principle, I would prefer that the attributes are read-only, but I am not sure how to define this properly. Also, I don't see the point of writing getters and setters here.</p>\n</blockquote>\n<p>See <a href=\"https://stackoverflow.com/questions/14594120/python-read-only-property\">this question</a> for some possible answers.</p>\n<blockquote>\n<p>In the same class, I didn't want to write __move_dict and __text_map twice in test_route and print_route, so I defined it as class variables. I am not sure if this is idiomatic at all.</p>\n</blockquote>\n<p>This is perfectly fine! Avoiding repetition is very important in keeping your code concise and maintainable.</p>\n<blockquote>\n<p>Similarly, test_route and print_route share the same code. I have been thinking if it would be possible to abstract away somehow the common loop, but I have no idea how to do this in Python.</p>\n</blockquote>\n<p>You can create a <em>generator</em> that loops over the path, and for each point yields the position of that point. Then you can use that to simplify loops in <code>test_route()</code> and <code>print_route()</code>, like so:</p>\n<pre><code>def visit_route(self):\n ...\n for gene in genome.genes:\n ...\n position = new_pos\n yield position\n\ndef test_route(self, genome):\n last_position = self.start\n\n for position in self.visit_route():\n last_position = position\n\n return 1 / (1 + distance(last_position, self.end))\n\ndef print_route(self):\n text_level = [[self.__text_map[elem] for elem in row] for row in self.map]\n\n for position in self.visit_route():\n text_level[position.y][position.x] = "*")\n\n for row in text_level:\n print ("".join(row))\n</code></pre>\n<h1>Avoid storing redundant information</h1>\n<p>Your <code>class Level</code> stores <code>width</code> and <code>height</code>, but this information is already in <code>map</code>: <code>height</code> should be equal to <code>len(map)</code>, and <code>width</code> should be equal to <code>len(map[0])</code>. While there might sometimes be reasons to keep copies of data that is expensive to calculate, the drawback is that you have to ensure the data is consistent. What if I create a <code>Level([[EMPTY]], 100, 100)</code>?</p>\n<p>Similarly, what happens if <code>start_point</code> and <code>end_point</code> don't match where the <code>DOOR</code>s are in the <code>map</code>? This one is perhaps more tricky. Consider creating a constructor for <code>class Level</code> that checks whether the given parameters are consistent, or have it automatically derive <code>width</code>, <code>height</code>, <code>start_point</code> and <code>end_point</code> from the <code>map</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-04T11:27:39.710",
"Id": "250179",
"ParentId": "250065",
"Score": "5"
}
},
{
"body": "<h2>Representation</h2>\n<pre><code>############\nO....#.....#\n#.#.#.#.#..#\n#........#.O\n############\n</code></pre>\n<p>I would find this representation of a level much more readable if the empty space was printed as space <code> </code> rather than <code>.</code></p>\n<pre><code>############\nO # #\n# # # # # #\n# # O\n############\n</code></pre>\n<p>In the code, I would use the same representations as input to the program, so that rather than this</p>\n<pre><code>L1 = [[WALL, WALL, WALL, WALL, WALL,\n</code></pre>\n<p>You could define</p>\n<pre><code>L1 = [\n"############",\n"O # #",\n"# # # # # #",\n"# # O",\n"############",\n]\n</code></pre>\n<p>And then you would let some function translate that into whatever internal logic you need for your algorithm.</p>\n<p>I would also change the symbol for the travelled path from <code>*</code> to something else that is easier to visually distinguish from the <code>#</code> used for walls. Perhaps change the walls too.</p>\n<h2>Code</h2>\n<pre><code>if 0 <= new_pos.x < self.width:\n if 0 <= new_pos.y < self.height:\n if self.map[new_pos.y][new_pos.x] != WALL:\n position = new_pos\n</code></pre>\n<p>This is not wrong, but it would typically be written using <code>and</code> instead of several nested ifs, when you have no need for <code>else</code> cases or other options.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-04T12:20:33.660",
"Id": "250180",
"ParentId": "250065",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "250179",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T08:07:52.837",
"Id": "250065",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"genetic-algorithm"
],
"Title": "Route finding Genetic Algorithm"
}
|
250065
|
<p>I hope this is the right spot to ask this, if not tell me and I will delete the post.</p>
<p>I need my GUI/program to update whenever the <code>active_bots</code> variable is changed, to display the contents of this variable.</p>
<p>Is this the correct way to speak to the GUI instance? Pass the instance in the module-call and then set the active_bots-variable by calling the GUI-setter from the module. Or is this bad practice/is there a better way?</p>
<p>Cutting out a lot my code looks like this:</p>
<pre><code>import curses
import modules.bots.quote_bot as quoteBot
class GUI:
def __init__(self, stdscr):
self.active_bots = [] #This variable is the one that needs to be watched
#All kinds of preparation etc.
self.run() # This would normally call run and start the program
def run(self):
while True:
key = self.screen.getch()
if key == ord('e'):
#End program
break
elif (key == ord('q')):
# Start bot
quoteBot.start(self)
else:
#do nothing
continue
#Revert terminal settings and end
self.screen.clear()
curses.endwin()
def active_bots_setter(self, operator, botname):
if (operator == '-'):
self.active_bots.remove(botname)
elif (operator == '+'):
self.active_bots.append(botname)
else:
raise ValueError
self.init_user_window() #Refresh user-window
#Start program.
#Use wrapper to restore original terminal settings even if exception raised
curses.wrapper(GUI)
</code></pre>
<p>quote_bot.py</p>
<pre><code>def start(GUI_instance):
#Check whether QuoteBot is already running
thread_list = [] #List of alive threads
for thread in threading.enumerate():
thread_list.append(thread.getName())
if "QuoteBot-Thread" in thread_list:
logger.info("QuoteBot: Shutting down...")
stop()
else:
logger.info("QuoteBot: Starting up...")
GUI_instance.active_bots_setter('+', "QuoteBot")
if (check_connection() == True):
t = threading.Thread(target=tweet_quote)
t.name = 'QuoteBot-Thread'
t.daemon = True
t.start()
else:
logger.error("Quotebot: Quote API Connection Test - Failed to connect! /nCancelling start up.")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T14:23:14.947",
"Id": "490506",
"Score": "1",
"body": "\"Is this the correct way to speak to the GUI instance?\" Did you test it? Does it work?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T14:25:15.863",
"Id": "490507",
"Score": "2",
"body": "Please take a look at our [FAQ on asking questions](https://codereview.meta.stackexchange.com/q/2436/52915)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-05T09:36:05.230",
"Id": "490875",
"Score": "0",
"body": "@Mast Yes I tested it, it does indeed work. Passing self makes my module able to speak to the gui-instance. I was just wondering whether there exists a better, cleaner way."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T09:14:31.767",
"Id": "250068",
"Score": "1",
"Tags": [
"python",
"gui",
"modules",
"curses"
],
"Title": "Tell GUI to update itself by passing self to module?"
}
|
250068
|
<p>I'm working with TCP sockets in C, specifically only for client side HTTP(S) requests, and would like to get some feedback on my send and recv code.</p>
<p>You can make some assumptions regarding my code, as it is, by no means a complete example but I'll try to make it reproducible.</p>
<ul>
<li>Assume <code>sfd</code> has been set to <code>O_NONBLOCK</code></li>
<li>Assume <code>SOCKET_ERROR</code> is a macro for -1</li>
<li>Assume <code>POLLFD</code> is a typedef for <code>struct pollfd</code></li>
<li>Assume <code>RESPONSE_BUFFER_LEN</code> is 4096</li>
<li>Assume <code>errno_is_ok</code> is a macro to check if errno is set to <code>EWOULDBLOCK</code>, <code>EAGAIN</code> or <code>EINTR</code> - these errnos are ignored</li>
<li>Assume <code>extend_resbuff</code> (used in the recv code) is a function that extends resbuff by multiplying its current len with 2. It takes care of alloc failures by itself</li>
<li>Assume <code>trim_resbuff</code> (used in the recv code) is a function that trims the resbuff to the exact size it needs to be and null terminates it</li>
<li>The message sent using my sender function will <strong>always</strong> contain <code>Connection: close</code> as a header.</li>
</ul>
<p>My <code>send</code> code, assume a <code>connect</code> call has been made. Also assume <code>connect</code> has returned - or rather, set errno to - <code>EINPROGRESS</code>.</p>
<pre><code>/*
Send given message through given socket
Sends the message in its entirety
Returns true upon success, false upon failure
*/
bool send_all(socket_t sfd, char const* restrict msg, ssize_t msglen)
{
ssize_t sent = 0;
ssize_t stat = 0;
do
{
/* Poll for readying the send */
POLLFD pfds[1] = { { .fd = sfd, .events = POLLOUT } };
if (poll(pfds, sizeof(pfds) / sizeof(pfds[0]), POLL_TIMEOUT) == 0)
{
/* Timeout */
return false;
}
if (pfds[0].revents & POLLOUT)
{
/* Ready to write */
stat = send(sfd, msg + sent, msglen - sent, 0);
sent += stat;
}
else
{
/*
Is it safe to assume an errno is set in this branch?
The caller is then expected to check the errno
If this branch is hit, is recovery possible (within the scope
of this function)?
*/
return false;
}
/*
This loop exits either when
* full message is sent
* stat is SOCKET_ERROR but errno **is not** EAGAIN or EWOULDBLOCK or EINTR
*/
} while (sent < msglen && (stat != SOCKET_ERROR || errno_is_ok));
return stat != SOCKET_ERROR;
}
</code></pre>
<p>Also of note- the <code>msg</code> is always an HTTP request. Something like <code>GET / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n</code>. That <code>Connection: close</code> is always present in the headers.</p>
<p>Now, the <code>recv</code> code.</p>
<pre><code>/*
Receive response through given socket
Receives the message in its entirety and stores it into resbuff
resbuff does not need to be allocated - this function manages the allocation
Returns true upon success, false upon failure
*/
bool recv_all(socket_t sfd, char** restrict resbuff, size_t* restrict len)
{
ssize_t stat = 0;
size_t idx = 0; /* Latest initialized element index of *resbuff */
*len = RESPONSE_BUFFER_LEN; /* Length of *resbuff (initially) */
/* Prepare the resbuff */
*resbuff = malloc(*len * sizeof(**resbuff));
if (*resbuff == NULL)
{
/* malloc failed */
return false;
}
/* Poll for readying the recv */
POLLFD pfds[1] = { { .fd = sfd, .events = POLLIN } };
/* Read responses and append to resbuff until connection is closed */
do
{
if (poll(pfds, sizeof(pfds) / sizeof(pfds[0]), POLL_TIMEOUT) == 0)
{
/* Timeout */
return false;
}
/* Extend the buffer if at limit */
if (idx == *len && !extend_resbuff(resbuff, len))
{
/* extend_resbuff failed */
return false;
}
if (pfds[0].revents & POLLIN)
{
/* Ready to read */
stat = recv(sfd, *resbuff + idx, *len - idx, 0);
idx += (size_t)stat;
}
else if (pfds[0].revents & POLLHUP)
{
/* Connection closed on remote side - response is most likely all read */
/*
I have noticed linux does not reach this even when response is over
recv, just keeps executing and it keeps returning 0
which is why the loop exits when recv is 0
However, on windows (WSAPoll instead of poll) - this branch is triggered
*/
break;
}
else
{
/*
Is it safe to assume an errno is set in this branch?
The caller is then expected to check the errno
If this branch is hit, is recovery possible (within the scope
of this function)?
*/
return false;
}
/*
This loop exits either when
* Full response is received and connection is closed (stat is 0)
* stat is SOCKET_ERROR but errno **is not** EAGAIN or EWOULDBLOCK or EINTR
*/
} while (stat > 0 && (stat != SOCKET_ERROR || errno_is_ok));
/*
Trim resbuff to exactly the size it needs to be (only if stat is not -1)
the following returns true only if everything succeeds
(trim_resbuff will not be called if stat is SOCKET_ERROR in the first place)
*/
return stat != SOCKET_ERROR && trim_resbuff(resbuff, idx, len);
}
</code></pre>
<p>My primary doubts can be seen in form of comments in my code. Also, not necessarily regarding the code in question but are there any socket options I should change that may make these operations more efficient? Options such as <code>TCP_NODELAY</code>, <code>TCP_QUICKACK</code>, <code>SO_RCVBUF</code>, and <code>SO_SNDBUF</code>. Are the default values for these options good enough?</p>
<p><strong>Note</strong>: Performance, even microseconds (not milli), is crucial for this specific implementation. Although that does not mean implementing <code>epoll</code> (for linux) and/or an async event loop. I just want the best performance possible using <code>poll</code> and non blocking sockets :)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T11:43:17.333",
"Id": "490492",
"Score": "0",
"body": "Is this example code or taken from a real project? Please take a look at the [help/on-topic]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T13:21:18.693",
"Id": "490498",
"Score": "0",
"body": "@Mast it is a part of a library I'm working on. A real project certainly, but unreleased as of now and certainly by me :). I tried to make it as complete as possible without having to include 10+ source files"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T17:55:11.240",
"Id": "490525",
"Score": "1",
"body": "You are not using `poll()` correctly. You use poll to listen to many sockets (if there is no data available on the socket you do other work). I would expect a single thread to be running a poll in a loop. Any sockets that have work generate a work item that is handled by a separate thread (or more generally an active thread pool)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T17:56:23.050",
"Id": "490528",
"Score": "1",
"body": "The way you are using i totally wastes the non blocking nature of the socket as you ae blocking on the poll call instead. You may as well simply use `read()` and `write()` directly on blocking sockets as you will get the same results with less complicated code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T18:16:07.770",
"Id": "490530",
"Score": "0",
"body": "@MartinYork I realize `poll` is better utilized for multiple sockets. However, I wanted to avoid busy looping using `send` and `recv` since that would hog cpu time. Should I run the poll on a separate thread, with a callback passed in to call once the function finishes?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T18:22:04.317",
"Id": "490531",
"Score": "1",
"body": "You have swapped busy looping on send/recv for busy looping on poll (though you just give instead of actually looping)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T18:22:07.870",
"Id": "490532",
"Score": "1",
"body": "`Should I run the poll on a separate thread`: This is a an easy design to do, but you could do it without the thread (ie you set up a lot of reads/writes and then poll until all are done). `callback passed in to call once the function finishes`: That again is a good simple way to do it (though you may want to be able to partially processes the data as it comes along rather than waiting for everything, ie.. web browser can often start displaying some of the page before the full thing is downloaded)."
}
] |
[
{
"body": "<h1>Overview</h1>\n<p>I don' think the way you are using <code>poll()</code> is affective. You are basically moving the busy loop from <code>send()</code>/<code>recv()</code> to the <code>poll()</code> function but then giving up when there is a timeout.</p>\n<p>If your socket is on loopback that may work great but anything coming across the internet is going to potentially have long waits at some point thus causing your reads to be abandoned and never resumed.</p>\n<h3>how I would structure it:</h3>\n<pre><code> void pollLoop()\n {\n bool finished = false;\n do { \n int count = poll(/* Very short sleep or use signal to force dropout*/);\n if (count < 0) {\n handleError();\n }\n for(int loop = 0;loop < count; ++loop) {\n handleSocket(loop);\n }\n getNewSocketsThatHaveBeenAdded();\n }\n while(!finished);\n }\n\n void addSocket(int socket, int type /*read or write */, callback, callbackdata)\n {\n lockGlobalMutexForSocket();\n AddInfoToSo_getNewSocketsThatHaveBeenAdded_PicksItUp();\n unlockGlobalMutex();\n // Optionally create a signal so poll() drops out of sleep\n }\n\n void getNewSocketsThatHaveBeenAdded()\n {\n lockGlobalMutexForSocket();\n // Add data stored by addSocket to data structure used by poll\n // This may be basically a null op.\n // As long as there is no reallocation the above function can\n // simply append socket information this function will result\n // in the size of the structured used by poll() being larger\n // i.e. parameter 2 in poll() `nfds` increases.\n unlockGlobalMutex();\n }\n\n void handleSocket(loop)\n {\n // Important.\n // Set the appropriate fd to negative in the poll structure\n // so that poll does not report on this socket while you\n // are handling it.\n fd[loop].fd = -fd[loop].fd; // You flip it back when you are done.\n\n if (fd[loop].dataAvailable) {\n AddToThreadPool(readOrWriteDataAsAppropriate, loop);\n }\n else /* No data available we have reached the end */\n AddToThreadPool(callSocketCallBackWithData, loop);\n }\n }\n \n</code></pre>\n<p>This the basic for most servers (though I would use libevent personally rather than <code>poll()</code> or <code>ppoll()</code>). With this type of structure a handfull of threads can easily handle 10's of thousands of simultaneous connection.</p>\n<h1>Code Review</h1>\n<p>Does C support <code>bool</code>? I though that was C++. I though the C version was slightly different?</p>\n<pre><code>bool send_all(socket_t sfd, char const* restrict msg, ssize_t msglen)\n</code></pre>\n<hr />\n<p>This must be modern C syntax.<br />\nHeard about it not seen it before.</p>\n<pre><code> POLLFD pfds[1] = { { .fd = sfd, .events = POLLOUT } };\n</code></pre>\n<hr />\n<p>You <code>nfds</code> is always 1!</p>\n<pre><code> if (poll(pfds, sizeof(pfds) / sizeof(pfds[0]), POLL_TIMEOUT) == 0)\n</code></pre>\n<hr />\n<p>Basically you will give up if there is any significant delay. But you don't return any information about how far you got. So it is not possible to resume. If you are going to do it this way then this failure should give you the opportunity to resume by including return data about how far you got.</p>\n<pre><code> {\n /* Timeout */\n return false;\n }\n</code></pre>\n<hr />\n<p>You don't check for negative values from <code>poll()</code>. Sometimes there will be an error (or signal) you need to check for these.</p>\n<hr />\n<p>You don't check for errors on <code>send()</code>. You need to do that.</p>\n<pre><code> stat = send(sfd, msg + sent, msglen - sent, 0);\n</code></pre>\n<hr />\n<p>Well it better be a <code>OUT</code> signal since you are sending data. But don't you all expect there at some point to be a response on the same socket? With the current implementation you need to complete the send before you start receiving data. What happens if the server on the other end starts to send data before you have finished sending your data? Not all operations require all the data before they can start responding!</p>\n<pre><code> if (pfds[0].revents & POLLOUT)\n</code></pre>\n<hr />\n<p>You should be explicitly checking for an error.</p>\n<pre><code> else\n {\n /*\n Is it safe to assume an errno is set in this branch?\n The caller is then expected to check the errno\n\n If this branch is hit, is recovery possible (within the scope\n of this function)?\n */\n return false;\n }\n</code></pre>\n<hr />\n<p>This is fine.</p>\n<pre><code> } while (sent < msglen && (stat != SOCKET_ERROR || errno_is_ok));\n</code></pre>\n<p>There are several types of error that are not actually errors and you simply try again().</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T08:31:35.903",
"Id": "490576",
"Score": "0",
"body": "thanks! One question about \"completing the send before receiving the data\": Do HTTP servers start sending data before they have actually read the full HTTP request from remote side?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T16:37:31.173",
"Id": "490633",
"Score": "0",
"body": "@Chase I don't actually know. But I don't see why not. If you know the response you don't need to wait for the full message for a reply. Example form validation. You may fail validation very quickly but the form can contain an arbitrary amount of information. There is no need to wait until you have the whole form before starting a reply with an error response if it is quick."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T16:37:33.793",
"Id": "490634",
"Score": "0",
"body": "Or security validation based on the header information you can quickly send a not authorized after the headers are received without needing to know the body. You still need to read the rest of the body as the connection is going to be reused for the next request."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T19:00:47.893",
"Id": "250091",
"ParentId": "250073",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "250091",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T11:25:07.200",
"Id": "250073",
"Score": "1",
"Tags": [
"c",
"networking",
"socket",
"c99"
],
"Title": "Feedback on send/recv functions for non blocking sockets in client side HTTP library"
}
|
250073
|
<p>I want to know if my SCSS code looks correct.<br />
Note: Everything works as I expected. The Main Idea of this code is to generate Word Break Utilities for controlling word breaks in an element.<br />
using SCSS mean I can declare only css classes in html element.</p>
<p><strong>here is the result of my code :</strong></p>
<pre><code>.break-normal {
overflow-wrap: normal;
word-break: normal;
}
.break-words {
overflow-wrap: break-word;
}
.break-all {
word-break: break-all;
}
.truncate {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
</code></pre>
<p><strong>My SCSS CODE :</strong></p>
<pre><code>$wordBreak: (
"break-normal": normal,
"break-words": break-word,
"break-all": break-all,
"truncate": (
"overflow": hidden,
"text-overflow": ellipsis,
"white-space": nowrap
),
) !default;
@each $wordBreakClassName , $wordBreakType in $wordBreak {
@if ($wordBreakClassName) == "break-normal" {
.#{$wordBreakClassName} {
overflow-wrap: $wordBreakType;
word-break: $wordBreakType;
}
}
@else if ($wordBreakClassName) == "break-words" {
.#{$wordBreakClassName} {
overflow-wrap: $wordBreakType;
}
}
@else if ($wordBreakClassName) == "break-all" {
.#{$wordBreakClassName} {
word-break: $wordBreakType;
}
}
@else if ($wordBreakClassName) == "truncate" {
.#{$wordBreakClassName} {
overflow: map-get(map-get($wordBreak, truncate), overflow);
text-overflow: map-get(map-get($wordBreak, truncate), text-overflow);
white-space: map-get(map-get($wordBreak, truncate), white-space);
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-06T21:37:42.237",
"Id": "491073",
"Score": "1",
"body": "Could you explain why you are using SASS here at all? The SASS code is more conplicated and difficult to understand that the created CSS."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T13:18:53.307",
"Id": "250074",
"Score": "2",
"Tags": [
"sass",
"layout"
],
"Title": "Utility classes to control word breaks"
}
|
250074
|
<p>I am trying to build this view model that has a ChildViewModel and this was the only way I was able to get it working. Any advice on how to make this code; cleaner, more effective, just overall better! It’s just the adding to view model that will need to be reviewed the other section is to create the mock up.</p>
<pre><code> static void Main(string[] args)
{
try
{
//Setup Database object
List<Subscription> ListOfSubscription = new List<Subscription>();
ListOfSubscription.Add(new Subscription() { SubscriptionId = 1, ParentProductId = 4, ChildProductId = 4 , ParentProductName = "Product 1", ChildProductName = "Product 1", GroupId = 362 });
ListOfSubscription.Add(new Subscription() { SubscriptionId = 2, ParentProductId = 114, ChildProductId = 1, ParentProductName = "Product 2", ChildProductName = "Product 3", GroupId = 1 });
ListOfSubscription.Add(new Subscription() { SubscriptionId = 3, ParentProductId = 114, ChildProductId = 2, ParentProductName = "Product 2", ChildProductName = "Product 4",GroupId = 1 });
//Review Section of the Code
var groupedListOfSubscription = ListOfSubscription.GroupBy(u => u.GroupId).ToList();
List<SubscriptionViewModel> SubscriptionViewModel = new List<SubscriptionViewModel>();
foreach (var record in groupedListOfSubscription)
{
int groupId = record.Key;
var SelectListofSubscription = ListOfSubscription.Where(w=> w.GroupId == groupId).ToList();
foreach (var subscription in SelectListofSubscription)
{
SubscriptionViewModel svm = new SubscriptionViewModel();
if (subscription.ParentProductId == subscription.ChildProductId)
{
svm.ParentProductId = subscription.ParentProductId;
svm.SubscriptionIds = subscription.SubscriptionId.ToString();
svm.GroupId = subscription.GroupId;
svm.ParentProductName = subscription.ParentProductName;
SubscriptionViewModel.Add(svm);
}
else
{
svm.ParentProductId = subscription.ParentProductId;
svm.GroupId = subscription.GroupId;
svm.ParentProductName = subscription.ParentProductName;
var SelectChildListofSubscription = ListOfSubscription.Where(w => w.GroupId == groupId).ToList();
StringBuilder builderSubscriptionIds = new StringBuilder();
List<SubscriptionChildViewModel> _scvm = new List<SubscriptionChildViewModel>();
foreach (var child in SelectChildListofSubscription)
{
builderSubscriptionIds.Append(child.ChildProductName);
builderSubscriptionIds.Append(",");
_scvm.Add(new SubscriptionChildViewModel()
{
ChildProductId = child.ChildProductId,
ChildProductName = child.ChildProductName
});
}
svm.ListOfSubscriptionChild = _scvm;
svm.SubscriptionIds = builderSubscriptionIds.ToString();
SubscriptionViewModel.Add(svm);
}
}
}
}
catch (Exception ex)
{
ex.ToString();
}
}
class Subscription
{
public int SubscriptionId { get; set; }
public int ParentProductId { get; set; }
public string ParentProductName { get; set; }
public string ChildProductName { get; set; }
public int ChildProductId { get; set; }
public int GroupId { get; set; }
public DateTime? EndDate { get; set; }
}
class SubscriptionViewModel
{
public int SubscriptionId { get; set; }
public int ParentProductId { get; set; }
public string ParentProductName{ get; set; }
public string SubscriptionIds { get; set; }
public int GroupId { get; set; }
public List<SubscriptionChildViewModel> ListOfSubscriptionChild { get; set; }
}
class SubscriptionChildViewModel
{
public string ChildProductName { get; set; }
public int ChildProductId { get; set; }
}
</code></pre>
<p>Output</p>
<pre><code><Subscription>
<Parent>Product 1</Parent>
<ProductId>4</ProductId>
<SubscriptionIds Ids="1" />
</Subscription>
<Subscription>
<Parent>Product 2</Parent>
<ProductId>114</ProductId>
<SubscriptionIds Ids="2,3" />
<Children>
<Child Name="Product 3">
<ChildProductId>1</ChildProductId>
</Child>
<Child Name="Product 4">
<ChildProductId>2</ChildProductId>
</Child>
</Children>
</Subscription>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T14:30:07.833",
"Id": "490509",
"Score": "4",
"body": "In my humble opinion, `ListOfSubscription` is naming in the style of Hungarian notation at its worst. I would give the `subscriptions` name (in the plural)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T18:15:57.347",
"Id": "490652",
"Score": "1",
"body": "*//review this section of code*. My previous answer is 100% applicable. This section, its length, complexity, harder than it needs to be to read and understand, the `try` covering all of it because functionality is shotgunned all over that block, ... all are symptoms of the foundational design. Code Review rules ask for complete, working code postings so accurate assessments can be made. No code can live in a vacuum."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T18:43:14.387",
"Id": "490654",
"Score": "0",
"body": "I am not sure what to do with that answer its very high level. The database is flat and I am trying to add it to a view model. the code is working just wanted to see what improvements can be made?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T22:22:33.350",
"Id": "490684",
"Score": "0",
"body": "I added to my answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-07T06:58:48.320",
"Id": "491090",
"Score": "0",
"body": "Is the code really correct? If I run it I get three `SubscriptionViewModel`s with `SubscriptionId` = 0 and the latter two are identical (having `Product 3,Product 4,`). It would help to see your expected output."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-07T12:30:21.707",
"Id": "491122",
"Score": "0",
"body": "@gert-arnold I updated with the output that I am looking for it should just have two records in `SubscriptionViewModel`"
}
] |
[
{
"body": "<p><strong>Database design vs Object Oriented Class Design</strong></p>\n<p>The code has a look and feel of "database think" not Object Oriented think. Often the database schema <em>naturally</em> overlaps the code classes but that should never be an explicit class design criteria. This code is not object oriented in the least. Reasons why:</p>\n<ul>\n<li>all classes have no methods - just like database tables.</li>\n<li>parent objects are instantiated with child properties. This implies that a parent object cannot exist unless it already has children.</li>\n<li>child properties are passed to parents but the child object does not exist.</li>\n<li>no constructors. Constructor parameters force client code to supply the minimal required properties for a valid object. Constructor overloads can make more complex instantiations easier.</li>\n<li>classX properties exist also as ClassY instance properties.</li>\n<li>The client code, <code>Main()</code>, does all functionality to and for all other classes - just like SQL does for tables.</li>\n</ul>\n<hr />\n<p><strong>Good OO classes hide state and expose functionality</strong></p>\n<ul>\n<li>Without constructors client code cannot guarantee bug free objects without knowing about every property and how each is used anywhere and everywhere after creation.</li>\n<li>Without constructors the created object cannot guarantee to the client code that it is in a valid, bug free state.</li>\n<li>A sure candidate for a method: anywhere client code applies conditional logic directly on another class' property.</li>\n<li>The View classes should contain whole data objects, not disconnected object properties. The View will have its own methods/properties for exposing the encapsulated data objects as and how desired.</li>\n</ul>\n<hr />\n<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0394800184\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\"><strong>Are You My Mother?</strong></a></p>\n<p>In the children's book the baby bird asks each animal it meets, "are you my mother?". If this book was about OO, the title would be <code>aPuppy.IsParent(babyBird)</code>. In contrast, our version has <code>Main</code>()` strapping down the helpless tiny bird and puppy, alien probing their DNA.</p>\n<hr />\n<p><strong>.NET Collections</strong></p>\n<p>There is lots of magic built into .NET collection classes. You can leverage <code>Add()</code>, <code>Contains()</code>, <code>Find()</code>, <code>Sort()</code> and more if you design the "collected" class right. For a <code>Subscriptions</code> list for example, in <code>Subscription</code> class override <code>Equals</code> and <code>CompareTo()</code>. You really must read the MSDN documentation.</p>\n<p>The volume of collection classes MSDN documentation is stunning, but just focus on "equals" and/or "compareTo". You do not have to implement or override the brazillion interfaces and virtual methods.</p>\n<p>The grouping and filtering LINQ can then be put into <code>Subscriptions</code> class which is where it belongs, with methods like <code>SortThisWay(...)</code></p>\n<pre><code> class Subscription : IEquatable<Subscription> {\n public bool Equals( Subscription thatOne ) {\n if ( thatOne == null ) return false;\n if ( this.Id = thatOne.Id ) return true;\n return false;\n }\n }\n\n class Subscriptions : List<Subscription> {\n public bool Add( thisSubscription ) {\n if ( thisSubscription == null ) return false;\n\n // uses Subscription.Equals in the background.\n if ( this.Contains( thisSubscription ) return false;\n\n this.Add( thisSubscription );\n return true;\n }\n\n public Subscription FindById( thisSubscription ) {\n this.Find( x => x.Equals( thisSubscription )\n }\n\n }\n</code></pre>\n<hr />\n<p><strong>Edit</strong></p>\n<blockquote>\n<p>I am not sure what to do with that answer its very high level. The database is flat and I am trying to add it to a view model.</p>\n</blockquote>\n<hr />\n<p>not this:</p>\n<pre><code>foreach (var subscription in SelectListofSubscription)\n {\n SubscriptionViewModel svm = new SubscriptionViewModel();\n if (subscription.ParentProductId == subscription.ChildProductId)\n {\n svm.ParentProductId = subscription.ParentProductId;\n svm.SubscriptionIds = subscription.SubscriptionId.ToString();\n svm.GroupId = subscription.GroupId;\n svm.ParentProductName = subscription.ParentProductName;\n SubscriptionViewModel.Add(svm);\n }\n else\n {\n svm.ParentProductId = subscription.ParentProductId;\n svm.GroupId = subscription.GroupId;\n svm.ParentProductName = subscription.ParentProductName;\n var SelectChildListofSubscription = ListOfSubscription.Where(w => w.GroupId == groupId).ToList();\n StringBuilder builderSubscriptionIds = new StringBuilder();\n List<SubscriptionChildViewModel> _scvm = new List<SubscriptionChildViewModel>();\n foreach (var child in SelectChildListofSubscription)\n {\n builderSubscriptionIds.Append(child.ChildProductName);\n builderSubscriptionIds.Append(","); \n _scvm.Add(new SubscriptionChildViewModel()\n {\n ChildProductId = child.ChildProductId,\n ChildProductName = child.ChildProductName\n });\n }\n svm.ListOfSubscriptionChild = _scvm;\n svm.SubscriptionIds = builderSubscriptionIds.ToString();\n SubscriptionViewModel.Add(svm);\n }\n }\n</code></pre>\n<p>this</p>\n<pre><code>Subscriptions mySubscriptions = new Subscriptions();\n// assume all objects and collection are created\n\nSubscrptionsVMs my SubscriptionsVMs = new SubscriptionsVMs();\n// assume all objects are created.\n\n\nmySubscriptionVMs.Add(mySubscriptions);\n\n// that's all folks!\n</code></pre>\n<p>------- The above courtesy of the following -------</p>\n<p>.</p>\n<ul>\n<li>The view model object has a subscription object</li>\n<li>view model properties pass through the subscription properties. They are transformed as needed for the VM. There could be several "forms" of a property, as needed.</li>\n<li>I don't know if Subscription children are "products" or "subscriptions", or what.</li>\n<li>much of the original nested code goes away because the view models hold the entire object instead of "cutting out" a sub-set of a subscriptions object.</li>\n<li>if a given VM does not use a certain Subscription property, then just ignore it. Don't create a matching pass-through property.</li>\n<li>GroupId - note how the original object, a Subscription, returns the value untouched. It is up to the view model to transform it as desired. And note how that logic is distributed between the view model and view model collection.</li>\n</ul>\n<p>.</p>\n<pre><code>public class SubscriptionsVMs : IEnumerable<List<SubscriptionVM>> {\n protected List<SubscriptionVM> theScripts {get; set;}\n\n public string GroupIds() {\n Stringbuilder groupIds = new Stringbuilder();\n \n forEach(var script in theScripts) {\n groupIds.Append(script.Id + ",");\n }\n\n return groupIds.ToString();\n }\n\n // for client code to "forEach" SubscriptionsVMs collection we need to implement IEnumerable<T> - this one method, that's it.\n // List<T> already implements an Enumerator.\n public IEnumerator<List<SubscriptionVM>> GetEnumerator() {\n return theScripts.GetEnumerator();\n }\n\n public bool Add(SubscriptionVM thisGuy) {\n if( thisGuy == null ) return false;\n \n theScripts.Add(thisGuy);\n return true;\n } \n\n public bool Add(SubscriptionVMs these) {\n if( these == null ) return false;\n \n theScripts.Add(these);\n return true;\n } \n\n\n public bool Add(Subscriptions theseGuys) {\n if( theseGuys == null ) return false;\n\n forEach(Subscription guy in theseGuys) {\n if( guy == null ) continue;\n Add(new SubscriptionVM( guy ))\n }\n\n return true;\n }\n}\n\n\npublic class SubscriptionVM {\n protected Subscript theSubscription {get; set;}\n\n public SubscriptionVM(Subscription thisGuy ) {\n if( thisGuy = null ) { // throw ArgumentNullException }\n\n theSubscription = thisGuy;\n }\n\n\n // I assume the basic VM wants it as a string\n public string GroupId { return theSubscription.GroupId.ToString(); }\n\n public in ParentProductId { return theSubscription.ParentProductId; }\n // and so on\n\n public SubscriptionVM ( Subscription aSubscript ) {\n if ( aSubscript = null ) { \n // throw ArguementNullException\n }\n\n this.theSubscription = aSubscript\n }\n} //class SubscriptionVM\n\n\npublic class Subscriptions {\n // constructor not shown\n protected List<Subscription> theSubscriptions {get; set;}\n\n public List<int> GroupIds() {\n List<int> groupies = new List<int>();\n\n forEach (var subscript in theSubscriptions) {\n groupies.Append(subscript.GroupId);\n }\n\n return groupies;\n }\n\n // for client code to "forEach" Subscriptions collection we need to implement IEnumerable<T> - this one method, that's it.\n // List<T> already implements an Enumerator.\n public IEnumerator<List<Subscription>> GetEnumerator() {\n return theSubscriptions.GetEnumerator();\n } \n} // class Subscriptions\n\n\npublic class Subscription : IEquatable<Subscription> {\n // constructor not shown\n\n public Subscriptions Children {get; protected set;}\n\n // my guess as to what comparing these Ids means.\n // Testing Children collection for empty would be good\n public bool HasChildren() {\n return this.ParentProductId == this.ChildProductId ? false : true;\n }\n}\n</code></pre>\n<p><strong>end Edit</strong></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T10:37:37.200",
"Id": "490592",
"Score": "1",
"body": "[Do not inherit from List<T>](https://stackoverflow.com/a/21694054/958732)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T12:25:33.500",
"Id": "490600",
"Score": "0",
"body": "@Johnbot Maybe something was lost in translation but to quote that answer \"\"Is inheriting from List<T> always unacceptable?\" Unacceptable to who? Me? No.\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T17:50:41.953",
"Id": "490647",
"Score": "0",
"body": "@Johnbot, yeah, I was lazy. In real life I *always* use composition creating custom collections. I want a very DSL api. And leaving all those `List<T>`methods exposed also makes it easy too easy, and tempting(!), for client code to screw things up."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-05T12:51:12.293",
"Id": "490896",
"Score": "0",
"body": "@radarbob I tried to create your view model but getting error related to Subscript? `https://dotnetfiddle.net/XamjC0`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-05T19:42:39.400",
"Id": "490952",
"Score": "0",
"body": "it's a typo. the type should be \"Subscription\" NOTE: `protected Subscript theSubscription {get; set;}` - I declared it, misspelled it. The intent is to instantiate it in a constructor."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-08T07:34:04.717",
"Id": "491202",
"Score": "0",
"body": "IMO, the \"database think\" is justified here, because in reality I think the class mode is part of an ORM's client-side model, so it's part of a data layer and should not be confused with a domain model. The primary responsibility of an ORM's class model is to offer smooth data access, not business logic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T23:14:23.903",
"Id": "493332",
"Score": "0",
"body": "A **data layer** transforms/maps DB records into domain model objects. ORM is a particular mechanism for doing that. The **ViewModel** maps the domain objects to the UI. These layers decouple the **domain model** from any particular DB or UI. How to access domain objects should be built into the domain classes, not in the \"bridging code\". But that's what's going on here. ....."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T23:31:39.857",
"Id": "493333",
"Score": "0",
"body": "cont. ... The OP code should create the ViewModel objects directly. `Subscription` is nothing because it does nothing and its properties are simply duplicates of ViewModel classes. If there is an actual business model then `Subscription` must mean something to software users. It must be something and do stuff. I should be able to create objects, add to collections, filter collections with provided domain class functionality (methods). Who goes to a restaurant, takes over the kitchen and cooks their own food? What then is the purpose of a restaurant?"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T19:40:17.643",
"Id": "250092",
"ParentId": "250076",
"Score": "6"
}
},
{
"body": "<p>The code pattern <code>var x = new List<X>()</code> followed by a <code>foreach</code> adding to that list is always a telltale that LINQ will probably make things easier and more comprehensible.</p>\n<p>Your code is not exception to that rule. I'll show you how this can be done quite concisely using LINQ and then explain a few things:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>var groupedSubscriptions = subscriptions.GroupBy(u => u.GroupId);\n\nvar result = groupedSubscriptions.Select(grp1 => new\n{\n GroupId = grp1.Key,\n Subscriptions = grp1.GroupBy(subscr => new \n { \n subscr.ParentProductId, \n subscr.ParentProductName \n })\n .Select(grp2 => new SubscriptionViewModel\n {\n GroupId = grp1.Key,\n ParentProductId = grp2.Key.ParentProductId,\n ParentProductName = grp2.Key.ParentProductName,\n SubscriptionIds = string.Join(",", grp2.Select(y => y.SubscriptionId)),\n ListOfSubscriptionChild = grp2\n .Where(subsc => subsc.ChildProductId != grp2.Key.ParentProductId)\n .Select(subsc => new SubscriptionChildViewModel\n {\n ChildProductId = subsc.ChildProductId,\n ChildProductName = subsc.ChildProductName\n })\n .ToList()\n })\n});\n</code></pre>\n<p>In Linqpad, the final result, <code>result.SelectMany((s => s.Subscriptions)</code> shows this:</p>\n<p><a href=\"https://i.stack.imgur.com/tnR7O.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tnR7O.png\" alt=\"result\" /></a></p>\n<p>Remarks:</p>\n<ul>\n<li>I used prevailing naming conventions (<code>subscriptions</code> is your <code>ListOfSubscription </code>).</li>\n<li>You only grouped by <code>GroupId</code> and omitted a second required grouping level, <code>ParentProductId</code>. So I added a nested grouping by <code>ParentProductId</code> which I accompanied by <code>ParentProductName</code> to have a <code>Key</code> that can readily be used for the view model properties. And both properties should be always be coupled, right?</li>\n<li>As you see, populating <code>ListOfSubscriptionChild</code> is just a subquery on the nested grouping. No need to loop through <code>SubscriptionViewModel</code>s to populate their child lists.</li>\n</ul>\n<p>A note on architecture:</p>\n<p>In a remark you say "The database is flat", which probably means it presents the source data shaped like your <code>ListOfSubscription</code>. I probably don't have to explain to you that this is not well normalized, like not at all. Especially the redundant product names are a nuisance an a possible source of errors and ambiguity. If you have even the slightest chance of improving this database model, go for it. The database should be able to readily produce the data more or less in the form of the end result.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-09T14:48:39.070",
"Id": "491346",
"Score": "0",
"body": "Can I flattened this and just return the SubscriptionViewModel `var flattenedresult = result.SelectMany(grp => grp.AsEnumerable()).ToList();`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-09T15:07:50.593",
"Id": "491348",
"Score": "0",
"body": "I get this AnonymousType and not the SubscriptionViewModel"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-09T15:09:23.957",
"Id": "491349",
"Score": "1",
"body": "Yes, that's why you need the syntax `result.SelectMany(s => s.Subscriptions)`. `s` is an anonymous type here. (Or `grp` in your code)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-29T13:27:17.320",
"Id": "494644",
"Score": "0",
"body": "what if I wanted to check OriginalSubscriptionId is null? Would I add it to `grp1.GroupBy`? They are different numbers so I dont think it would work ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-29T13:37:42.707",
"Id": "494646",
"Score": "0",
"body": "would something like this work `(grp2.Select(y => y.OriginalSubscriptionId).Count() > 0) ? null :string.Join(\",\", grp2.Select(y => y.OriginalSubscriptionId))`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-29T14:02:40.957",
"Id": "494647",
"Score": "0",
"body": "Looks like that should work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-29T16:14:41.903",
"Id": "494669",
"Score": "0",
"body": "This displays the CustomerId when the OriginalSubscriptionId is 0 `SubscriptionIds = (grp2.Select(y => y.OriginalSubscriptionId).Count() == 0) ? null : (string.Format(\"{0},{1}\", string.Join(\",\", grp2.Select(y => y.OriginalSubscriptionId)), grp2.Key.CustomerId)),`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-29T16:31:25.427",
"Id": "494672",
"Score": "0",
"body": "It's a bit hard to do follow-up questions in comments. I'm not even sure if you're asking something in the last comment. I think what you bring up here should be asked in a Stack Overflow question where you can give all required details of what you want to achieve."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-07T19:38:57.253",
"Id": "250336",
"ParentId": "250076",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "250336",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T13:55:41.320",
"Id": "250076",
"Score": "6",
"Tags": [
"c#",
"linq"
],
"Title": "c# list object with view model child list"
}
|
250076
|
<p>I have made a program that sort of mimics YouTube trending, but only with videos from channels that I am subscribed to. It looks at each <a href="https://developers.google.com/resources/api-libraries/documentation/youtube/v3/java/latest/com/google/api/services/youtube/model/Subscription.html" rel="nofollow noreferrer"><code>Subscription</code></a>, converts the subscription to a <a href="https://developers.google.com/resources/api-libraries/documentation/youtube/v3/java/latest/com/google/api/services/youtube/model/Channel.html" rel="nofollow noreferrer"><code>Channel</code></a>, gets the channel's uploads <a href="https://developers.google.com/resources/api-libraries/documentation/youtube/v3/java/latest/com/google/api/services/youtube/model/Playlist.html" rel="nofollow noreferrer"><code>PlayList</code></a>, converts each <a href="https://developers.google.com/resources/api-libraries/documentation/youtube/v3/java/latest/com/google/api/services/youtube/model/PlaylistItem.html" rel="nofollow noreferrer"><code>PlayListItem</code></a> to a <a href="https://developers.google.com/resources/api-libraries/documentation/youtube/v3/java/latest/com/google/api/services/youtube/model/Video.html" rel="nofollow noreferrer"><code>Video</code></a>, and finally filters the videos to only include new uploads and then sorts by views.</p>
<p>It works, I guess, but is so painfully slow that the app is unusable. Manually looping through everything takes too much time. I am subscribed to too many channels, and each channel has too many uploads. I tried to shed time by replacing loops with streams where I could, but it doesn't really help.</p>
<p>The primary class in the program, and the only one I will be posting here, is <code>APICaller.java</code>.</p>
<pre class="lang-java prettyprint-override"><code>import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class APICaller {
private static final String CLIENT_SECRETS = "client_secret.json";
private static final Collection<String> SCOPES =
Collections.singletonList("https://www.googleapis.com/auth/youtube.readonly");
private static final String APPLICATION_NAME = "Better YouTube Trending";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
public static List<Video> generateVideos() throws IOException, GeneralSecurityException {
YouTube youtubeService = getService();
List<Subscription> subscriptions = getSubscriptions(youtubeService);
List<String> playLists = getPlayLists(youtubeService, subscriptions);
List<PlaylistItem> playlistItems = getPlayListItems(youtubeService, playLists);
List<Video> videos = getVideos(youtubeService, playlistItems);
videos.sort(APICaller::comparison);
return videos;
}
private static YouTube getService() throws GeneralSecurityException, IOException {
final NetHttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
Credential credential = authorize(httpTransport);
return new YouTube.Builder(httpTransport, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME)
.build();
}
private static Credential authorize(final NetHttpTransport httpTransport) throws IOException {
// Load client secrets.
InputStream in = APICaller.class.getResourceAsStream(CLIENT_SECRETS);
GoogleClientSecrets clientSecrets =
GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow =
new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY, clientSecrets, SCOPES)
.build();
return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}
private static List<Subscription> getSubscriptions(YouTube youtubeService) throws IOException {
List<Subscription> subscriptions = new ArrayList<>();
YouTube.Subscriptions.List request = youtubeService.subscriptions().list("snippet");
SubscriptionListResponse response;
String nextPageToken = "";
for (boolean first = true; nextPageToken != null; first = false) {
if (first) {
response = request.setMine(true)
.setMaxResults(50L)
.execute();
} else {
response = request.setMine(true)
.setPageToken(nextPageToken)
.setMaxResults(50L)
.execute();
}
subscriptions.addAll(response.getItems());
nextPageToken = response.getNextPageToken();
}
return subscriptions;
}
private static List<String> getPlayLists(YouTube youtubeService, List<Subscription> subscriptions) throws IOException {
List<String> playLists = new ArrayList<>();
YouTube.Channels.List request = youtubeService.channels().list("contentDetails");
subscriptions.forEach(s -> {
try {
String id = s.getSnippet().getResourceId().getChannelId();
ChannelListResponse response = request.setId(id).execute();
playLists.add(response.getItems().get(0).getContentDetails().getRelatedPlaylists().getUploads());
} catch (IOException e) {
e.printStackTrace();
}
});
return playLists;
}
private static List<PlaylistItem> getPlayListItems(YouTube youtubeService, List<String> playLists) throws IOException {
List<PlaylistItem> videos = new ArrayList<>();
YouTube.PlaylistItems.List request = youtubeService.playlistItems().list("snippet");
playLists.forEach(playlist -> {
try {
PlaylistItemListResponse response;
String nextPageToken = "";
for (boolean first = true; nextPageToken != null; first = false) {
if (first) {
response = request.setPlaylistId(playlist)
.setMaxResults(50L)
.execute();
} else {
response = request.setPlaylistId(playlist)
.setPageToken(nextPageToken)
.setMaxResults(50L)
.execute();
}
videos.addAll(response.getItems());
nextPageToken = response.getNextPageToken();
}
} catch (IOException e) {
e.printStackTrace();
}
});
return videos;
}
private static List<Video> getVideos(YouTube youtubeService, List<PlaylistItem> playlistItems) throws IOException {
List<Video> videos = new ArrayList<>();
YouTube.Videos.List request = youtubeService.videos().list("snippet,statistics");
playlistItems.forEach(playlistItem -> {
String id = playlistItem.getSnippet().getResourceId().getVideoId();
try {
VideoListResponse response = request.setId(id).execute();
if (isNewVideo(response.getItems().get(0))) {
videos.add(response.getItems().get(0));
}
} catch (IOException e) {
e.printStackTrace();
}
});
return videos;
}
private static boolean isNewVideo(Video video) {
LocalDate publishedAt = LocalDate.parse(video.getSnippet().getPublishedAt().toString().substring(0, 10));
return ChronoUnit.DAYS.between(publishedAt, LocalDate.now()) < 7;
}
private static int comparison(Video video1, Video video2) {
return (int)(video1.getStatistics().getViewCount().longValue()) - (int)(video2.getStatistics().getViewCount().longValue());
}
}
</code></pre>
<p>The program is run by calling the one <code>public</code> method in the class: <code>generateVideos()</code>. You would need to use your own <code>client_secret.json</code> file, which you can download <a href="https://console.developers.google.com/apis/credentials" rel="nofollow noreferrer">here</a>. The method returns returns a <a href="https://docs.oracle.com/javase/8/docs/api/java/util/List.html" rel="nofollow noreferrer"><code>List</code></a> of videos, which would then be used elsewhere in the program to populate the GUI. I haven't included all that because it isn't really relevant to my question.</p>
<p>So, how would you improve this code? Are there any glaring inefficiencies, obvious mistakes, extraneous steps, and the like?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T09:16:09.697",
"Id": "490580",
"Score": "2",
"body": "I don't know youtube api, but it seems me you are making distinct requests limited to the first `50` results, so if you have a great number of items to retrieve this could explain why it is so slow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T09:52:49.930",
"Id": "490582",
"Score": "1",
"body": "If I read this correctly, you page throug *all* the results, never stopping until the very last page. How many results and how many calls for 50 items is this in total? How long does a single `list()` call take?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T12:49:48.910",
"Id": "490606",
"Score": "1",
"body": "@dariosicily The Youtube API only allows a maximum of 50 results with each response. You have to paginate through the whole thing in order to get all the results."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T13:42:26.443",
"Id": "490611",
"Score": "1",
"body": "I see, then if you have a great number of items you are obliged to do several calls of the API."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T13:54:02.457",
"Id": "490612",
"Score": "1",
"body": "@dariosicily I initially set it to return some absurdly large number of results with one call, but it always returned a maximum of 50 anyway. That led me to this on Stack Overflow: [Youtube API V3; Maximum number of videos only 50?](https://stackoverflow.com/questions/52803732/youtube-api-v3-maximum-number-of-videos-only-50)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-05T13:27:53.280",
"Id": "490905",
"Score": "1",
"body": "Did you tried to move the retrieval of playlists and videos of each subscription in a dedicated thread ? Also, if this will run on a schedule, you could save the last result so that you wont list items older than that one (like a message offset)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-05T13:51:38.133",
"Id": "490911",
"Score": "0",
"body": "@gervais.b My knowledge of how multithreading works is somewhat limited. Is there a way to run each step in separate threads, when each one requires data from the previous one? Or, more precisely, since the threads can't run simultaneously anyway, would multithreading help in this case?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-06T07:41:12.387",
"Id": "491006",
"Score": "0",
"body": "Threads can be seen as parts of your code that are executed \"in parallel\". But you can pass the parameters that you want. Why do you think that they \"can't run simultaneously\" ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-06T11:29:42.533",
"Id": "491018",
"Score": "0",
"body": "@gervais.b Maybe what I’m saying makes no sense, but if each of the method calls in `generateVideos` requires data from the previous one, I can’t run any until the previous one completes. Would putting them into separate threads still allow them to run simultaneously?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-06T12:16:05.470",
"Id": "491023",
"Score": "0",
"body": "You could generate one video per thread but that may be too much. At the first step you could try to move the creation of one playlist and children (PlaylistItem and Video) in one thread per subscription."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-06T13:00:41.507",
"Id": "491027",
"Score": "1",
"body": "@gervais.b I know next to nothing about Java multithreading. Any way you can write up a quick summary with some code as an answer? Thanks."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T14:21:24.797",
"Id": "250077",
"Score": "2",
"Tags": [
"java",
"performance",
"youtube"
],
"Title": "YouTube Data API v3: Modified version of YouTube trending that only includes videos from subscribed to channels"
}
|
250077
|
<p>I have come across a situation where I feel running some code in parallel will greatly improve performance, but I am concerned about the implementation and am looking for some confirmation. Take the following controller resources</p>
<pre><code>[HttpGet]
[Route("{id}")]
public IHttpActionResult Get(int id)
{
return Ok(_context.Get(id));
}
[HttpGet]
[Route("async/{id}")]
public async Task<IHttpActionResult> Get(int id)
{
return Ok(await _context.GetAsync(id));
}
</code></pre>
<p>The contents of Get(...) function are fairly straight forward. A WCF call is made using the passed id to retrieve document a object. That document object contains a list of associated material numbers for which I need to make a separate WCF call for each to gather additional data</p>
<pre><code>public DocumentModel Get(int id)
{
//Call to WCF service
DocumentModel model = _documents.Get(id);
//For each material, make a call to WCF service
//Potential for bottle neck due to possibility of large number of associated materials
foreach (Material material in model.Materials)
model.MaterialModels.Add(_materials.Get(material.Number));
return model;
}
</code></pre>
<p>It is worth noting that I am using a library developed and maintained by a colleague to call WCF services that are hosted on the same VM, so lets just say that I don't have access to modify this library for sake of the question. Retrieving a material looks like the following</p>
<pre><code>public MaterialModel Get(string number)
{
using(var client = new MaterialClient(out WcfResult result))
{
client.Get(number, out Material material, out Result result);
return new MaterialModel(material);
}
}
</code></pre>
<p>Everything works as expected, but as previously noted its possible for a significant number of materials to be returned (~20-60). Typically, I wouldn't encounter a problem like this since I would be utilizing HATEOAS and supplying the resource for each material in the DocumentModel object, however; this is an API for internal business use and the business requires all the data be in the response so I am left with little choice. So I made a separate implementation that will retrieve that material data in parallel</p>
<pre><code>public async Task<DocumentModel> GetAsync(int id)
{
//Call to WCF service
DocumentModel model = _documents.Get(id);
IEnumerable<Task<MaterialModel>> tasks = model.Materials.Select(material =>
_materials.GetAsync(material.Number));
MaterialModel[] result = await Task.WhenAll(tasks);
model.MaterialModels.AddRange(result);
return model;
}
</code></pre>
<p>Here is where my concern is. There are no Async implementations in the library, so my initial thought was to just do the following</p>
<pre><code>public Task<MaterialModel> GetAsync(string number)
{
//This concerns me
return Task.Run(() =>
{
using(var client = new MaterialClient(out WcfResult result))
{
client.Get(number, out Material material, out Result result);
return new MaterialModel(material);
}
});
}
</code></pre>
<p>Both implementations work, but when I run them both side by side the one making calls in parallel is significantly faster and diagnostics shows the flow is what I expected as well</p>
<p><a href="https://i.stack.imgur.com/iqZ63.png" rel="noreferrer"><img src="https://i.stack.imgur.com/iqZ63.png" alt="Sequence" /></a></p>
<hr />
<p><a href="https://i.stack.imgur.com/vVi9m.png" rel="noreferrer"><img src="https://i.stack.imgur.com/vVi9m.png" alt="Parallel" /></a></p>
<p>Is this an acceptable implementation or are there some pitfalls to this I may not be aware about?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T10:30:21.993",
"Id": "490590",
"Score": "1",
"body": "The main problem with doing this in ASP.Net specifically is that you can kill scalability. That might not be a problem for your specific use case (i.e. if it's an internal API called infrequently)."
}
] |
[
{
"body": "<p>I think instead of creating an unknown amount of task using PLinq would make it simpler and have control over the number of task inflight/created</p>\n<p>something like</p>\n<pre><code>var result = model.Materials\n .AsParallel()\n .WithDegreeOfParallelism(8) // whatever you want or leave it out \n .Select(material => _materials.Get(material.Number));\n\nmodel.MaterialModels.AddRange(result);\n</code></pre>\n<p>This way it's not trying to make synchronous code async and can limit the amount of task inflight vs unlimited amount.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-07T09:30:23.110",
"Id": "491102",
"Score": "0",
"body": "If you don't care about ordering then you might improve efficiency by calling `ForAll`: `.Select(material => _materials.Get(material.Number)).ForAll(model.MaterialModels.Add)`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T18:13:16.607",
"Id": "250087",
"ParentId": "250078",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T14:27:57.233",
"Id": "250078",
"Score": "5",
"Tags": [
"c#",
"async-await",
"task-parallel-library",
"asp.net-web-api",
"wcf"
],
"Title": "Parallel Calls to External WCF Service - ASP.NET Web Api"
}
|
250078
|
<p>I have sorted ascending number if you do abs(arr) in below code, I am trying to search for index where sign got changed from negative to positive. Wrote this below code, but for some reasons, I believe we can improve it or optimize more. Any tips and tricks ?</p>
<pre><code>import numpy as np
arr = np.array([-1,-2,-3, 4, 5, 6])
_cut_index_1 = np.where(arr > 0)[0][0]
_cut_index_2 = np.where(arr < 0)[0][-1]
arr[_cut_index_1] # output: 4
arr[_cut_index_2] # output: -3
</code></pre>
|
[] |
[
{
"body": "<p>Your current solution does two passes over the input array (the two invocations of <code>np.where</code>) which as stated seems wasteful. One simple way to solve the problem is to use <code>np.argmax</code> which will take linear time:</p>\n<pre><code>import numpy as np\narr = np.array([-1, -2, -3, 4, 5, 6])\nnp.argmax(arr > 0) # Return (index) 3\n</code></pre>\n<p>At this point, if we can assume (as you seem to imply) that there is a single position of interest (and/or that we only care about the first one, read from left to right) we are done: just decrement one from the answer and you have the other cut-off point (but do check whether we are at a corner case so as not to return a non-valid index).</p>\n<p>But in fact, if you can safely assume that the input is sorted, you can avoid doing a linear scan and not even read the whole input. For this, you can do a binary search via <a href=\"https://numpy.org/doc/stable/reference/generated/numpy.searchsorted.html\" rel=\"nofollow noreferrer\">searchsorted</a>. Theoretically, this is faster (i.e., logarithmic vs. linear in the worst case) but in practice this will depend on the size of the array. That is, for small enough arrays a linear scan will be faster due to cache locality (or, at least, that should be the case modulo your hardware details).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T17:45:09.217",
"Id": "250122",
"ParentId": "250081",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "250122",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T14:56:29.167",
"Id": "250081",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"numpy"
],
"Title": "Searching in Numpy"
}
|
250081
|
<p>I made a placeholder for entry widgets from tkinter, so I was wondering how good it is. I just started learning Python a bit before, so please do correct me if I'm wrong or if I missed something, or some easy steps or where it loses the efficiency.</p>
<p>Code:</p>
<pre><code>import tkinter as tk
from tkinter import ttk
class PlaceholderEntry(ttk.Entry):
'''
Custom modern Placeholder Entry box, takes positional argument master and placeholder\n
Use acquire() for getting output from entry widget\n
Use shove() for inserting into entry widget\n
Use remove() for deleting from entry widget\n
Use length() for getting the length of text in the widget\n
BUG 1: Possible bugs with binding to this class\n
BUG 2: Potential bugs with config or configure method
'''
def __init__(self, master, placeholder, **kwargs):
# style for ttk widget
self.s = ttk.Style()
self.s.configure('my.TEntry', foreground='black', font=(0, 0, 'normal'))
self.s.configure('placeholder.TEntry', foreground='grey', font=(0, 0, 'bold'))
# init entry box
ttk.Entry.__init__(self, master,style='my.TEntry', **kwargs)
self.text = placeholder
self.__has_placeholder = False # placeholder flag
# add placeholder if box empty
self._add()
# bindings of the widget
self.bind('<FocusIn>', self._clear)
self.bind('<FocusOut>', self._add)
self.bind('<KeyRelease>',self._normal)
def _clear(self, *args): # method to remove the placeholder
if self.get() == self.text and self.__has_placeholder: # remove placeholder when focus gain
self.delete(0, tk.END)
self.configure(style='my.TEntry')
self.__has_placeholder = False # set flag to false
def _add(self, *args): # method to add placeholder
if self.get() == '' and not self.__has_placeholder: # if no text add placeholder
self.configure(style='placeholder.TEntry')
self.insert(0, self.text) # insert placeholder
self.icursor(0) # move insertion cursor to start of entrybox
self.__has_placeholder = True # set flag to true
def _normal(self, *args): # method to set the text to normal properties
self._add() # if empty add placeholder
if self.get() == self.text and self.__has_placeholder: # clear the placeholder if starts typing
self.bind('<Key>', self._clear)
self.icursor(-1) # keep insertion cursor to the end
else:
self.configure(style='my.TEntry') # set normal font
def acquire(self): # custom method to get the text
if self.get() == self.text and self.__has_placeholder:
return 'None'
else:
return self.get()
def shove(self, index, string): # custom method to insert into entry
self._clear()
self.insert(index, string)
def remove(self, first, last): # custom method to remove from entry
if self.get() != self.text:
self.delete(first, last)
self._add()
elif self.acquire() == self.text and not self.__has_placeholder:
self.delete(first, last)
self._add()
def length(self):
if self.get() == self.text and self.__has_placeholder:
return 0
else:
return len(self.get())
#usage of class
if __name__ == '__main__':
root = tk.Tk()
e = PlaceholderEntry(root,placeholder='Type something here...')
e.pack(padx=10,pady=10)
root.mainloop()
</code></pre>
<p><strong>Edit:</strong></p>
<p>The older update used global changes, which lead to problems when using more than one entry widget, now that is fixed.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T15:38:12.703",
"Id": "250083",
"Score": "4",
"Tags": [
"python",
"object-oriented",
"classes",
"tkinter"
],
"Title": "Python tkinter placeholder entry widget"
}
|
250083
|
<h1>Problem</h1>
<p>I keep trying to use various todo lists. But I keep coming back to the same situation; not having an <em>active</em> todo list. This can come in two forms:</p>
<ol>
<li><p>I don't have a habit to open bespoke software.<br />
I've tried using Excel, notes and calendars as they're close to my current work flows.
But I tend to always forget about them.
This is because even though I check my emails, my calendar and my notes are on different windows that I just slowly forget to check.</p>
</li>
<li><p>I frequently move away from the 'todo page' in my pad of paper<br />
I have a pad of paper that I see every day.
I can't forget about the pad of paper because it's constantly in my face.
However as I normally jot down ideas on the paper I sometimes go to the next page, and it's like the 'todo page' never existed.</p>
</li>
</ol>
<p>I have a local website that serves links to frequently used pages.
Like Firefox's new page tab, but better™.
For example when I want to double check <a href="https://docs.python.org/3/library/itertools.html" rel="nofollow noreferrer"><code>itertools</code></a> docs I just click on the Python new tab and there's the link.</p>
<p>This solves both problems:</p>
<ol>
<li>I'm in control of the page, and my todo list will always be front and center so I can't forget about it.</li>
<li>My new tab page won't ever change from my local website. Even if I navigate away my new tab will always stay the same.</li>
</ol>
<h1>Environment</h1>
<p>My local website is just a single page and I'm making it fairly modular.
To achieve this I'm having a 'compiler server' that builds the HTML from various other servers.
As such I'm keeping my assets really basic: a single CSS file and a single JS file.</p>
<p>Both scripts are split into two sections:</p>
<ul>
<li><p>The beginning of a very basic component library.
I've used a couple of other component libraries and they've normally had a prefix to avoid collisions so I've done the same.</p>
</li>
<li><p>The bespoke code to build the todo list information and bind to the REST database server.<br />
<strong>Note</strong>: the connection to the REST database hasn't been built yet, which allows for a better stack snippet.</p>
</li>
</ul>
<h1>Features</h1>
<ul>
<li><p>Menu (in the bottom left)</p>
<ul>
<li><p>↻<br />
Refresh the list with the REST database server. (currently a static JSON string)<br />
This is ran on load so the list is populated on start.</p>
</li>
<li><p>+<br />
Add new task.
This will change the view port to a form to add a new task.
Clicking again will close the form.</p>
</li>
</ul>
</li>
<li><p>List (in the top left)</p>
<ul>
<li><p>A list of tasks. You can click on these to open up the task.
Clicking again will close the task.</p>
</li>
<li><p>This is scrollable when 6 or more tasks are entered.<br />
Add a new task to see it yourself :)</p>
</li>
</ul>
</li>
<li><p>View port (on the right)<br />
This has three modes.</p>
<ul>
<li><p>Default<br />
This is the default mode with nothing displayed.
I am planning on putting some information in there that is related to my tasks so I have provided an empty scope.</p>
</li>
<li><p>Item<br />
This displays the item with the title in a title bar.
And the body in the body.</p>
<ul>
<li>Clicking the ✔️ or ❌ will allow you to change the status of the task.</li>
<li>Clicking the × in the top right will go back to the default view.</li>
</ul>
</li>
<li><p>New task<br />
This is almost identical to the item view, but the title is always "New task" and the body is always a form to fill out.</p>
<p>Pressing the "Cancel" button will also change back to the default view.</p>
</li>
</ul>
</li>
</ul>
<h1>Review</h1>
<p>I would appreciate any comments on my design.
I think it looks nice and I've attempted to provide all visual feedback.
The feedback is mostly around hovering as I change the mouse pointer and highlight boxes.</p>
<p>I would appreciate most comments on my JavaScript.
I've tried to follow what I think is standard JavaScript style.
With two main exceptions.</p>
<ul>
<li><p>I have used 4 tabs as I don't want to fiddle with my IDE's settings.
My code is in a Python project and I don't want the headache.</p>
</li>
<li><p>My code is an old-school god file, rather than modern compiled JS.
The simplicity of having two files to maintain greatly outweighs the modern environment I'd set up.
Having JS environments for each and every widget with dodgy build processes that automatically move the built code into the relevant server's static directory.
Not exactly what I'd call KISS.</p>
</li>
</ul>
<h1>Code</h1>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const pTodo = {
props: ['todos', 'default'],
emits: ['refresh'],
data: function () {
return {
selected: this.default === undefined ? null : this.default,
};
},
methods: {
setSelected(value) {
this.selected = value === this.selected ? null : value;
}
},
template: `
<div class="p-todo">
<div class="p-aside">
<div class="p-list">
<div
:class="'p-item' + (index === selected ? ' selected' : '')"
@click="setSelected(index)"
v-for="(todo, index) in todos"
>
<slot v-bind:todo="todo" name="list-item"></slot>
</div>
</div>
<div class="p-menu">
<span
@click="setSelected(null); $emit('refresh', null)"
>
↻
</span>
<span
@click="setSelected('new')"
>
+
</span>
</div>
</div>
<div class="p-view">
<slot
v-if="selected === 'new'"
v-bind:setSelected="setSelected"
name="new"
>
</slot>
<slot
v-else-if="selected !== null"
v-bind:todo="todos[selected]"
v-bind:index="selected"
v-bind:setSelected="setSelected"
>
</slot>
<slot
v-else
v-bind:setSelected="setSelected"
name="overview"
>
</slot>
</div>
</div>
`,
};
const pInput = {
props: ['label', 'value'],
emits: ['input'],
template: `
<div class="p-input">
<label>{{ label }}</label>
<input
:value="value"
@input="$emit('input', $event.target.value)"
>
</div>
`,
};
const TODOS = `[
{
"task": "Task 1",
"body": "Body 1",
"completed": true
},
{
"task": "Task 2",
"body": "Body 2",
"completed": false
},
{
"task": "Task 3",
"body": "Body 3",
"completed": false
},
{
"task": "Task 4",
"body": "Body 4",
"completed": false
},
{
"task": "Task 5",
"body": "Body 5",
"completed": false
}
]`;
(function(){
const newTask = {
components: {
'p-input': pInput,
},
data: function () {
return {
task: "",
body: "",
completed: false,
};
},
emits: ['new', 'cancel'],
template: `
<div class="p-form">
<div class="header">
<span>New task</span>
<span class="close" @click="$emit('cancel', null)">×</span>
</div>
<p class="content">
<p-input label="Task" v-model="task"></p-input>
<p-input label="Body" v-model="body"></p-input>
<button
class="p-button--default"
@click="$emit('new', {task: task, body: body, completed: completed})"
>
Submit
</button>
<button
@click="$emit('cancel', null)"
>
Cancel
</button>
</p>
</div>
`,
};
const pane = {
components: {
'p-todo-pane': pTodo,
'new-task': newTask,
},
data: function () {
return {
todos: [],
};
},
created() {
this.refresh();
},
methods: {
refresh() {
this.todos = JSON.parse(TODOS);
},
add(todo, setSelected) {
this.$set(this, 'todos', [...this.todos, todo]);
setSelected(this.todos.length - 1);
},
toggle(todo, index) {
this.$set(this.todos, index, {...todo, completed: !todo.completed});
},
},
template: `
<p-todo-pane
:todos="todos"
@refresh="refresh"
>
<template #list-item="{ todo, setSelected }">
<span>{{ todo.completed ? "✔️" : "❌" }}</span>
&nbsp;<span>{{ todo.task }}</span>
</template>
<template #default="{ todo, setSelected, index }">
<div class="header">
<span
@click="toggle(todo, index)"
>
{{ todo.completed ? "✔️" : "❌" }}
</span>
&nbsp;<span>{{ todo.task }}</span>
<span class="close" @click="setSelected(null)">×</span>
</div>
<p class="content">
{{ todo.body }}
</p>
</template>
<template #new="{ setSelected }">
<new-task
@new="add($event, setSelected)"
@cancel="setSelected(null)"
>
</new-task>
</template>
</p-todo-pane>
`,
};
new Vue({
el: '#todo',
components: {
'todo-pane': pane,
},
data() {
return {};
}
});
})();</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>html {
background-color: #181a1b;
color: #e8e6e3;
font-family: "DejaVu Serif", "Twemoji Mozilla";
}
@font-face {
font-family: 'Twemoji Mozilla';
/* Changed for the stack snippet */
/* src: url('/static/TwemojiMozilla.ttf') format('truetype'); */
src: url('https://github.com/mozilla/twemoji-colr/releases/download/v0.5.1/TwemojiMozilla.ttf') format('truetype')
}
#todo .p-todo .p-item {
padding: 0.5em;
}
#todo .header {
border-bottom: 1px dotted #333333;
padding-bottom: 0.2em;
}
#todo .header > .close {
float: right;
color: #333333;
cursor: pointer;
}
#todo .content {
margin-bottom: 0;
}
/* Peilonrayz' Components */
.p-todo {
width: 30em;
display: flex;
max-height: 15em;
}
.p-todo > * {
border: 1px solid #111111;
background-color: #222426;
border-right-width: 0;
overflow: hidden;
max-height: inherit;
box-sizing: border-box;
height: 15em;
min-height: 15em;
max-height: 15em;
}
.p-todo > *:first-child {
border-top-left-radius: 0.5em;
border-bottom-left-radius: 0.5em;
}
.p-todo > *:last-child {
border-top-right-radius: 0.5em;
border-bottom-right-radius: 0.5em;
border-right-width: 1px;
}
.p-todo > .p-aside {
flex-grow: 1;
width: 33.33333%;
}
.p-todo > .p-view {
flex-grow: 2;
width: 66.66666%;
padding: 0.5em;
}
.p-todo .p-list {
height: calc(100% - 2em);
overflow-y: scroll;
scrollbar-color: #282a2c #222426;
}
.p-todo .p-list::-webkit-scrollbar
{
width: 12px;
background-color: #222426;
}
.p-todo .p-list::-webkit-scrollbar-thumb
{
background-color: #282a2c;
}
.p-todo .p-menu {
height: 2em;
background-color: #111111;
padding: 0.5em;
display: flex;
width: 100%;
box-sizing: border-box;
justify-content: space-around;
}
.p-todo .p-menu > * {
cursor: pointer;
}
.p-todo .p-list > .p-item {
border-bottom: 1px dotted #333333;
border-top: 1px dotted #333333;
cursor: pointer;
}
.p-todo .p-list > .p-item:first-child {
border-top-width: 0px;
}
.p-todo .p-list > .p-item:last-child {
border-bottom-width: 0px;
}
.p-todo .p-list > .p-item.selected {
background-color: #26282a;
}
.p-todo .p-list > .p-item:not(.selected):hover {
background-color: #242628;
}
.p-input label {
position: absolute;
font-size: 0.8em;
}
.p-input input, .p-input textarea {
background-color : #222426;
border: 0;
border-bottom: 1px dotted #333333;
color: e8e6e3;
padding-top: 1.2em;
margin-bottom: 0.5em;
}
.p-form button {
background-color : #222426;
border: 2px solid #282a2c;
color: e8e6e3;
}
.p-form button:hover {
background-color: #242628;
}
.p-form button.p-button--default {
background-color: #242628;
}
.p-form button.p-button--default:hover {
background-color: #26282a;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/vue@2.6.11/dist/vue.js"></script>
<html>
<body>
<div id="todo"><todo-pane></todo-pane></div>
</body>
</html></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<p>I've managed to join the links and the todo list in my modular 'compiler server'. I've added some more features too and I've had some growing pains with the code.</p>\n<ol>\n<li><p>Components have a minimum size for good interactions. Changing the todo component to the width of the links module makes the todo component horrible to use. Whilst I've dropped the width from 480px to 436px, not even a 10% reduction, the affect is clearly noticeable.</p>\n<p><a href=\"https://i.stack.imgur.com/kiGtf.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/kiGtf.png\" alt=\"Too small example image.\" /></a></p>\n<p>This highlights a couple of problems:</p>\n<ol>\n<li><p>The task preview is far too small. With a couple of solutions.</p>\n<ul>\n<li><p>If the todo component's width is reduced to an unusable size make both the task list and the preview occupy 100% of the component.</p>\n<p>This is possible through <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries\" rel=\"nofollow noreferrer\">media queries</a>. This has the downside that we'd need to know where the component gets its width, as component queries don't exist.</p>\n</li>\n<li><p>Allocate 2/3 of the width to both the list and the view and manually select which gets the joint 1/3 to be shown. For example always show the view unless the view is empty (default) or the user is hovering over the list.</p>\n<p>This would start to look quite ugly if the tasks component is much larger than it is now. To fix this we could use either media queries or by specifying a minimum width. To use a minimum width we can set the width to 1/3 for the list and 2/3 for the view; but by setting both to a minimum width of say 20em we can get them both to have a width of 2/3 if the width of the component is 30em.</p>\n</li>\n<li><p>Don't support smaller sizes, so force the consumer to make the component bigger.</p>\n</li>\n</ul>\n</li>\n<li><p>When a task overflows to the next line the description shouldn't go under the ✔️ or ❌. This is because the "7p" looks completely out of place. And reminds me of a question I asked when I was younger; "why do all old books start with a ridiculously big first letter that looks ugly?" Not all old books have lettrines.</p>\n<p>This can be solved by using a flexbox rather than inline blocks.</p>\n</li>\n</ol>\n</li>\n<li><p>To fix 1.1 I went with the simple solution of, just make it biggerer. But I ran into another problem.</p>\n<p><a href=\"https://i.stack.imgur.com/SUeeu.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/SUeeu.png\" alt=\"Too short example image.\" /></a></p>\n<blockquote>\n<p>Just because you've used relative length units, <code>em</code>, doesn't mean your code is responsive. If the font size never changes - and we don't want it to or we'll be back at square 1 - then your design is static.</p>\n</blockquote>\n<p>I think it should be noted that this doesn't mean you should replace <code>em</code> with <code>px</code>. <code>em</code> allows for a design to resize depending on the font size. This means if you need to <a href=\"https://support.mozilla.org/en-US/kb/font-size-and-zoom-increase-size-of-web-pages\" rel=\"nofollow noreferrer\">enlarge a page</a>, say you have bad eyesight, then all the relative distances stay the same - a border doesn't start to move towards your font.</p>\n<p>I liked the 2 width : 1 height ratio originally selected so we can exploit the fact that <code>margin/padding-top/bottom</code> when specified in % goes off the width.</p>\n<pre class=\"lang-css prettyprint-override\"><code>.p-todo--aspect-ratio {\n position: relative;\n width: 100%;\n height: 0;\n padding-bottom: calc(100% / 2);\n}\n\n.p-todo--aspect-ratio > .p-todo {\n position: absolute;\n width: 100%;\n height: 100%;\n}\n</code></pre>\n<p>I will call <code>.p-todo--aspect-ratio</code> "the parent" and <code>.p-todo</code> as "the child".</p>\n<p>The way this works is:</p>\n<ol>\n<li><p>The containing box includes all of the margin, border, padding and content.</p>\n<p>For example the containing width is the sum of the left and right margin, left and right border, left and right padding and the width of the content.</p>\n</li>\n<li><p>Set the parent's containing box's width to the width we want.</p>\n<pre class=\"lang-css prettyprint-override\"><code>width: 100%\n</code></pre>\n<p>Be careful if any margin, border or padding is added to the box as these will be included in the calculations - which you may not want.</p>\n</li>\n<li><p>Set the parent's containing box's height to the height we want.</p>\n<blockquote>\n<p>It works because margin/padding-top/bottom, when specified as a percentage, is determined according to the <em>width</em> of the containing element. Essentially, you have a situation where "vertical" properties can be sized with respect to a "horizontal" property. This isn't an exploit or a hack, because this is how the CSS specification is defined.<br />\n– <a href=\"https://stackoverflow.com/users/651536/nathan-ryan\">Nathan Ryan</a>\n<a href=\"https://stackoverflow.com/a/6615994#comment19404409_6615994\">2012-12-26 18:25:00Z, License: CC BY-SA 3.0</a></p>\n</blockquote>\n<p><strong>Note</strong>: It doesn't always work this way, we have to specify the position as relative to achieve this. Otherwise it goes off a different element's height.</p>\n<pre class=\"lang-css prettyprint-override\"><code>position: relative;\nheight: 0;\npadding-bottom: calc(100% / 2);\n</code></pre>\n</li>\n<li><p>Set the child's containing box to the size we want. Since height and width are based off the parent's containing box this is super simple. The one gotcha is that you have to specify the position as absolute otherwise the height isn't set correctly.</p>\n<pre class=\"lang-css prettyprint-override\"><code>position: absolute;\nwidth: 100%;\nheight: 100%;\n</code></pre>\n</li>\n<li><p>Whilst we could have used <code>padding-top</code> rather than <code>padding-bottom</code> this moves the position of the parent's content box, moving the child to where that is now located. You can get around that with setting <code>top: 0</code> in the child. But that's just more CSS for more CSS.</p>\n</li>\n</ol>\n<p>Now the box maintains the desired 1:2 aspect ratio. And the child has the height specified so everything can stretch correctly; it's like the code isn't even there!</p>\n</li>\n<li><p>The CSS as currently specified will conflict with other components that get added. <code>.p-list</code> for example was mutating the list component I later added, and vice versa. To prevent this you can prefix the style with the name of the component it's attached to.</p>\n<blockquote>\n<pre class=\"lang-css prettyprint-override\"><code>.p-todo .p-list\n</code></pre>\n</blockquote>\n<pre class=\"lang-css prettyprint-override\"><code>.p-todo .p-todo--list\n</code></pre>\n<p>I'm not sold on this style as I'm used to it meaning a change in state, rather than a new class. Take for example <code>.p-radio</code> and <code>.p-radio--checked</code>.</p>\n</li>\n</ol>\n<p>Currently I've been pretty content with the code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T18:30:17.213",
"Id": "254492",
"ParentId": "250088",
"Score": "1"
}
},
{
"body": "<h1>UI</h1>\n<p>I noticed that when I add a new task I tried to click on the text "<em>New task</em>" to replace that with the text of the task but then I didn't get a cursor, so then I clicked on the text labeled "<em>Task</em>" and started typing - I could barely tell my text was added but it was black so it was difficult to see it against the black background. Perhaps a light contrast color would make it easier to see the text as I type. The same is also true for the buttons labeled <em>Submit</em> and <em>Cancel</em>.\nSee the <strong>CSS</strong> section below where the flaw with the style is mentioned.</p>\n<p><a href=\"https://i.stack.imgur.com/7kM4R.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7kM4R.png\" alt=\"new task screenshot\" /></a></p>\n<p>I also noticed that if I didn't enter text for a task then I could still add it and it would show with no text. I felt stuck because I couldn't edit it . Maybe that is not an issue for you because you always enter text but think about people who are not you, or yourself many years ahead... somebody will skip the text....</p>\n<p><a href=\"https://i.stack.imgur.com/1QETS.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/1QETS.png\" alt=\"enter image description here\" /></a></p>\n<h1>Review</h1>\n<h2>Initial feedback</h2>\n<p>Great job using templates, slots and other features of Vue, as well as using <code>const</code> for variables that don’t need to be re-assigned, lest there be room for accidental re-assignment. Keeping everything in a “god” file seems fine by me.</p>\n<h2>JS</h2>\n<h3>selected data property in <code>Ptodo</code>:</h3>\n<blockquote>\n<pre><code>emits: ['refresh'],'refresh'],\ndata: function () {\n return {\n selected: this.default === undefined ? null : this.default,\n };\n</code></pre>\n</blockquote>\n<p>Idiomatic JS would typically involve short-circuit evaluation:</p>\n<pre><code>emits: ['refresh'],\ndata: function () {\n return {\n selected: this.default || null,\n };\n</code></pre>\n<p>Or the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator\" rel=\"nofollow noreferrer\">nullish coalescing operator</a> could be used:</p>\n<pre><code> selected: this.default ?? null\n</code></pre>\n<h3>duplicate key names in <code>$emit()</code> for submit button</h3>\n<blockquote>\n<pre><code> <button\n class="p-button--default"\n @click="$emit('new', {task: task, body: body, completed: completed})"\n >\n</code></pre>\n</blockquote>\n<p>could be simplified using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Property_definitions\" rel=\"nofollow noreferrer\">the shorthand property definition notation</a> to:</p>\n<pre><code><button\n class="p-button--default"\n @click="$emit('new', {task, body, completed})"\n>\n</code></pre>\n<h3>empty data object when instantiating <code>new Vue()</code>.</h3>\n<p>Maybe this is just boilerplate but it isn't needed:</p>\n<blockquote>\n<pre><code>data() {\n return {};\n }\n</code></pre>\n</blockquote>\n<h2>CSS</h2>\n<p>Lets look at this ruleset:</p>\n<blockquote>\n<pre><code>.p-input input, .p-input textarea {\n background-color : #222426;\n border: 0;\n border-bottom: 1px dotted #333333;\n color: e8e6e3;\n padding-top: 1.2em;\n margin-bottom: 0.5em;\n }\n</code></pre>\n</blockquote>\n<ul>\n<li>there is no hashtag/octothorpe on the <code>color</code> rule. That is why the text entered by the user is black ( as mentioned earlier). The same applies to the color in ruleset for <code>.p-form button</code> - i.e. the Submit and Cancel buttons.</li>\n<li>there are no units on the <code>border</code> rule, which is fine though inconsistent with previous rules where units were specified with a zero value. Some argue <a href=\"https://stackoverflow.com/q/7923042/1575353\">a unit should be specified in case the value is ever changed</a> though opponents point out that <code>0px</code> would create a border with 0px width and hold that readability is better with no units<sup><a href=\"https://stackoverflow.com/a/7923077/1575353\">1</a></sup>. Perhaps it is only an issue if a <code>calc()</code> or similar function is needed<sup><a href=\"https://stackoverflow.com/a/55391061/1575353\">2</a></sup>.</li>\n</ul>\n<h3>Repeated styles for different selectors</h3>\n<p>There are three different rulesets with this single rule:</p>\n<blockquote>\n<pre><code>background-color: #242628;\n</code></pre>\n</blockquote>\n<p>These could be combined:</p>\n<pre><code>.p-todo .p-list > .p-item:not(.selected):hover,\n.p- form button:hover,\n.p-form button.p-button--default {\n background-color: #26282;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T01:20:45.677",
"Id": "502483",
"Score": "0",
"body": "Nice! I completely forgot about the missing `#`s. The code for some bizzare reason worked in my Firefox... I may have Dark Reader enabled and tainting my website... There's some good stuff here, thanks! I'm not a fan of `foo || bar` because I've been snakebit by it so many times in Python, but I look forward to using `??` instead! Also I agree there really should be an edit button. I kinda just deleted and made a new task if I ever made a mistake... I'll revamp my code to take into account your response, thanks Sam!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T00:23:47.747",
"Id": "254770",
"ParentId": "250088",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "254770",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T18:34:51.740",
"Id": "250088",
"Score": "5",
"Tags": [
"javascript",
"beginner",
"ecmascript-6",
"to-do-list",
"vue.js"
],
"Title": "Very basic Vue todo list viewer"
}
|
250088
|
<p>So this is a fun little project I am working on. This is my current progress with the game:</p>
<pre class="lang-py prettyprint-override"><code>import random
import time
import pygame
pygame.init()
pygame.font.init()
pygame.display.set_caption('Parsel Tongue')
MARGIN = 60
WINDOW_SIZE = (600, 600 + MARGIN)
RED = (255, 0, 0)
BLACK = (0, 0, 0)
GREEN = (0, 255, 100)
WHITE = (255, 255, 255)
SNAKE_SIZE = 15
SNAKE_SPEED = 1
FONT_SIZE = 30
if WINDOW_SIZE[0] % SNAKE_SIZE != 0 or WINDOW_SIZE[1] % SNAKE_SIZE != 0 or MARGIN % SNAKE_SIZE != 0:
raise Exception('Size of grid should be divisible by SNAKE_SIZE')
class Food:
foods = []
def __init__(self):
self.add_to_list()
self.coords = None
self.count = 0
self.create_food()
def add_to_list(self):
self.foods.append(self)
def remove_from_list(self):
self.foods.remove(self)
def create_food(self):
self.count += 1
check = set(tuple(part[0]) for snake in Snake.snakes for part in snake.body)
self.coords = random.choice([(i, j) for i in range(0, WINDOW_SIZE[0], SNAKE_SIZE) for j in range(MARGIN, WINDOW_SIZE[1], SNAKE_SIZE) if (i, j) not in check])
def display(self, canvas):
pygame.draw.rect(canvas, RED, (self.coords[0] + 1, self.coords[1] + 1, SNAKE_SIZE - 2, SNAKE_SIZE - 2))
class Snake:
snakes = []
def __init__(self, initial_body):
self.add_to_list()
self.body = initial_body.copy()
self.lock_last = False
self.last_key_function = self.prev_key_function = -1
def add_to_list(self):
self.snakes.append(self)
def remove_from_list(self):
self.snakes.remove(self)
def update_key_function(self, keys):
for key in keys:
if key in (pygame.K_w, pygame.K_UP):
self.last_key_function = 0
if key in (pygame.K_s, pygame.K_DOWN):
self.last_key_function = 2
if key in (pygame.K_a, pygame.K_LEFT):
self.last_key_function = 1
if key in (pygame.K_d, pygame.K_RIGHT):
self.last_key_function = 3
def update(self):
if self.head_in_block():
self.lock_last = False
if self.last_key_function == 0:
if not self.move_up():
self.last_key_function = self.prev_key_function
elif self.last_key_function == 1:
if not self.move_left():
self.last_key_function = self.prev_key_function
elif self.last_key_function == 2:
if not self.move_down():
self.last_key_function = self.prev_key_function
elif self.last_key_function == 3:
if not self.move_right():
self.last_key_function = self.prev_key_function
self.prev_key_function = self.last_key_function
for food in Food.foods:
if self.body[0][0] == food.coords:
self.add_part(food)
self.move()
def add_part(self, food):
self.lock_last = True
self.body.append(self.body[-1].copy())
food.create_food()
def move(self):
if self.last_key_function != -1:
for part_index, (part_coords, part_velocity) in enumerate(self.body if not self.lock_last else self.body[:-1]):
new_part_coords = (part_coords[0] + part_velocity[0], part_coords[1] + part_velocity[1])
self.body[part_index][0] = new_part_coords
if self.head_in_block():
for part_index in range(len(self.body) - 1 - int(self.lock_last), 0, -1):
for new_part_index in range(part_index - 1, -1, -1):
if self.body[new_part_index][0] != self.body[part_index][0]:
self.body[part_index][1] = self.body[new_part_index][1]
break
def move_up(self):
if len(self.body) <= 1 or self.body[0][0][1] <= self.body[1][0][1]:
self.body[0][1] = (0, -SNAKE_SPEED)
return True
return False
def move_left(self):
if len(self.body) <= 1 or self.body[0][0][0] <= self.body[1][0][0]:
self.body[0][1] = (-SNAKE_SPEED, 0)
return True
return False
def move_down(self):
if len(self.body) <= 1 or self.body[0][0][1] >= self.body[1][0][1]:
self.body[0][1] = (0, SNAKE_SPEED)
return True
return False
def move_right(self):
if len(self.body) <= 1 or self.body[0][0][0] >= self.body[1][0][0]:
self.body[0][1] = (SNAKE_SPEED, 0)
return True
return False
def head_in_block(self):
return self.coords_in_block(self.body[0][0])
@staticmethod
def coords_in_block(coords):
return coords[0] % SNAKE_SIZE == coords[1] % SNAKE_SIZE == 0
def display(self, canvas):
for part_index, (part_coords, part_velocity) in enumerate(self.body):
pygame.draw.rect(canvas, WHITE, (part_coords[0] + 1, part_coords[1] + 1, SNAKE_SIZE - 2, SNAKE_SIZE - 2))
if part_index != 0:
while True:
part_coords = (part_coords[0] + part_velocity[0], part_coords[1] + part_velocity[1])
pygame.draw.rect(canvas, WHITE, (part_coords[0] + 1, part_coords[1] + 1, SNAKE_SIZE - 2, SNAKE_SIZE - 2))
if self.coords_in_block(part_coords):
break
if part_index != len(self.body) - 1:
while True:
part_coords = (part_coords[0] - part_velocity[0], part_coords[1] - part_velocity[1])
pygame.draw.rect(canvas, WHITE, (part_coords[0] + 1, part_coords[1] + 1, SNAKE_SIZE - 2, SNAKE_SIZE - 2))
if self.coords_in_block(part_coords):
break
def collided(self):
if not (0 <= self.body[0][0][0] < WINDOW_SIZE[0] - SNAKE_SIZE + 1) or \
not (MARGIN <= self.body[0][0][1] < WINDOW_SIZE[1] - SNAKE_SIZE + 1):
return True
if self.head_in_block():
for part_index, (part_coords, part_velocity) in enumerate(self.body[1:], 1):
if abs(self.body[0][0][0] - part_coords[0]) < SNAKE_SIZE and \
abs(self.body[0][0][1] - part_coords[1]) < SNAKE_SIZE:
return True
else:
return False
class Game:
def __init__(self):
clock = pygame.time.Clock()
self.canvas = pygame.display.set_mode(WINDOW_SIZE)
self.font = pygame.font.SysFont('Arial', FONT_SIZE)
self.finished = False
self.lost = self.paused = False
self.lose_time = self.pause_time = None
self.init_head = (WINDOW_SIZE[0] // 2 // 10 * 10, WINDOW_SIZE[1] // 2 // 10 * 10)
self.init_body = [[self.init_head, (0, 0)]]
self.snake = Snake(self.init_body)
self.food = Food()
while not self.finished:
self.canvas.fill(BLACK)
self.__update()
clock.tick(180)
pygame.draw.rect(self.canvas, WHITE, ((0, MARGIN - 1), (WINDOW_SIZE[0], 1)))
pygame.display.update()
self.__reset()
def __reset(self):
self.finished = False
self.lost = self.paused = False
self.lose_time = self.pause_time = None
self.init_head = (WINDOW_SIZE[0] // 2 // 10 * 10, WINDOW_SIZE[1] // 2 // 10 * 10)
self.init_body = [[self.init_head, (0, 0)]]
self.snake.remove_from_list()
self.food.remove_from_list()
self.snake = Snake(self.init_body)
self.food = Food()
def __update(self):
snake_update_keys = []
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.finished = True
if event.type == pygame.KEYDOWN:
if not self.lost and (event.key == pygame.K_p or event.key == pygame.K_ESCAPE):
self.paused = not self.paused
self.pause_time = time.time() if self.paused else None
snake_update_keys.append(event.key)
if self.lost and event.key == pygame.K_r:
self.__reset()
if not self.lost and self.snake.collided():
self.lost = True
self.lose_time = time.time()
if not self.lost and not self.paused:
self.snake.update_key_function(snake_update_keys)
self.snake.update()
self.food.display(self.canvas)
self.snake.display(self.canvas)
self.__update_score()
self.__update_pause()
self.__update_fail()
def __update_score(self):
self.score = self.food.count - 1
self.score_text = self.font.render('Score: ' + str(self.score), True, GREEN)
self.canvas.blit(self.score_text, (10, 10))
def __update_fail(self):
if self.lost:
fail_text = self.font.render('You lost!', True, GREEN)
self.canvas.blit(fail_text, (WINDOW_SIZE[0] - 10 - fail_text.get_rect().width, 10))
if (time.time() - self.lose_time) % 1 > 0.5:
restart = self.font.render('Press R to restart', True, GREEN)
self.canvas.blit(restart, (WINDOW_SIZE[0] // 2 - restart.get_rect().width // 2,
WINDOW_SIZE[1] // 2 - restart.get_rect().height // 2))
def __update_pause(self):
if self.paused:
if (time.time() - self.pause_time) % 1 > 0.5:
self.pause_text = self.font.render('Press P or Esc to resume', True, GREEN)
self.canvas.blit(self.pause_text, (WINDOW_SIZE[0] - 10 - self.pause_text.get_rect().width, 10))
elif not self.lost:
self.pause_text = self.font.render('Press P or Esc to pause', True, GREEN)
self.canvas.blit(self.pause_text, (WINDOW_SIZE[0] - 10 - self.pause_text.get_rect().width, 10))
game = Game()
</code></pre>
<p>The only bug I noticed is that the snake lags a tiny bit every few seconds. I'm not sure why that's happening, but since it's barely noticeable, I left it as it is for now.</p>
<p>I'm still really new to pygame, and this is one of my first pygame projects, so I'd really appreciate a review of my code.</p>
<p>I'm also thinking about adding textures to the snake and the food, but I'm not sure how I'd implement it. Any comments on that will also be appreciated!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T03:55:00.277",
"Id": "491493",
"Score": "1",
"body": "absolutely love the game, just ran it on my machine"
}
] |
[
{
"body": "<p>The code looks mostly well structured, formatted and using good names for functions, so those "obvious" things don't need fixing.</p>\n<h2>Logic 1 / Don't repeat yourself</h2>\n<pre><code>if WINDOW_SIZE[0] % SNAKE_SIZE != 0 or WINDOW_SIZE[1] % SNAKE_SIZE != 0 or MARGIN % SNAKE_SIZE != 0:\n raise Exception('Size of grid should be divisible by SNAKE_SIZE')\n</code></pre>\n<p>Since you're always dividing by the same thing here, I'd rather</p>\n<pre><code>for x in [WINDOW_SIZE[0], WINDOW_SIZE[1], MARGIN]:\n if x % SNAKE_SIZE != 0:\n raise Exception('...')\n</code></pre>\n<p>Also, since your window sizes are a multiple of MARGIN already, you could make it all simpler (somewhat less flexible) by defining them like that from the start.</p>\n<pre><code>MARGIN = 60\nWINDOW_SIZE = (10 * MARGIN, 11 * MARGIN)\n</code></pre>\n<p>And then you would only have to check MARGIN vs SNAKE_SIZE, not the other two.</p>\n<h2>Style 1</h2>\n<pre><code>def create_food(self):\n self.count += 1\n check = set(tuple(part[0]) for snake in Snake.snakes for part in snake.body)\n self.coords = random.choice([(i, j) for i in range(0, WINDOW_SIZE[0], SNAKE_SIZE) for j in range(MARGIN, WINDOW_SIZE[1], SNAKE_SIZE) if (i, j) not in check])\n</code></pre>\n<p>These lines are extremely long and are hard to follow or modify.\nI don't think the point of Python, or programming in general, is to write as few lines as possible. If you find this readable and maintainable, go ahead, but I'd rather see it split up over multiple lines to be easily understood.</p>\n<h2>Style 2</h2>\n<pre><code>pygame.draw.rect(canvas, RED, (self.coords[0] + 1, self.coords[1] + 1, SNAKE_SIZE - 2, SNAKE_SIZE - 2))\n</code></pre>\n<p>Partly the same problem here. I think <code>self.x</code> and <code>self.y</code> is much more readable than <code>self.coords[0]</code> , and you should name the size of the rect separately, in particular since you're using it twice.</p>\n<pre><code>size = SNAKE_SIZE - 2\npygame.draw.rect(canvas, RED, (self.x + 1, self.y + 1, size, size))\n</code></pre>\n<h2>Logic 2 / Don't repeat yourself</h2>\n<pre><code>def update_key_function(self, keys):\n for key in keys:\n if key in (pygame.K_w, pygame.K_UP):\n self.last_key_function = 0\n\n if key in (pygame.K_s, pygame.K_DOWN):\n self.last_key_function = 2\n\n if key in (pygame.K_a, pygame.K_LEFT):\n self.last_key_function = 1\n\n if key in (pygame.K_d, pygame.K_RIGHT):\n self.last_key_function = 3\n</code></pre>\n<p>So there may be multiple keys, but you only want to save one and only the last one. To make this clearer and less repetitive, I would first define a keymap (it might be better to define it outside of this function, as a "global" or class member, whatever suits.</p>\n<pre><code>direction_keys = {\n pygame.K_w: 0,\n pygame.K_UP: 0,\n ...\n pygame.K_d: 3,\n pygame.K_RIGHT: 3\n} \n</code></pre>\n<p>Then iterate from the end and return on the first hit which makes it clear what this code intends, and doesn't check more keys than needed. (For speed, it probably doesn't matter, but it's clearer and DRYer.</p>\n<pre><code>for k in reversed(keys):\n if k in direction_keys:\n self.last_key_function = direction_keys[k]\n return\n</code></pre>\n<h2>Logic 3 / Don't repeat yourself</h2>\n<pre><code>if self.last_key_function == 0:\n if not self.move_up():\n self.last_key_function = self.prev_key_function\n\n elif self.last_key_function == 1:\n if not self.move_left():\n self.last_key_function = self.prev_key_function\n\n elif self.last_key_function == 2:\n if not self.move_down():\n self.last_key_function = self.prev_key_function\n\n elif self.last_key_function == 3:\n if not self.move_right():\n self.last_key_function = self.prev_key_function\n</code></pre>\n<p>This code has a similar problem. You're repeating a bunch of things when you don't have to.</p>\n<p>The outcome of each of those 4 <code>if</code>s is the same, <code>self.last_key_function = self.prev_key_function</code>, so the <code>elif</code> isn't needed and they could be rewritten as a big <code>or</code> clause like so</p>\n<pre><code>if A or B or C or D:\n self.last_key_function = self.prev_key_function\n</code></pre>\n<p>But we can do better.</p>\n<p>Since these move functions nicely use the numbers <code>0, 1, 2, 3</code> we can for example do this</p>\n<pre><code>for number, func in enumerate ([self.move_up, self.move_left, self.move_down, self.move_right]):\n if self.last_key_function == number and not func():\n self.last_key_function = self.prev_key_function\n break\n</code></pre>\n<p>If you think this is hard to read, just use the <code>or</code> version, which is a lot shorter and better than the current one.</p>\n<p>I would write more comments, but I'm running out of time. Hope this is helpful.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T22:38:01.900",
"Id": "250488",
"ParentId": "250089",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T18:45:19.143",
"Id": "250089",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"game",
"pygame",
"snake-game"
],
"Title": "A Python snake game (using Pygame)"
}
|
250089
|
<p>I created a project for academic purposes that works on Twitter data. It should:</p>
<ul>
<li>Get all friends and follows of the user</li>
<li>Store them in MongoDB</li>
<li>Display them in a table</li>
</ul>
<p>I'm using django + plain HTML, but when trying on an account with only 230 contacts it took 3 minutes to load. The application is intended to be scalable to handle accounts with at least 100k contacts.</p>
<p>How can I improve the scalability of this program?</p>
<pre><code>from twitter_auth.apiKeys import *
import tweepy
from manager.models import Contact
def get_api(user):
access_tokens = user.social_auth \
.filter(provider='twitter')[0] \
.extra_data['access_token']
auth = tweepy.OAuthHandler(
SOCIAL_AUTH_TWITTER_KEY,
SOCIAL_AUTH_TWITTER_SECRET
)
auth.set_access_token(
access_tokens['oauth_token'],
access_tokens['oauth_token_secret']
)
api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)
return api
def get_user_contacts(user):
# Setup Twitter API instance of logged User
api = get_api(user)
me = api.me()
# Set number of contacts fetched per call Max:200
count = 200
# Fetch logged User's friends into a list
friends = tweepy.Cursor(api.friends, me.screen_name, count=count).items()
# friends = api.friends(me.screen_name, count=10)
friend_list = []
for i in friends:
friend_list.append(i)
# Fetch logged User's followers into a list
followers = tweepy.Cursor(api.followers, me.screen_name, count=count).items()
# followers = api.followers(me.screen_name, count=10)
follower_list = []
for j in followers:
follower_list.append(j)
existing_contacts = Contact.objects.filter(user=user)
for contact in existing_contacts:
if contact not in friend_list and contact not in follower_list:
contact.delete()
# Start iterating friend list fetched from Twitter API
for friend in friend_list:
# Initialize Contact Object
temp_friend = Contact(
twitter_id=friend.id,
profile_image_url=friend.profile_image_url_https,
screen_name=friend.screen_name,
name=friend.name,
followers_count=friend.followers_count,
friends_count=friend.friends_count,
statuses_count=friend.statuses_count,
description=friend.description,
location=friend.location,
friendship_status=1,
protected_status=friend.protected,
user=user
)
# Check if entry is just Friend (1) or Friend & Follower (3)
if friend in follower_list:
temp_friend.friendship_status = 3
# Check if current friend already exists in DB
existing_friend = Contact.objects.filter(screen_name=friend.screen_name, user=user)
if existing_friend:
# Update Contact info
existing_friend.update(
profile_image_url=friend.profile_image_url_https,
name=friend.name,
followers_count=friend.followers_count,
friends_count=friend.friends_count,
statuses_count=friend.statuses_count,
description=friend.description,
location=friend.location,
protected_status=friend.protected,
)
# Check if existing Contact followed back
# Case: Have followed back so friendship status updates to (3)
if existing_friend in follower_list:
existing_friend.update(
friendship_status=3
)
# Case: Have not followed back so friendship status remains unchanged(1)
else:
temp_friend.save()
# Start iterating follower list fetched from Twitter API
for follower in follower_list:
# Initialize Contact Object
temp_follower = Contact(
twitter_id=follower.id,
profile_image_url=follower.profile_image_url_https,
screen_name=follower.screen_name,
name=follower.name,
followers_count=follower.followers_count,
friends_count=follower.friends_count,
statuses_count=follower.statuses_count,
description=follower.description,
location=follower.location,
friendship_status=2,
protected_status=follower.protected,
user=user
)
# Check if current follower already exists in DB
existing_follower = Contact.objects.filter(twitter_id=follower.id, user=user)
if existing_follower:
# Update Contact info
existing_follower.update(
profile_image_url=follower.profile_image_url_https,
name=follower.name,
followers_count=follower.followers_count,
friends_count=follower.friends_count,
statuses_count=follower.statuses_count,
description=follower.description,
location=follower.location,
protected_status=follower.protected,
)
# Check if user followed back existing the existing follower
# Case: Have followed back so friendship status updates to (3)
if existing_follower in friend_list:
existing_follower.update(
friendship_status=3
)
# Case: Have not followed back so friendship status remains unchanged(2)
else:
temp_follower.save()
def get_user_tweets(user, id):
api = get_api(user)
tweet_list = api.user_timeline(id=id, count=2)
return tweet_list
</code></pre>
|
[] |
[
{
"body": "<h2>Line continuations</h2>\n<p>They're possible but discouraged.</p>\n<pre><code>access_tokens = user.social_auth \\\n .filter(provider='twitter')[0] \\\n .extra_data['access_token']\n</code></pre>\n<p>would be better, according to most linters, as</p>\n<pre><code>access_tokens = (\n user.social_auth\n .filter(provider='twitter')[0]\n .extra_data['access_token']\n)\n</code></pre>\n<h2>List formation</h2>\n<pre><code>friend_list = []\nfor i in friends:\n friend_list.append(i)\n</code></pre>\n<p>can just be</p>\n<pre><code>friend_list = list(friends)\n</code></pre>\n<p>However, given your usage:</p>\n<pre><code>for contact in existing_contacts:\n if contact not in friend_list and contact not in follower_list:\n contact.delete()\n</code></pre>\n<p>you're better off using sets:</p>\n<pre><code>friend_list = set(friends)\nfollower_list = set(followers)\nexisting_contacts = set(Contact.objects.filter(user=user))\nto_delete = existing_contacts - friend_list - follower_list\nfor contact in to_delete:\n contact.delete()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-09T22:42:49.217",
"Id": "250453",
"ParentId": "250090",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T18:53:01.573",
"Id": "250090",
"Score": "5",
"Tags": [
"python",
"performance",
"time-limit-exceeded",
"django",
"twitter"
],
"Title": "Twitter contact scraper with Tweepy & Django"
}
|
250090
|
<p>I have written a k-means function in Python to understand the methodology. I am trying to use this on a more complex dataset with a larger value for k, but it is running super slow. Does anyone have any recommendations for how I can improve this? I have provided code below, along with loading in an example dataset and applying the algorithm.</p>
<pre><code>def Euc(x,y):
return math.sqrt(sum([(a - b) ** 2 for a,b in zip(x,y)]))
def K_means(TE,k):
Iteration = 0
R = []
O_a = []
Epoch = 0
Tol = 1
Old_Tol = 2
Tol_r = []
start_time = time.time()
mean_cl = [[random.uniform(TE.iloc[i].min(),TE.iloc[i].max()) for i in range(len(TE.columns))] for c in range(0,k)]
for n in range(len(TE)):
D = [Euc(TE.iloc[n].tolist(),mean_cl[c]) for c in range(0,k)]
O_a.append(D.index(min(D)))
while(abs(Old_Tol - Tol) > 0.005):
Old_Tol = Tol
Epoch = Epoch + 1
mean_cl = [TE.iloc[[j for j, x in enumerate(O_a) if x == i]].mean() for i in range(0,k)]
N_a = []
for n in range(len(TE)):
Iteration = Iteration + 1
D = [Euc(TE.iloc[n].tolist(),mean_cl[c]) for c in range(0,k)]
N_a.append(D.index(min(D)))
Tol = np.mean([x != y for x,y in zip(O_a,N_a)])
Tol_r.append(Tol)
O_a = N_a
R.append(time.time() - start_time)
R.append(Tol_r)
R.append(N_a)
R.append(Iteration)
return R
def load_Pima():
url = "http://www.stats.ox.ac.uk/pub/PRNN/pima.tr"
Pima_training = pd.read_csv(url,sep = '\s+')
url = "http://www.stats.ox.ac.uk/pub/PRNN/pima.te"
Pima_testing = pd.read_csv(url,sep = '\s+')
Pima_training = Pima_training.iloc[1:]
Pima_testing = Pima_testing.iloc[1:]
Pima_training.loc[:,"type"] = Pima_training.loc[:,"type"].apply(lambda x : 0 if x == 'Yes' else 1)
Pima_testing.loc[:,"type"] = Pima_testing.loc[:,"type"].apply(lambda x : 0 if x == 'Yes' else 1)
Features = Pima_training.loc[:,Pima_training.columns != "type"]
Means = Features.mean()
SDs = Features.std()
for name in Features.columns:
Pima_training[name] = (Pima_training[name]-Means[name])/SDs[name]
Pima_testing[name] = (Pima_testing[name]-Means[name])/SDs[name]
return Pima_training, Pima_testing
Pima_training, Pima_testing = load_Pima()
class_var = "type"
random.seed(2031)
k = 2
TE = Pima_testing
TE = TE.loc[:,TE.columns != class_var]
km = K_means(TE,k)
</code></pre>
<p>The function returns the runtime of the algorithm, the tolerance at each epoch (% of changes in cluster assignment), the final cluster assignments, and the total number of iterations. I have already removed four for loops, which has sped it up quite a bit. But I fear my lack of Python programming is holding me back from making this more efficient. Any help is appreciated!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T20:10:46.660",
"Id": "490541",
"Score": "1",
"body": "I tried to run this code, but I get this error: `NameError: name 'Euc' is not defined`. Can you include that function too?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T20:10:59.313",
"Id": "490542",
"Score": "3",
"body": "Can you show the `Euc` function? One efficiency step would be to vectorize this and apply it to the whole dataframe `TE` at once instead of row by row."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T20:17:10.600",
"Id": "490544",
"Score": "0",
"body": "Woops sorry guys. Added the \"Euc\" function now too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-04T11:56:46.987",
"Id": "490785",
"Score": "0",
"body": "Please do not edit the code after you have received a review, this violates our [question and answer policy](https://codereview.stackexchange.com/help/someone-answers) and everyone needs to be able to see the code that the answer(s) apply to. You can create a follow up question by asking a new question with the updated code and then making a link between the 2 question."
}
] |
[
{
"body": "<p>You can vectorize this at various points to apply arithmetic to the whole dataframe rather than row-by-row.</p>\n<pre><code>def min_euclidean(df, options):\n """ Returns the index of the series in iterable options for which df - row has minimum\n Euclidean distance """\n return pd.DataFrame(((df - series) ** 2).sum(axis=1, skipna=False) for series in options).idxmin()\n\ndef k_means(TE, k):\n iteration = 0\n epoch = 0\n tol = 1\n old_tol = 2\n tols = []\n start_time = time.time()\n mean_cl = [random.uniform(TE.min(), TE.max()) for _ in range(k)]\n o_a = min_euclidean(TE, mean_cl)\n while abs(old_tol - tol) > 0.005:\n old_tol = tol\n epoch += 1\n mean_cl = [TE[o_a == i].mean() for i in range(k)]\n n_a = min_euclidean(TE, mean_cl)\n iteration += len(TE)\n tol = (o_a != n_a).mean()\n tols.append(tol)\n o_a = n_a\n return time.time() - start_time, tols, n_a, iteration\n</code></pre>\n<p>Note that:</p>\n<ul>\n<li>wherever possible we work with Pandas series or dataframes instead of lists</li>\n<li>I calculate <code>mean_cl</code> as a list of Pandas series instead of a list of lists. This way we avoid iterating through the column or row indices of <code>TE</code>, which is slower. There might be some way to optimize this further by storing <code>mean_cl</code> as a dataframe, but I can't see an obvious way of working with it that way.</li>\n<li>there is no need to take the square root for the Euclidean distance - the indices associated with minimal distance will be the same working with the squared values</li>\n<li><code>o_a</code> and <code>n_a</code> are also stored as series. We can then do <code>(o_a!= n_a).mean()</code> to calculate the disparity between them.</li>\n<li>The biggest optimization here is probably the <code>min_euclidean</code> function which calculates the square difference for the entire dataframe in an optimized way, rather than iterating through it.</li>\n</ul>\n<p><a href=\"https://engineering.upside.com/a-beginners-guide-to-optimizing-pandas-code-for-speed-c09ef2c6a4d6\" rel=\"nofollow noreferrer\">This</a> may be a helpful explanation of vectorization. Working with Pandas series and dataframes in an optimal often involves a slightly different way of thinking than in regular Python.</p>\n<p>EDIT: Here is a version using numpy instead of pandas. This fully vectorizes all the operations and is substantially faster again. It uses an optimization from this <a href=\"https://stackoverflow.com/a/64252529/567595\">StackOverflow answer</a>.</p>\n<pre><code>def k_means(TE, k):\n epoch = 0\n tol = 1\n old_tol = 2\n tols = []\n start_time = time.time()\n te = np.array(TE)\n rows, columns = te.shape\n te3 = te[:, np.newaxis] # 3d version of te for calculating euclidean more easily\n k_range = np.arange(k)[:, np.newaxis]\n mean_cl = np.random.uniform(te.min(axis=0), te.max(axis=0), size=(k, columns))\n o_a = np.nanargmin(((te3 - mean_cl) ** 2).sum(axis=2), axis=1)\n while abs(old_tol - tol) > 0.005:\n old_tol = tol\n epoch += 1\n m = o_a == k_range # masks for each value in range 0 to k-1\n mean_cl = m.dot(te) / m.sum(1, keepdims=True)\n n_a = np.nanargmin(((te3 - mean_cl) ** 2).sum(axis=2), axis=1)\n tol = (o_a != n_a).mean()\n tols.append(tol)\n o_a = n_a\n return time.time() - start_time, tols, n_a, epoch * rows\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T00:54:48.853",
"Id": "490564",
"Score": "0",
"body": "Apologies there was a missing `.mean()` -- edited and it should return the same results now"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T01:58:13.913",
"Id": "490568",
"Score": "0",
"body": "Thanks so much for your help!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-07T15:26:15.223",
"Id": "491146",
"Score": "0",
"body": "I have edited the answer as it was sometimes giving different results from the original: `skipna=False` is needed in the `min_euclidean` function for cases where there are one or more clusters to which no rows are assigned."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T22:13:39.203",
"Id": "250097",
"ParentId": "250094",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "250097",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T20:08:21.653",
"Id": "250094",
"Score": "10",
"Tags": [
"python",
"python-3.x",
"machine-learning"
],
"Title": "K-means function in Python"
}
|
250094
|
<p>I am sending a series of SOAP messages to a server and capturing the results of the SOAP transaction. The issue that I am having is that I need to perform five SOAP calls, and each call requires some data from the previous call. This has led me to create a Data Class that holds Strings accessible with Getters and Setters that gets modified after each call. This code seems "smelly" to me, there is a lot of state change going on in the class and I'm just wondering if there is a better way to go about this.</p>
<p>Here is what's going on, I have the following method in an abstract class:</p>
<pre><code>protected SoapBodyParameters soapBodyParameters;
public void release(String primaryConfigurationIdentifier) throws ReleaseManagerException {
this.soapBodyParameters.setPrimaryConfigurationItemIdentifier(primaryConfigurationIdentifier);
// Implemented by child - Will throw an exception if bad configuration
verify();
// Get user full name and append soapBodyParameters
String userFullName = sendGetUserInfoSoapMessage(this.soapBodyParameters);
this.soapBodyParameters.setUserFullName(userFullName);
// Create a release package on the server - no return needed
sendCreateReleasePackageFromLocalFilesSoapMessage(this.soapBodyParameters);
// Find the release package ID we just made and append soapBodyParameters
String releasePackageSystemId = sendGetReleasePackagesSoapMessage(this.soapBodyParameters);
this.soapBodyParameters.setReleasePackageSystemId(releasePackageSystemId);
// Open the release package and find the task model information
TaskModel taskModel = sendOpenReleasePackageSoapMessage(this.soapBodyParameters);
this.soapBodyParameter.setTaskModelFile(taskModel.getIARTaskModel());
this.soapBodyParameters.setTaskModelId(taskModel.getTaskModelId());
// Implemented by child - Update the task model with required info
updateLocalTaskModel(this.soapBodyParameters);
// Save the task model to the release package on the server
sendSaveTaskModelSoapMessage(this.soapBodyParameters);
}
</code></pre>
<p>So with each of these calls modifying soapBodyParameters and each following call relying on the previous call to modify soapBodyParameters.... I don't know, it just feels <em>smelly</em>. Like I am faking a global parameter in the class.</p>
<p>Is there a better way to do this? I'm trying to get better at recognizing when and where a design pattern would be more appropriate.</p>
|
[] |
[
{
"body": "<p>The code smell I can detect is that your operations require some data from previous calls but you are passing all data from previous calls to them. If you are not sending the full user name in <code>sendOpenReleasePackageSoapMessage(...)</code> you shouldn't include it in the method parameters either. Split the <code>SoapBodyParameters</code> data class to <code>CommonSoapBodyParameters</code> that are sent with all requests and several operation specific data classes that contain only the parameters relevant to the specific operation.</p>\n<p>Passing the member field <code>soapBodyParameters</code> as a method parameter is redundant because the methds can already accss the field directly. So once you have created the <code>CommonSoapBodyParameters</code> class, leave that as a protected member field (or better yet, protect it and provide an accessor method <code>getCommonSoapBodyParameters()</code> with which the concrete subclasses can retrieve it) and only pass the operation specific data objects as method parameter.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T20:50:49.750",
"Id": "490675",
"Score": "0",
"body": "Thanks for your answer. I took your advice and factored out the common params and pass them to the child classes (the message writing classes) as a constructor argument. Then I capture the response for each message and handle the primitive that comes back seperate from those original params, no longer modifying state after each message. Thanks for taking the time to help!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T07:11:09.627",
"Id": "250104",
"ParentId": "250095",
"Score": "3"
}
},
{
"body": "<p>Basically, whenever you find yourself doing something like:</p>\n<pre><code>MyDataStructure data;\n\ncall1(data); // modifies data\ncall2(data); // modifies data\ncall3(data); // modifies data\n</code></pre>\n<p>you have a big indicator, that the data structure should indeed be a class:</p>\n<pre><code>MyDataClass dataClass;\n\ndataClass.call1();\ndataClass.call2();\ndataClass.call3();\n</code></pre>\n<p>If the call chain depends on a given order, encapsulate this in the class as well:</p>\n<pre><code>MyDataClass {\n\n public void doComplexTask() {\n call1();\n if (resultIsNotGood) throw Exception...\n \n call2();\n ...\n // you get it\n }\n\n private call1() { ... } // not exposed any more\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T20:48:38.447",
"Id": "490673",
"Score": "0",
"body": "Thanks for your answer. I considered this approach this morning but wasn't able to get a good implementation due to the rest of the structure of the program... The messaging classes are too tightly coupled to be broken apart like this. I will keep this approach in mind going forward though; thanks again."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T09:50:53.547",
"Id": "250110",
"ParentId": "250095",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "250104",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T20:47:12.377",
"Id": "250095",
"Score": "5",
"Tags": [
"java"
],
"Title": "Data Class code smell? Java object is modified by multiple methods in a row"
}
|
250095
|
<p>I have this working code, but <code>sendAndReceive</code> function looks ugly/smelly to me. Eslint complains about using await inside a loop, and using <code>true</code> as conditional in <code>while</code> loop. Would there be a more elegant way to achieve this? I mean, "blocking" until a response appears in <code>inbox</code> before returning a response. This is necessary because I need to get each response before sending the next message, otherwise the device firmware complains.</p>
<pre><code>const SerialPort = require('serialport');
const ReadLine = require('@serialport/parser-readline');
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
const inbox = [];
// IS THIS FUNCTION OK?
const sendAndReceive = async (message, port) => {
port.write(message);
while (true) {
await sleep(1);
if (inbox.length > 0) {
const response = inbox.pop();
return response;
}
}
};
SerialPort.list()
.then(async portInfos => {
portInfos.filter(pinfo => pinfo.manufacturer === 'FTDI')
.forEach(async portInfo => {
const port = new SerialPort(portInfo.path).setEncoding('ascii');
const parser = port.pipe(new ReadLine({
delimiter: '\r\n',
encoding: 'ascii',
}));
parser.on('data', data => {
inbox.push(data);
});
port.open();
const serialMessage = api.createReadMessage(SERIAL);
const batteryMessage = api.createReadMessage(BATTERY);
for await (const m of [serialMessage, batteryMessage]) {
const response = await sendAndReceive(m, port);
console.log(m.trim());
console.log(response);
console.log();
}
});
});
</code></pre>
|
[] |
[
{
"body": "<p>The <code>while (true) { await sleep(1); ...</code> is potentially very computationally expensive. Yes, it'd be good to refactor it out if possible.</p>\n<p><strong>Response bug</strong> Your current implementation looks like it has a bug, or what could very easily become a bug. The <code>inbox</code> array is global, but each <code>portInfo</code> array item will push <em>separate, undistinguished</em> items to the <code>inbox</code> array. That is, each <code>forEach</code> iteration will create a <code>port</code> and open it <em>immediately</em>, and then whichever iteration whose <code>sendAndReceive</code> happens to run its timeout first after the <code>data</code> callback has pushed an item to the array will get the response. Here:</p>\n<pre><code>const response = await sendAndReceive(m, port);\n</code></pre>\n<p>Unless you have only a single <code>portInfo</code>, the <code>response</code> received is likely to correspond to a <em>different</em> iteration's <code>m</code> and <code>port</code>.</p>\n<p>The easy way to fix this would be to declare a separate <code>inbox</code> array inside each iteration - but the whole approach there deserves some reworking, as you noticed.</p>\n<p>Inside the innermost loop that calls <code>sendAndReceive</code>, you might construct Promises for each message being iterated over, and push their resolve function to an array. When the parser responds, if the array has a resolver function, shift it out and call it with the data:</p>\n<pre><code>portInfos.filter(pinfo => pinfo.manufacturer === 'FTDI')\n .forEach(portInfo => {\n const port = new SerialPort(portInfo.path).setEncoding('ascii');\n const parser = port.pipe(new ReadLine({\n delimiter: '\\r\\n',\n encoding: 'ascii',\n }));\n\n const resolves = [];\n parser.on('data', data => {\n if (resolves.length) {\n resolves.shift()(data);\n }\n });\n\n port.open();\n\n const serialMessage = api.createReadMessage(SERIAL);\n const batteryMessage = api.createReadMessage(BATTERY);\n for (const message of [serialMessage, batteryMessage]) {\n new Promise((resolve) => {\n port.write(message);\n resolves.push(resolve)\n })\n .then((response) => {\n console.log(m.trim());\n console.log(response);\n });\n }\n });\n</code></pre>\n<p>The promises are currently dangling, which is usually weird, but in this case, the promises will never reject. If <code>parser</code> might not be able to get a <code>data</code> for a given message, and it exposes an API for that (an error event, maybe?), it would be good to listen for that, so errors can be properly handled instead of ignored.</p>\n<p>Note that the above approach calls <code>port.write</code> twice at once in a given iteration *once for each method), instead of waiting for the prior message Promise to resolve first - this will speed up your program a bit, since you're now waiting in parallel, not in serial. If you wanted to do something when both messages are received, you'd use <code>Promise.all</code> and pass into it an array of the Promises instead of using <code>for..of</code>. (If you have to wait in serial, you can <code>await</code> the resolution of each Promise inside the loop)</p>\n<hr />\n<p>Other things I noticed:</p>\n<p><strong><code>for..await</code> is only for async iterators</strong> While you're technically allowed to do</p>\n<pre><code>for await (const m of [serialMessage, batteryMessage]) {\n</code></pre>\n<p>it doesn't make sense to use <code>for await</code>, since the array there is just a plain array - it's not something that implements the async iterator interface. It'd be more appropriate to use just <code>for (const m ...</code></p>\n<p><strong>Variable names</strong> <code>m</code> isn't so great as a variable name. <code>message</code> is significantly more informative.</p>\n<p><strong>Only use <code>async</code> when you need to return a Promise</strong> You do:</p>\n<pre><code>SerialPort.list()\n .then(async portInfos => {\n portInfos.filter(pinfo => pinfo.manufacturer === 'FTDI')\n .forEach(async portInfo => {\n</code></pre>\n<p>The <code>.then</code>'s callback does not use <code>await</code> directly inside of it, nor does it need to return a Promise, so there's no need for the <code>async</code> keyword - it's just potentially confusing noise.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T01:26:48.007",
"Id": "250100",
"ParentId": "250098",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "250100",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T23:13:18.830",
"Id": "250098",
"Score": "2",
"Tags": [
"node.js",
"async-await",
"promise"
],
"Title": "Send message and wait for receive while using async/await and promises the proper way"
}
|
250098
|
<p>See my original post: <a href="https://codereview.stackexchange.com/questions/250062/email-validation-in-php-see-edit">here</a>.</p>
<p>I have one html page and four php files that allow users to sign up for an email list. One of the php scripts is a cronjob that deletes <em>unverified rows</em> older than 24 hours, and it is not included below for the sake of post length. I use PDO for my prepared statements. Everything has been tested live and is fully functional to the best of my knowledge. Any and all feedback is welcome. I've bulleted some questions below the snippets. :)</p>
<p><em><strong>email.html</strong></em> --- Users sign up here</p>
<pre><code><form action="signup.php" method="POST" autocomplete="off">
<input type="text" autocomplete="off" placeholder="Email address" name="email" required>
<br/>
<input type="submit" autocomplete="off" value="Subscribe">
</form>
</code></pre>
<p><em><strong>signup.php</strong></em> --- Filters and sends user input to the database</p>
<pre><code><?php
//1---DATABASE CONNECTION---
$dbHost = "HOST";
$dbName = "DATABASE";
$dbUser = "USER";
$dbPassword = "PASSWORD";
$port = "PORT";
$charset = 'utf8mb4';
$options = [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
\PDO::ATTR_EMULATE_PREPARES => false,
];
$dsn = "mysql:host=$dbHost;dbname=$dbName;charset=$charset;port=$port";
try {
$pdo = new \PDO($dsn, $dbUser, $dbPassword, $options);
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
//1---END---
//2---Add to table: IPv4 ADDRESS, EMAIL, DATETIME, and ACODE---
//prevent direct url access of .php from users, routes to starting page
if(($_SERVER['REQUEST_METHOD'] == 'POST') == NULL) {
header("Location: email.html");
exit (0);
}
//trim spaces on ends of user email input
$Temail = trim($_POST['email']); //(on mobile, auto-complete often leaves a space at the end)
//allow international characters
if(preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^/", $Temail)) {
//prevents invalid email addresses
header("Location: invalid.html");
exit (0);
}
//Check Email Domain MX Record
$email_host = strtolower(substr(strrchr($Temail, "@"), 1));
if (!checkdnsrr($email_host, "MX")) {
header("Location: invalid.html");
exit (0);
}
//Prevent users from inputting a specific domain...like mine
$notallowed = [
'mydomain.com',
];
if (!in_array($email_host, $notallowed) == NULL) {
header("Location: notallowed.html");
exit (0);
}
//checks database to make sure the email is not a duplicate
$stmt1 = $pdo->prepare("SELECT email FROM emailTable WHERE email = ?");
$stmt1->execute([$Temail]);
if($stmt1->fetch()) { //prevents adding a duplicate email
header("Location: duplicate.html");
exit (0);
}
//send verification email using seperate php file
include_once 'vEmail.php';
//check to see if email could be put together
if(include_once 'vEmail' == NULL) {
header("Location: failure.html");
exit (0);
}
//set date and time
date_default_timezone_set('America/Los_Angeles');
$dateTime = date('Ymd-His', strtotime('NOW')); // ('Ymd-His' format and LA timezone are preferred)
//variable to store ipv4 address
$euserIP4 = $_SERVER['REMOTE_ADDR'];
//add all data to the database
$stmt2 = $pdo->prepare("INSERT INTO emailTable (IP4, datetime, email, acode) VALUES (:IP4, :datetime, :email, :acode)");
$stmt2->execute(['IP4' => $euserIP4, 'datetime' => $dateTime, 'email' => $Temail, 'acode' => $Acode]);
header("Location: success.html");
exit (0);
//2---END---
?>
</code></pre>
<p><em><strong>vEmail.php</strong></em> --- <code>include_once</code> in signup.php, sends verification email</p>
<pre><code><?php
//generate verification code
$Acode = bin2hex(random_bytes(30));
//send verification email w/ code
$emailbody =
"<html>
<body>
<table>
<tr>
<td>
<button><a href='https://www.MYDOMAIN.com/status/verify.php?acode=$Acode'>VERIFY</a></button>
</td>
</tr>
</table>
</body>
</html>";
$headers = "Reply-To: MY NAME <no-reply@MYDOMAIN.com>\r\n";
$headers .= "Return-Path: MY NAME <no-reply@MYDOMAIN.com>\r\n";
$headers .= "From: MY NAME <no-reply@MYDOMAIN.com>\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=UTF-8\r\n";
$headers .= "X-Priority: 3\r\n";
//send email
mail($Temail, 'Confirm Your Email Subscription', $emailbody, $headers, '-f ' . 'no-reply@MYDOMAIN.com');
?>
</code></pre>
<p><em><strong>verify.php</strong></em> --- Attached to link that was sent in the verification email</p>
<pre><code><?php
//1---DATABASE CONNECTION---
$vHost = "";
$vName = "";
$vUser = "";
$vPassword = "";
$vPort = "";
$vCharset = "";
$vOptions = [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
\PDO::ATTR_EMULATE_PREPARES => false,
];
$vdsn = "mysql:host=$vHost;dbname=$vName;charset=$vCharset;port=$vPort";
try {
$vpdo = new \PDO($vdsn, $vUser, $vPassword, $vOptions);
} catch (\PDOException $ve) {
throw new \PDOException($ve->getMessage(), (int)$ve->getCode());
}
//1---END---
//2---VERIFICATION LINK---
//set timezone
date_default_timezone_set('America/Los_Angeles');
//prevent direct url access of .php from users, routes to starting page
if(isset($_GET['acode']) == NULL) {
header("Location: email.html");
exit (0);
}
//set verification code variable
$vAcode = $_GET['acode'];
//check if row still exists
$vStmt1 = $vpdo->prepare("SELECT verified, acode FROM emailTable WHERE acode = '$vAcode' LIMIT 1");
$vStmt1->execute();
if($vStmt1->rowCount() == NULL) {
//EXPIRED
header("Location: expired1.html");
exit (0);
}
//check if row is verified ('verified' set to 0)
$vStmt2 = $vpdo->prepare("SELECT verified, acode FROM emailTable WHERE verified = 0 AND acode = '$vAcode' LIMIT 1");
$vStmt2->execute();
if($vStmt2->rowCount() == NULL) { //if 'verified' is set to 1 already
header("Location: expired2.html");
exit (0);
}
//since 'verified' is set to 0,update verification status to 1
$vStmt3 = $vpdo->prepare("UPDATE emailTable SET verified = 1 WHERE acode = '$vAcode' LIMIT 1");
$vStmt3->execute();
//check if the 'verified' was updated correctly
if($vStmt3->fetch()) {
header("Location: failure.html");
exit (0);
}
//SUCCESS
header("Location: verified.html");
exit (0);
//2---END---
?>
</code></pre>
<h2>Questions and Comments:</h2>
<ul>
<li>I've included database connections for each php file, but I've found that some prefer to have a global config file for their connections. Why is that? Is it more efficient?</li>
<li>In the original post, someone mentioned that the regex found in signup.php is missing the unicode flag. Could someone explain this, because I wasn't able to find anything on it.</li>
<li>While storing IPv4 works well, I haven't been able to figure out how to correctly store IPv6 (as far as I know). I've tried this: <code>bin2hex(inet_pton($_SERVER['REMOTE_ADDR']));</code> but I couldn't figure out if the output was correct, because it looked nothing like an ipv6 address. Correct me if this looks usable.</li>
<li>I'm looking into PHPMailer rather than using the native mail() function. In the case of the above scripts, would this be recommended or is it more for bulk email sending?</li>
</ul>
<h2>Edit 1:</h2>
<p>I've just realized that the email validation found in <code>signup.php</code> allows an email address with spaces (ie: ohnothere are spaces@mydomain.com). The previous version of the script, found at the link at the top of the post, prevented these sorts of addresses. Any ideas why that may be, or how to prevent that? I'd like to stay away from filter_var(FILTER_VALIDATE_EMAIL) since it cancels international characters. Will continue experimenting with it...</p>
|
[] |
[
{
"body": "<p>Including a global configuration file is not about efficiency, it's just about centralizing the application configuration data.</p>\n<p>Suppose, for example, that you're developing a new feature for your application, you want to use a database specifically for this purpose, so as not to interfere with the production database.</p>\n<p>If you're including the database configuration on each script, you're going to have to make sure you check (and hopefully double-check) every script to make sure none of your development actions get propagated to the production database. (Even if you were certain none of your changes would be visible to your application if pushed to the production database, using a completely different database saves your production database and application from having to handle the load from both regular users and the development team.)</p>\n<p>On the other hand, you could just do this. Note that defining <a href=\"https://www.php.net/manual/en/function.define\" rel=\"nofollow noreferrer\">array-valued constants</a> is valid as of PHP 7.0.0, although you could simply use ini-style <code>define( 'DEV_HOSTNAME', ... )</code> style constant definitions, it's just not as fancy.</p>\n<pre><code>define( 'CONFIGURATION', 'PRODUCTION' );\n\ndefine( 'ENVIRONMENT', [\n 'DEVELOPMENT' => [\n 'hostname' => 'localhost',\n 'database' => 'devdb',\n 'username' => 'username',\n 'password' => 'password'\n ],\n 'PRODUCTION' => [\n 'hostname' => 'hostname',\n 'database' => 'proddb',\n 'username' => 'username',\n 'password' => 'password'\n ]\n]);\n</code></pre>\n<p>Now all you have to do to switch environments in your application is modify the <code>CONFIGURATION</code> constant, since your application could access the configuration values using something like this.</p>\n<pre><code>$hostname = ENVIRONMENT[CONFIGURATION]['hostname'];\n$database = ENVIRONMENT[CONFIGURATION]['database'];\n$username = ENVIRONMENT[CONFIGURATION]['username'];\n$password = ENVIRONMENT[CONFIGURATION]['password'];\n</code></pre>\n<p>What some production applications do is define an abstract <code>Database</code> class whose derived classes implement an interface that defines how they should be accessed, so you could switch between say MySQL and Postgres by doing something like the above. This is one of the reasons PDO is so useful; it allows us to code to an interface, not an implementation.</p>\n<p>To answer your question about efficiency, it's actually <em>less</em> efficient to include a separate file that contains the configuration data.</p>\n<p>To include a file, the interpreter has to get it first. Application configuration files are (obviously) application-specific, and thus located somewhere in or around the current directory. However, unless the include path is absolute or begins with a '.' or '..', <a href=\"https://www.php.net/manual/en/function.include.php\" rel=\"nofollow noreferrer\">PHP will first look for the file in the <code>include_path</code></a>.</p>\n<p>Assuming the file is actually found eventually, reading it from wherever it is stored requires disk access, which is <a href=\"https://gist.githubusercontent.com/jboner/2841832/raw/7e5cb7f173d0b59820f63cc6d489ec4f449bc126/latency.txt\" rel=\"nofollow noreferrer\">really slow</a>, although the impact can be mitigated by using SSDs or even <a href=\"https://man7.org/linux/man-pages/man5/tmpfs.5.html\" rel=\"nofollow noreferrer\"><code>tempfs</code></a>, as well as caching.</p>\n<p>Worse yet, if you use the <code>*_once</code> version of either <a href=\"https://www.php.net/manual/en/function.require.php\" rel=\"nofollow noreferrer\"><code>require</code></a> or <a href=\"https://www.php.net/manual/en/function.include.php\" rel=\"nofollow noreferrer\"><code>include</code></a>, it won't just include the file (if and when the file is eventually found), the interpreter will go through the additional trouble of verifying the file hasn't already been included.</p>\n<p>You can think of the tradeoff between inefficient configuration change propagation and execution speed as a tradeoff between development time efficiency vs. execution time efficiency, and it's definitely worth your while (pun intended).</p>\n<p>Larger applications tend to opt for a more object-oriented approach to configuration by essentially encapsulating these global variables in a singleton class that oversees the getting and setting of configuration parameters. You'll probably see this referred to as the <a href=\"https://designpatternsphp.readthedocs.io/en/latest/Structural/Registry/README.html\" rel=\"nofollow noreferrer\">Registry pattern</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T19:28:01.953",
"Id": "490657",
"Score": "0",
"body": "With only 4 php files connecting a single database and table, I'm leaning more towards simply including the same database connection in each file (with differing variable name). Which method would you recommend is best for my situation?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T15:17:54.073",
"Id": "250115",
"ParentId": "250099",
"Score": "2"
}
},
{
"body": "<p>Yes, use an include file for your DB connection. If you change the DB password or the server, you'll have to update several pages and make sure they all match. That is tedious, and even if you have just 4 pages today, that could be 20 or more in the future.</p>\n<p>Avoid unnecessary <strong>repetition</strong>. Repetition is every programmer's enemy. There is also more stuff that you repeat in other pages, for example:</p>\n<pre><code>date_default_timezone_set('America/Los_Angeles');\n</code></pre>\n<p>What is the purpose of this ? Anyway, you should have some sort of <strong>config file</strong> to centralize settings. And then require_once should do.</p>\n<h2>DNS records</h2>\n<p>I think the merit of this is debatable:</p>\n<pre><code>//Check Email Domain MX Record\n$email_host = strtolower(substr(strrchr($Temail, "@"), 1));\nif (!checkdnsrr($email_host, "MX")) {\n header("Location: invalid.html");\n exit (0);\n}\n</code></pre>\n<p>You are checking if the domain has at least one MX record. Presumably you want to thwart random submissions by spammers or whatever. But in itself that proves very little, and it does not demonstrate that the submission was made in good faith. I could use anybody's E-mail address, as long as it passes the test. So I don't see a lot of added value in this personally.</p>\n<p>Also, transient DNS errors may occur. This function may fail from time to time, even with legitimate domain names. Normally, the mail is not delivered directly but goes to a local queue and in case of DNS lookup failures or whatever your MTA will try sending the mail at regular intervals.</p>\n<p>Also, if I am not wrong, the RFC says that in the absence of a MX record, the MTA can use a A record as a fallback (keep in mind that many DNS zones are poorly configured).</p>\n<p>strtolower is not needed, as domain names are not case-sensitive. Although you may want to normalize input and force the whole E-mail address to lowercase in case it contains a mix of lowercase and uppercase characters. Purely for cosmetic reasons.</p>\n<h2>Includes</h2>\n<p>Don't do this:</p>\n<pre><code>//send verification email using seperate php file\ninclude_once 'vEmail.php';\n</code></pre>\n<p>That makes the code even more difficult to follow and understand. Remember, code that is hard to read/understand tends to be more buggy and less secure.</p>\n<p>Instead, write a dedicated function that returns a boolean value, or anything you want. But you can have an include at the top of your code to import your functions of course. Could be something like this:</p>\n<pre><code>if (!send_verification_email($email, $verification_code)) {\n // an error occured, do something\n}\n// proceed normally\n</code></pre>\n<h2>Misc</h2>\n<p>I think you have too many redirect pages, just consider this:</p>\n<ul>\n<li>expired1.html</li>\n<li>expired2.html</li>\n<li>email.html</li>\n<li>invalid.html</li>\n<li>notallowed.html</li>\n<li>duplicate.html</li>\n<li>failure.html</li>\n<li>success.html</li>\n<li>verified.html</li>\n</ul>\n<p>And of course they must all be very similar. I would strongly advise to evolve your coding practices - use a <strong>framework</strong> or at least a <strong>templating</strong> solution. One page would suffice, and you pass some parameters like a custom message so that the page can be rendered in many different ways. You don't need a page for every possible scenario. Just think about maintenance and bloat.</p>\n<p>Note that you could use templates for your <strong>mails</strong> too. All you need is text files with some delimited tags eg %VERIFICATION_CODE%, then you simply replace those tags with the values from your variables.</p>\n<h2>IPv6</h2>\n<p>What is your problem with IPv6 ? Are you storing the value in a varchar field ? Then allocate at least <a href=\"https://stackoverflow.com/questions/166132/maximum-length-of-the-textual-representation-of-an-ipv6-address\">45 characters</a> but there is nothing special about it. Of course IPv6 addresses tend to be longer and have a markedly different pattern. The question is, what is the purpose of storing this information and how do you intend to use it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T20:34:23.090",
"Id": "250128",
"ParentId": "250099",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "250115",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-01T23:35:05.790",
"Id": "250099",
"Score": "4",
"Tags": [
"php",
"html",
"validation",
"email"
],
"Title": "PHP Email List Sign Up"
}
|
250099
|
<p>I've been trying to get into web development, so I made a quick Tic Tac Toe implementation. It feels messy to me, but I'm not sure what is really considered to be good practice and what not. Any poor practice in my code, or things I could improve?</p>
<p><a href="https://github.com/jason-shepherd/tictactoe" rel="nofollow noreferrer">https://github.com/jason-shepherd/tictactoe</a></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>//Get the board, record, and select html elements
const gridSpaces = document.querySelectorAll('[data-spaces]');
const recordText = document.querySelector('[data-record]');
const difficultySelect = document.querySelector('[data-select]')
const gridWidth = Math.sqrt(gridSpaces.length);
let opponent = "O"
let player = "X"
let difficulty;
let record = {
X: 0,
O: 0,
ties: 0
}
let moveCount = 0;
let inPlay = true;
function init() {
updateDifficulty();
//Init the board spaces with an event listener
for(let i = 0; i < gridSpaces.length; i++) {
gridSpaces[i].addEventListener('click', () => {
if(!inPlay) {
reset();
return;
}
if(getSpaceValue(i) != '') return;
//Player's move
setSpaceValue(i, player);
gridSpaces[i].style.cursor = "default";
win = getWin(Math.floor(i % gridWidth), Math.floor(i / gridWidth), player);
displayWin(win, player);
moveCount++;
//AI move
if(inPlay) {
if(difficulty != 0)
makeAiMove();
else
player = player == "O" ? "X" : "O";
}
});
}
}
function checkRowSpace(index, x, y, board) {
return getGridSpace(index, y, board);
}
function checkColSpace(index, x, y, board) {
return getGridSpace(x, index, board);
}
function checkDiagonal(index, x, y, board) {
if(x == y)
return getGridSpace(index, index, board);
else
return null;
}
function checkAntiDiagonal(index, x, y, board) {
if(x + y == gridWidth - 1)
return getGridSpace(index, gridWidth - 1 - index, board);
else
return null
}
const checkFunctions = [checkRowSpace, checkColSpace, checkDiagonal, checkAntiDiagonal];
function getWin(x, y, currentPlayer, board) {
let winSequence = [];
for(let i = 0; i < 4; i++) {
for(let j = 0; j < gridWidth; j++) {
let currentSpace = checkFunctions[i](j, x, y, board);
if(board == undefined) {
if(getSpaceValue(currentSpace) != currentPlayer) {
winSequence = [];
break;
}
} else if(currentSpace != currentPlayer) {
winSequence = [];
break;
}
winSequence.push(currentSpace);
if(j == gridWidth - 1) {
return winSequence;
}
}
}
if(moveCount == Math.pow(gridWidth, 2) - 1) {
return gridSpaces;
}
return winSequence;
}
function displayWin(win, currentPlayer) {
if(win.length !== 0) {
let condition = "win";
if(win.length === gridSpaces.length) {
record.ties++;
condition = "draw";
} else {
record[currentPlayer]++;
}
recordText.textContent = `X ${record.X}-${record.ties}-${record.O} O`;
win.forEach(space => {
space.firstChild.classList.add(condition);
});
gridSpaces.forEach(space => {
space.style.cursor = "pointer";
});
inPlay = false;
return;
}
}
function makeAiMove() {
let bestVal = -11;
let bestMove;
let newBoard = [];
gridSpaces.forEach(space => {
newBoard.push(getSpaceValue(space));
});
let possibleMoves = getBoardChildren(newBoard, "O");
if(difficulty != 9)
possibleMoves.sort((a, b) => {return 0.5 - Math.random()})
possibleMoves.forEach(child => {
let value = minimax(child, difficulty, false);
if(value > bestVal) {
bestVal = value;
bestMove = child;
}
});
for(let i = 0; i < bestMove.length; i++) {
if(getSpaceValue(i) != bestMove[i]) {
setSpaceValue(i, 'O');
let win = getWin(Math.floor(i % gridWidth), Math.floor(i / gridWidth), opponent);
displayWin(win, opponent);
}
}
moveCount++;
}
function minimax(board, depth, maximizingPlayer) {
let score = scoreBoard(board, depth);
if(depth == 0 || isTerminating(board) || score != 0)
return score;
if(maximizingPlayer) {
let value = -10;
getBoardChildren(board, opponent).forEach(child => {
value = Math.max(value, minimax(child, depth - 1, false));
});
return value;
} else {
let value = 10;
getBoardChildren(board, player).forEach(child => {
value = Math.min(value, minimax(child, depth - 1, true));
});
return value;
}
}
function getBoardChildren(board, currentPlayer) {
let children = [];
for(let i = 0; i < board.length; i++) {
if(board[i] == '') {
board[i] = currentPlayer;
children.push([...board]);
board[i] = '';
}
}
return children;
}
function isTerminating(board) {
for(let i = 0; i < board.length; i++) {
if(board[i] == '')
return false;
}
return true;
}
function scoreBoard(board, depth) {
let currentPlayer = "O";
for(let i = 0; i < 2; i++) {
for(let j = 0; j < 3; j++) {
if(getWin(j, j, currentPlayer, board).length == 3) {
if(currentPlayer == "O")
return 10 - (difficulty - depth);
else
return -10 + (difficulty - depth);
}
}
currentPlayer = "X";
}
return 0;
}
function updateDifficulty() {
if(difficultySelect.value != "friend") {
switch(difficultySelect.value) {
case "easy":
difficulty = 1;
break;
case "medium":
difficulty = 4;
break;
case "unbeatable":
difficulty = 9;
break;
}
if(player == "O") {
player = "X";
makeAiMove();
}
} else {
difficulty = 0;
}
}
function reset() {
player = "X";
moveCount = 0;
inPlay = true;
for(let i = 0; i < gridSpaces.length; i++) {
gridSpaces[i].firstChild.classList.remove("win");
gridSpaces[i].firstChild.classList.remove("draw");
setSpaceValue(i, "");
}
}
function getSpaceValue(x, y, board) {
if(x == null)
return;
else if(typeof x === 'object')
return x.firstChild.textContent;
else if(y == undefined)
return gridSpaces[x].firstChild.textContent;
else
return gridSpaces[y * gridWidth + x].firstChild.textContent;
}
function setSpaceValue(index, value) {
gridSpaces[index].firstChild.textContent = value;
}
function getGridSpace(x, y, board) {
if(board != undefined)
return board[y * gridWidth + x];
else
return gridSpaces[y * gridWidth + x];
}
init();</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
background-color: #353A47;
}
.tictactoe-container {
background-color: #353A47;
width: 77vh;
height: auto;
position: absolute;
left: 50%;
top: 20%;
transform: translate(-50%, -20%);
}
.grid-container {
background-color: #2B303B;
display: inline-grid;
width: auto;
height: auto;
grid-gap: 1vh;
grid-template-columns: repeat(3, 25vh);
grid-template-rows: repeat(3, 25vh);
}
.grid-item {
background-color: #353A47;
color: #F0F7EE;
display: flex;
cursor: pointer;
justify-content: center;
align-items: center;
font-family: 'Varela Round', sans-serif;
font-weight: bold;
font-size: 25vh;
}
.record {
color: #F0F7EE;
font-weight: bold;
text-align: center;
font-family: 'Varela Round', sans-serif;
font-size: 10vh;
white-space: nowrap;
margin: 2vh auto;
}
.ai-select {
color: #F0F7EE;
background-color: #353A47;
font-size: 3vh;
width: 40%;
height: 15%;
margin: 1vh 30%;
}
.win {
color: #4BB3FD;
animation: shake 0.5s;
animation-iteration-count: 3;
}
.draw {
color: #FF312E;
animation: shake 0.5s;
animation-iteration-count: 6;
}
@keyframes shake {
0% { transform: translate(1px, 1px) rotate(0deg); }
10% { transform: translate(-1px, -2px) rotate(-1deg); }
20% { transform: translate(-3px, 0px) rotate(1deg); }
30% { transform: translate(3px, 2px) rotate(0deg); }
40% { transform: translate(1px, -1px) rotate(1deg); }
50% { transform: translate(-1px, 2px) rotate(-1deg); }
60% { transform: translate(-3px, 1px) rotate(0deg); }
70% { transform: translate(3px, 1px) rotate(-1deg); }
80% { transform: translate(-1px, -1px) rotate(1deg); }
90% { transform: translate(1px, 2px) rotate(0deg); }
100% { transform: translate(1px, -2px) rotate(-1deg); }
}
.noselect {
-webkit-touch-callout: none; /* iOS Safari */
-webkit-user-select: none; /* Safari */
-khtml-user-select: none; /* Konqueror HTML */
-moz-user-select: none; /* Old versions of Firefox */
-ms-user-select: none; /* Internet Explorer/Edge */
user-select: none; /* Non-prefixed version, currently
supported by Chrome, Edge, Opera and Firefox */
}
@media screen and (orientation:portrait) {
.tictactoe-container {
width: 77vw;
}
.grid-container {
grid-gap: 1vw;
grid-template-columns: repeat(3, 25vw);
grid-template-rows: repeat(3, 25vw);
}
.grid-item {
font-size: 25vw;
}
.record {
font-size: 10vw;
}
.ai-select {
font-size: 3vw;
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1">
<head>
<title>Tic Tac Toe</title>
<link rel="stylesheet" type = "text/css" href = "style.css">
<link href="https://fonts.googleapis.com/css2?family=Varela+Round&display=swap" rel="stylesheet">
</head>
<body>
<div class="tictactoe-container">
<p data-record class="record noselect">X 0-0-0 O</p>
<div class="grid-container noselect">
<div data-spaces class="grid-item"><p></p></div>
<div data-spaces class="grid-item"><p></p></div>
<div data-spaces class="grid-item"><p></p></div>
<div data-spaces class="grid-item"><p></p></div>
<div data-spaces class="grid-item"><p></p></div>
<div data-spaces class="grid-item"><p></p></div>
<div data-spaces class="grid-item"><p></p></div>
<div data-spaces class="grid-item"><p></p></div>
<div data-spaces class="grid-item"><p></p></div>
</div>
<select data-select class="ai-select" onchange="updateDifficulty()">
<option value="easy">Easy</option>
<option value="medium" selected="selected">Medium</option>
<option value="unbeatable">Unbeatable</option>
<option value="friend">Play with a friend</option>
</select>
</div>
<script src="tictactoe.js" defer></script>
</body>
</html></code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T15:53:52.087",
"Id": "490627",
"Score": "1",
"body": "Welcome to CR! Nice post, but it could be even better if you added the CSS and HTML and converted it to a [runnable stack snippet](https://meta.stackoverflow.com/questions/358992/ive-been-told-to-create-a-runnable-example-with-stack-snippets-how-do-i-do)."
}
] |
[
{
"body": "<p>To get into best practices would require volumes and get you plenty of opinion. At any rate, trying to program too far beyond your understanding is no good so I won't get into particulars. In general, the first thing that occurs to me is that if you're really serious about programming, be good to your future self. Programming starts as a thought process and your thoughts will change as your skills grow. Leave liberal notes (code comments) and six months or six years from now when you ( or perhaps me!) revisit your code, you can reconstruct the process that made the code.</p>\n<p>Kudos on naming your functions and variables so their intent is clear. Your indenting and coding style is consistent and that's important. Now get in the habit of leaving a line or two for each code block.</p>\n<p>I've been programming for the web for a couple of decades and you won't believe the stress of trying to make a minor change to 600 lines of logic you don't understand when the company you're working for bills a million a year and employs dozens of people. Or the shock when you realize it's your own programming!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T07:51:27.627",
"Id": "250740",
"ParentId": "250101",
"Score": "0"
}
},
{
"body": "<p>Here are some suggestions and a <a href=\"https://jsfiddle.net/y0medp6j/2/\" rel=\"nofollow noreferrer\">version</a> that tries to illustrate most of these points.</p>\n<h2>1. Separation of concerns</h2>\n<p>There should be some separation between the code that handles (i) the display and (ii) the underlying game logic and representation of the board. People often use design patterns like <a href=\"https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"nofollow noreferrer\">model-view-controller</a>.</p>\n<p>A classic way of separating them would be to make a class, module or object for the display and another for the underlying game logic. The two objects only call each others' methods in limited, well-defined cases. If you don't want to use objects you can just use function names and comments to have a clearer demarcation between the display/event handling and game logic.</p>\n<p>Instead, you are at various points using the html both to represent data as well as the display. For simple programs, this might work and even simplify the code, but it isn't great for your program because you have functions that you want to be able to handle both an 'imaginary' board and the actual board shown on the screen. For more complex games, it will get more and more complicated to work with the html representation of the board. If you allow every function to change or read the html directly, it becomes hard to track where a particular change is coming from. It also binds your program too closely to a particular representation. For example, imagine you wanted to use <code>canvas</code> or <code>svg</code> graphics instead of just text and css. This would require rewriting everything with the current set-up.</p>\n<p><code>getWin</code> is particularly confusing as it seems to work completely differently depending on whether you pass it the board parameter or not. You may be trying to optimize by only checking rows containing the particular x or y, but it is much easier to write a generic function that will check any board. The function returns a sequence which is either the winning sequence for a win, or the whole grid if it is a draw.</p>\n<h2>2. Small functions that do one thing</h2>\n<p>Your functions seem messy, partly because they are using a mixture of the on-screen representation of the board and a separate array representation to find whether a space is filled or not, but also because they are trying to work in too many different cases. e.g. <code>getWin</code> (as mentioned above) and <code>getSpaceValue</code>, which accepts values of <code>x</code> that are null, an html element, or a number, and <code>y</code> can also be undefined or a number. Most functions should accept inputs of a single type (an exception is sometimes allowing arguments to be omitted with defaults) and return a predictable return value.</p>\n<h2>3. Use modern <code>Array</code> methods more</h2>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter\" rel=\"nofollow noreferrer\"><code>filter</code></a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find\" rel=\"nofollow noreferrer\"><code>find</code></a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map\" rel=\"nofollow noreferrer\"><code>map</code></a> can all help write shorter and more readable code (although can also become unreadable if used to pack too much into a one-liner)</p>\n<h2>4. Use utility functions</h2>\n<p>You may not want to use a library like lodash, but a few standard utility functions would make your code more concise and readable, and using a popular library means that other programmers will be able to read your code and quickly understand what it is doing. For example lodash's <a href=\"https://docs-lodash.com/v4/max-by/\" rel=\"nofollow noreferrer\">maxBy</a> would be useful in choosing the optimal AI move. You can easily write your own if you don't want to use a library.</p>\n<h2>5. Code for determining a win</h2>\n<p>Your code works and is clever in a way but very convoluted! Sometimes you pass it the coords of the current move, but at one point you pass <code>j, j</code> as the coordinates, which mysteriously still works. A simpler and more transparent way to check for a win is to store an array of possible winning sequences (<code>[[0, 1, 2], [3, 4, 5], ...]</code>) and then find the first sequence for which all board squares are set to <code>player</code>.</p>\n<pre><code>const range = [...Array(gridWidth).keys()];\nconst lines = [\n ...range.map(i => range.map(j => i * gridWidth + j)), // rows\n ...range.map(i => range.map(j => i + j * gridWidth)), // columns\n range.map(j => j * (gridWidth + 1)), // diagonal\n range.map(j => (gridWidth - 1) * (j + 1)) // antidiagonal\n ];\nfunction win(player, board) {\n return lines.find(line => line.every(i => board[i] === player));\n}\n</code></pre>\n<p>If you can provide the coordinates of the current move, then you can write a potentially more efficient version of this which checks only the (max.) 4 lines that pass through those coordinates:</p>\n<pre><code>const range = [...Array(gridWidth).keys()];\nfunction win(player, x, y, board) {\n let lines = [\n range.map(i => y * gridWidth + i), // current row\n range.map(i => i * gridWidth + x) // current column\n ];\n if (x === y) { // diagonal\n lines.push(range.map(i => i * gridWidth + i));\n }\n if (gridWidth - x === y) { // antidiagonal\n lines.push(range.map(i => (gridWidth - 1) * (i + 1)));\n }\n return lines.find(line => line.every(i => board[i] === player));\n}\n</code></pre>\n<p>In practice for a 3x3 board this optimisation is unlikely to improve speed (and might worsen it, as the <code>lines</code> array has to be rebuilt each time).</p>\n<h2>6. html event handlers</h2>\n<p>Don't put event handlers in the html when most of your logic is in javascript. It's too messy and confusing. Put all the event handling in javascript.</p>\n<h2>7. Comments / documentation</h2>\n<p>As you are sharing your code and asking for feedback, you should document your code. At the simplest this could be a line or two of comments explaining what each function does and the overall structure. But there is a standard way of documenting called <a href=\"https://jsdoc.app/\" rel=\"nofollow noreferrer\">jsdoc</a> (<a href=\"https://gomakethings.com/whats-the-best-way-to-document-javascript/\" rel=\"nofollow noreferrer\">see also this intro</a>). This is especially important if you for some reason still need to have functions that work in surprising ways.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-26T17:10:44.347",
"Id": "251177",
"ParentId": "250101",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T02:09:20.473",
"Id": "250101",
"Score": "6",
"Tags": [
"javascript",
"html",
"css",
"tic-tac-toe"
],
"Title": "JavaScript Tic Tac Toe implementation"
}
|
250101
|
<p>I have a personal website that I use to share videos and images with friends. Below is a media generator using JavaScript and HTML. Its main purpose is to display one image at a time at the click of a button, but any type of media can be displayed. My goal was to create a fast-loading page to hold all of my media.</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>//VIDEO ARRAY
var oddvideo = [
'video1',
'video2',
'video3',
'video4',
'video5',
];
//AUDIO ARRAY
var oddaudio = [
'audio1',
'audio2',
'audio3',
'audio4',
'audio5',
];
//PHOTO ARRAY
var oddphoto = [
'photo1',
'photo2',
'photo3',
'photo4',
'photo5',
];
//TEXT ARRAY
var oddtext = [
'text1',
'text2',
'text3',
'text4',
'text5',
];
//RANDOM UNUSED ARRAY ITEMS
var Uvideo = [];
var Uaudio = [];
var Uphoto = [];
var Utext = [];
//OLD-NEW VARIABLES
var videoFor = 0;
var audioFor = 0;
var photoFor = 0;
var textFor = 0;
//NEW-OLD VARIABLES
var videoRev = oddvideo.length - 1;
var audioRev = oddaudio.length - 1;
var photoRev = oddphoto.length - 1;
var textRev = oddtext.length - 1;
//GENERATOR FUNCTION
function newThing() {
//RANDOM MODE
if(mode1.checked && (videoCheck.checked || audioCheck.checked || photoCheck.checked || textCheck.checked)) {
if (videoCheck.checked) {
if (!Uvideo.length) Uvideo = [...oddvideo];
var randomY = Uvideo;
}
if (audioCheck.checked) {
if (!Uaudio.length) Uaudio = [...oddaudio];
var randomY = Uaudio;
}
if (photoCheck.checked) {
if (!Uphoto.length) Uphoto = [...oddphoto];
var randomY = Uphoto;
}
if (textCheck.checked) {
if (!Utext.length) Utext = [...oddtext];
var randomY = Utext;
}
var randomX = Math.floor(Math.random() * (randomY.length));
var y = randomY;
var x = randomX;
document.getElementById("thingDisplay").innerHTML = y[x];
// remove randomx from the unused array since it's been used now
randomY.splice(randomX, 1);
}
//OLD-NEW MODE
if(mode2.checked && (videoCheck.checked || audioCheck.checked || photoCheck.checked || textCheck.checked)) {
if(videoCheck.checked) {
document.getElementById('thingDisplay').innerHTML = oddvideo[videoFor];
videoFor++;
if (videoFor >= oddvideo.length) videoFor = 0;
}
if(audioCheck.checked) {
document.getElementById('thingDisplay').innerHTML = oddaudio[audioFor];
audioFor++;
if (audioFor >= oddaudio.length) audioFor = 0;
}
if(photoCheck.checked) {
document.getElementById('thingDisplay').innerHTML = oddphoto[photoFor];
photoFor++;
if (photoFor >= oddphoto.length) photoFor = 0;
}
if(textCheck.checked) {
document.getElementById('thingDisplay').innerHTML = oddtext[textFor];
textFor++;
if (textFor >= oddtext.length) textFor = 0;
}
}
//NEW-OLD MODE
if(mode3.checked && (videoCheck.checked || audioCheck.checked || photoCheck.checked || textCheck.checked)) {
if(videoCheck.checked) {
document.getElementById('thingDisplay').innerHTML = oddvideo[videoRev];
videoRev--;
if (videoRev < 0) videoRev = oddvideo.length - 1;
}
if(audioCheck.checked) {
document.getElementById('thingDisplay').innerHTML = oddaudio[audioRev];
audioRev--;
if (audioRev < 0) audioRev = oddaudio.length - 1;
}
if(photoCheck.checked) {
document.getElementById('thingDisplay').innerHTML = oddphoto[photoRev];
photoRev--;
if (photoRev < 0) photoRev = oddphoto.length - 1;
}
if(textCheck.checked) {
document.getElementById('thingDisplay').innerHTML = oddtext[textRev];
textRev--;
if (textRev < 0) textRev = oddtext.length - 1;
}
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
<div align="center" id='thingDisplay'></div>
<div align="center">
<button onclick="newThing()">New Thing</button>
</div>
<form id="mode">
<label><input type="radio" name="modes" id="mode1"/></label>&nbsp;Random
<br/><label><input type="radio" name="modes" id="mode2"/></label>&nbsp;Old&nbsp;-&nbsp;New
<br/><label><input type="radio" name="modes" id="mode3"/></label>&nbsp;New&nbsp;-&nbsp;Old
</form>
<div align="right">
<form id="categories" align="right">
Video<label>&nbsp;<input type="radio" name="thing" id="videoCheck"/></label><br/>
Audio<label>&nbsp;<input type="radio" name="thing" id="audioCheck"/></label><br/>
Photo<label>&nbsp;<input type="radio" name="thing" id="photoCheck"/></label><br/>
Text<label>&nbsp;<input type="radio" name="thing" id="textCheck"/></label>
</form>
</div>
</body></code></pre>
</div>
</div>
</p>
<h2>A Few Things to Note...</h2>
<ul>
<li><p>I organize the JavaScript arrays with the youngest at the top and oldest at the bottom (with dates, it would look like this:</p>
<pre><code>oddDate = ['Oct. 1', 'Oct. 2', 'Oct. 3', 'Oct. 4', 'Oct. 5'];
</code></pre>
</li>
<li><p>The random mode is <em>pseudo random</em>, and is designed to display all array items once before repeating one.</p>
</li>
<li><p>The old-new and new-old modes move through the arrays from <em>top-to-bottom</em> and <em>bottom-to-top</em>, respectively.</p>
</li>
<li><p>Each mode and category saves its place when you change to a different one. For example, let's say you have the <strong>old-new</strong> mode on and are on <strong>item 3</strong> of the text category. You switch to the photo category, run through the array a bit, then return to the text category. It will display the next item from where you left off previously - i.e. <strong>item 4</strong>. The same can be said for switching between the three modes; they are all independent of each other. This is something I would like to maintain.</p>
</li>
<li><p><strong>One concern</strong> is that the generator and page will get slower and slower as I continue to add more items to the arrays, but I'm unsure if this is legitimate. In the live version, there are 500+ items in each array and more will be added over time.</p>
</li>
</ul>
|
[] |
[
{
"body": "<h2>Overall Feedback</h2>\n<p>This code seems to work acceptably, though the semantics of "old - new" seems reversed.</p>\n<p>The first bullet in the notes states:</p>\n<blockquote>\n<ul>\n<li>I organize the JavaScript arrays with the youngest at the top and oldest at the bottom (with dates, it would look like this: oddDate = ['Oct. 1', 'Oct. 2', 'Oct. 3', 'Oct. 4', 'Oct. 5']; )</li>\n</ul>\n</blockquote>\n<p>Yet the third bullet states:</p>\n<blockquote>\n<ul>\n<li>The old-new and new-old modes move through the arrays from <em>top-to-bottom</em> and <em>bottom-to-top</em>, respectively.</li>\n</ul>\n</blockquote>\n<p>That seems contradictory, since if the oldest was at the <em>bottom</em> then the <em>old-new</em> sorting should start at the end of the array.</p>\n<p>The JavaScript code seems very repetitive - especially in the function <code>newThing()</code> but also the variable names. I'd recommend some changes described later, after the review.</p>\n<h1>Review</h1>\n<h2>Javascript</h2>\n<h3>Variable declarations</h3>\n<p>The code uses some features specific to <a href=\"https://developer.mozilla.org/en-US/docs/Archive/Web/JavaScript/New_in_JavaScript/ECMAScript_2015_support_in_Mozilla\" rel=\"nofollow noreferrer\">ECMAScript-2015</a> (A.K.A. ES-6) like the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax\" rel=\"nofollow noreferrer\">spread syntax</a>. With ES6 variables it is advisable to use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const\" rel=\"nofollow noreferrer\"><code>const</code></a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let\" rel=\"nofollow noreferrer\"><code>let</code></a> to limit the scope of variables and <a href=\"https://softwareengineering.stackexchange.com/q/278652/244085\">avoid bugs</a>. Note that <code>const</code> doesn't mean immutability, but rather that such a variable cannot be re-assigned.</p>\n<h3>Global variables</h3>\n<p>The code references DOM elements using the variables implicitly created from the <em>id</em> attributes - e.g.</p>\n<blockquote>\n<pre><code>if(mode1.checked && (videoCheck.checked || audioCheck.checked || photoCheck.checked || textCheck.checked)) {\n</code></pre>\n</blockquote>\n<p>If you wanted to unit test the JavaScript code then this might make it difficult.</p>\n<h3>Input labels</h3>\n<p>It appears that all of the radio inputs are contained by <code><label></code> inputs, which is good for accessibility (e.g. screenreaders, ability of user to click label to focus/activate the input) however the text next to each input is <em>not</em> within the label. It seems pointless to have a label if the input is the only thing in it.</p>\n<h2>HTML</h2>\n<h3>Inline event handlers</h3>\n<p>The code sets up event handlers within the HTML code:</p>\n<blockquote>\n<pre><code><button onclick="newThing()">New Thing</button>\n</code></pre>\n</blockquote>\n<p>It is better to register event handlers within the JavaScript (e.g. using <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener\" rel=\"nofollow noreferrer\"><code>newButton.addEventListener</code></a> for multiple reasons:</p>\n<ol>\n<li>The logic can be separated from the markup - if multiple teammates worked on the project then one could work on the JavaScript while the other could work on the HTML independently.</li>\n<li>Such handlers can pollute the global namespace which can lead <a href=\"https://stackoverflow.com/a/59539045/1575353\">to strange behavior</a>.</li>\n</ol>\n<h3>Aligning child elements</h3>\n<p>The <code><div></code> elements have <code>align="center"</code> and <code>align="right"</code>. That appears to be <a href=\"https://www.w3.org/TR/html4/struct/tables.html#adef-align-CAPTION\" rel=\"nofollow noreferrer\">a deprecated HTML 4 attribute</a> and no longer supported in HTML 5. <a href=\"https://stackoverflow.com/q/14551305/1575353\">This can be converted to CSS rules</a>. Note that <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/text-align\" rel=\"nofollow noreferrer\"><code>text-align</code></a> applies to block containers<sup><a href=\"https://www.w3.org/TR/CSS21/text.html#alignment-prop\" rel=\"nofollow noreferrer\">1</a></sup>. To center inline elements like images, video, etc. <a href=\"https://stackoverflow.com/a/7055404/1575353\">the <code>display</code> would need to be set to <code>block</code> and <code>margin</code> set to <code>auto</code></a>.</p>\n<h3>Multiple form elements</h3>\n<p>There are two separate <code><form></code> elements. The two could be combined into a single form that contains all elements.</p>\n<h2>Simplifying code</h2>\n<p>The following changes, along with suggestions from the review points above can be used to dramatically decrease the length of the code:</p>\n<ul>\n<li><p>put options into an object that can contain the current index, and make the object a property of an object where the property name (i.e. key) is the type of thing - e.g.</p>\n<pre><code> const options = {\n video: {\n options: [ //VIDEO ARRAY\n 'video1',\n 'video2',\n 'video3',\n 'video4',\n 'video5',\n ],\n currentIndex: -1\n },\n audio: {\n options: [ //AUDIO ARRAY\n 'audio1',\n 'audio2',\n 'audio3',\n 'audio4',\n 'audio5',\n ],\n currentIndex: -1\n },\n photo: {\n options: [ //PHOTO ARRAY\n 'photo1',\n 'photo2',\n 'photo3',\n 'photo4',\n 'photo5',\n ],\n currentIndex: -1\n },\n text: {\n options: [ //TEXT ARRAY\n 'text1',\n 'text2',\n 'text3',\n 'text4',\n 'text5',\n ],\n currentIndex: -1\n },\n }\n</code></pre>\n</li>\n<li><p>instead of using <code>id</code> attributes for the radio buttons, just give them <code>value</code> attributes</p>\n</li>\n<li><p>reference the form elements via <code>document.forms.elements</code></p>\n</li>\n<li><p>determine which radio buttons are selected via <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/RadioNodeList/value\" rel=\"nofollow noreferrer\"><code>RadioNodeList.value</code></a></p>\n</li>\n<li><p>use an <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/output\" rel=\"nofollow noreferrer\"><code><output></code></a> element for the display of the <em>thing</em>.</p>\n</li>\n<li><p>use a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes\" rel=\"nofollow noreferrer\">class</a> to encapsulate the indexes, along with methods to get an item based on the mode</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>class ThingList {\n constructor(items) {\n this.items = items;\n this.randomUnused = [...items];\n this.forwardIndex = 0;\n this.reverseIndex = items.length - 1;\n }\n forwardItem() {\n return this.items[this.forwardIndex++ % (this.items.length)];\n }\n randomItem() {\n if (!this.randomUnused.length) {\n this.randomUnused.push(...this.items);\n }\n const index = Math.floor(Math.random() * this.randomUnused.length)\n return this.randomUnused.splice(index, 1);\n }\n reverseItem() {\n if (this.reverseIndex < 0) {\n this.reverseIndex = this.items.length - 1;\n }\n return this.items[this.reverseIndex--];\n }\n}\nconst options = {\n video: new ThingList([ //VIDEO ARRAY\n 'video1',\n 'video2',\n 'video3',\n 'video4',\n 'video5',\n ]),\n audio: new ThingList([ //AUDIO ARRAY\n 'audio1',\n 'audio2',\n 'audio3',\n 'audio4',\n 'audio5',\n ]),\n photo: new ThingList([ //PHOTO ARRAY\n 'photo1',\n 'photo2',\n 'photo3',\n 'photo4',\n 'photo5',\n ]),\n text: new ThingList([ //TEXT ARRAY\n 'text1',\n 'text2',\n 'text3',\n 'text4',\n 'text5',\n ])\n}\nconst output = document.getElementsByTagName('output')[0];\n//GENERATOR FUNCTION\nfunction newThing() {\n if (!(document.forms.thingSelection.type.value in options)) {\n return false;\n }\n const list = options[document.forms.thingSelection.type.value];\n const method = document.forms.thingSelection.mode.value + 'Item';\n const item = list[method]();\n output.innerHTML = item;\n}\ndocument.getElementsByTagName('button')[0].addEventListener('click', newThing)</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.center {\n text-align: center;\n}\n\n.right {\n text-align: right;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"center\"><output></output></div>\n\n<div class=\"center\">\n <button>New Thing</button>\n</div>\n\n<form name=\"thingSelection\">\n <label><input type=\"radio\" name=\"mode\" value=\"random\" />&nbsp;Random</label>\n <br /><label><input type=\"radio\" name=\"mode\" value=\"forward\" />&nbsp;Old&nbsp;-&nbsp;New</label>\n <br /><label><input type=\"radio\" name=\"mode\" value=\"reverse\" />&nbsp;New&nbsp;-&nbsp;Old</label>\n <div class=\"right\">\n <label>Video&nbsp;<input type=\"radio\" name=\"type\" value=\"video\" /></label><br />\n <label>Audio&nbsp;<input type=\"radio\" name=\"type\" value=\"audio\" /></label><br />\n <label>Photo&nbsp;<input type=\"radio\" name=\"type\" value=\"photo\" /></label><br />\n <label>Text&nbsp;<input type=\"radio\" name=\"type\" value=\"text\" /></label>\n </div>\n</form></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-08T15:50:12.837",
"Id": "491247",
"Score": "0",
"body": "Thank you for taking the time to simplify and correct my code. When testing your snippet, I noticed that switching between the four categories while in any of the three modes maintains the place in each category. However, the three modes no longer appear to be independent of each other, meaning running through the old-new mode affects the order of the new-old mode. Additionally, the random mode is no longer pseudo random and displays repeats before showing all array items. Please adjust your post to account for these things."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T05:36:04.743",
"Id": "491594",
"Score": "1",
"body": "okay - I have updated the snippet example to match the original requirements."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-07T20:22:47.940",
"Id": "250338",
"ParentId": "250102",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "250338",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T03:17:39.033",
"Id": "250102",
"Score": "4",
"Tags": [
"javascript",
"array",
"html",
"random",
"form"
],
"Title": "Displaying Media with HTML and JavaScript"
}
|
250102
|
<p>I've found the following example of an infinite slider to use on a project but as I will have multiple instances I have converted it to a prototype.</p>
<p><strong>The original example</strong>
<a href="https://medium.com/@claudiaconceic/infinite-plain-javascript-slider-click-and-touch-events-540c8bd174f2" rel="nofollow noreferrer">https://medium.com/@claudiaconceic/infinite-plain-javascript-slider-click-and-touch-events-540c8bd174f2</a></p>
<p><strong>My conversion</strong></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>function Slideshow(slider) {
const _self = this;
this.slider = slider;
this.sliderItems = slider.querySelector('.slides');
this.next = slider.querySelector('.control.next');
this.prev = slider.querySelector('.control.prev');
this.posX1 = 0;
this.posX2 = 0;
this.posInitial = null;
this.posFinal = null;
this.threshold = 100;
this.slides = this.sliderItems.getElementsByClassName('slide');
this.slidesLength = this.slides.length;
this.slideSize = this.sliderItems.getElementsByClassName('slide')[0].offsetWidth;
this.firstSlide = this.slides[0];
this.lastSlide = this.slides[this.slidesLength - 1];
this.cloneFirst = this.firstSlide.cloneNode(true);
this.cloneLast = this.lastSlide.cloneNode(true);
this.index = 0;
this.allowShift = true;
// Listen for mousedown events,
// when they happen, call the dragStart function
this.sliderItems.onmousedown = (ev) => {
this.dragStart.call(_self, ev);
}
// Touch Events
this.sliderItems.addEventListener('touchstart', (ev) => {this.dragStart(ev)});
this.sliderItems.addEventListener('touchend', (ev) => {this.dragEnd(ev)});
this.sliderItems.addEventListener('touchmove', (ev) => {this.dragAction(ev)});
// Click Events
this.next.addEventListener('click', () => this.shiftSlide(1));
this.prev.addEventListener('click', () => this.shiftSlide(-1));
// Transition Events
this.sliderItems.addEventListener('transitionend', this.checkIndex.bind(_self));
this.slide.call(this);
}
Slideshow.prototype.slide = function() {
this.cloneSlides.call(this);
}
// Clone Slides
Slideshow.prototype.cloneSlides = function() {
this.sliderItems.appendChild(this.cloneFirst);
this.sliderItems.insertBefore(this.cloneLast, this.firstSlide);
this.slider.classList.add('loaded');
}
// Drag Start
Slideshow.prototype.dragStart = function(event) {
_self = this;
event = event || window.event;
event.preventDefault();
this.posInitial = this.sliderItems.offsetLeft;
if(event.type === 'touchstart') {
this.posX1 = event.touches[0].clientX;
} else {
this.posX1 = event.clientX;
document.onmouseup = (ev) => {
this.dragEnd.call(_self, ev)
}
// document.onmousemove = this.dragAction;
document.onmousemove = (ev) => {
this.dragAction.call(_self, ev);
}
}
}
// Drag Action
Slideshow.prototype.dragAction = function(event) {
event = event || window.event;
if(event.type === 'touchmove') {
this.posX2 = this.posX1 - event.touches[0].clientX;
this.posX1 = event.touches[0].clientX;
} else {
this.posX2 = this.posX1 - event.clientX;
this.posX1 = event.clientX;
}
this.sliderItems.style.left = (this.sliderItems.offsetLeft - this.posX2) + "px";
}
// Drag Action
Slideshow.prototype.dragEnd = function(ev) {
this.posFinal = this.sliderItems.offsetLeft;
if(this.posFinal - this.posInitial < -this.threshold) {
this.shiftSlide(1, 'drag');
} else if(this.posFinal - this.posInitial > this.threshold) {
this.shiftSlide(-1, 'drag');
} else {
this.sliderItems.style.left = (this.posInitial) + "px";
}
document.onmouseup = null;
document.onmousemove = null;
}
// Shift Slide
Slideshow.prototype.shiftSlide = function(dir, action) {
this.sliderItems.classList.add('shifting');
if(this.allowShift) {
if(!action) {
this.posInitial = this.sliderItems.offsetLeft;
}
if(dir == 1) {
this.sliderItems.style.left = (this.posInitial - this.slideSize) + "px";
this.index++;
} else if(dir == -1) {
this.sliderItems.style.left = (this.posInitial + this.slideSize) + "px";
this.index--;
}
};
this.allowShift = false;
}
// Check Index
Slideshow.prototype.checkIndex = function() {
this.sliderItems.classList.remove('shifting');
if(this.index == -1) {
this.sliderItems.style.left = -(this.slidesLength * this.slideSize) + "px";
this.index = this.slidesLength - 1;
}
if(this.index == this.slidesLength) {
this.sliderItems.style.left = -(1 * this.slideSize) + "px";
this.index = 0;
}
this.allowShift = true;
}
window.addEventListener('load', function () {
const slider = document.querySelectorAll('.slider');
slider.forEach((slide) => {
new Slideshow(slide);
})
})</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url('https://fonts.googleapis.com/css?family=Roboto');
:root {
--slider-width: 400px;
--slider-height: 300px;
}
* { box-sizing: border-box; }
body {
height: 100%;
background-color: #7656d6;
color: #333;
font-family: 'Roboto', sans-serif;
text-align: center;
letter-spacing: 0.15em;
font-size: 22px;
}
.slider {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: var(--slider-width);
height: var(--slider-height);
box-shadow: 3px 3px 10px rgba(0,0,0,.2);
}
.wrapper {
overflow: hidden;
position: relative;
width: var(--slider-width);
height: var(--slider-height);
z-index: 1;
}
.slides {
display: flex;
position: relative;
top: 0;
left: calc(var(--slider-width) * -1);
width: 10000px;
}
.slides.shifting {
transition: left .2s ease-out;
}
.slide {
width: var(--slider-width);
height: var(--slider-height);
cursor: pointer;
display: flex;
flex-direction: column;
justify-content: center;
transition: all 1s;
position: relative;
background: #FFCF47;
border-radius: 2px;
}
/*.slider.loaded {*/
.slider.loaded .slide:nth-child(2),
.slider.loaded .slide:nth-child(7) { background: #FFCF47 }
.slider.loaded .slide:nth-child(1),
.slider.loaded .slide:nth-child(6) { background: #7ADCEF }
.slider.loaded .slide:nth-child(3) { background: #3CFF96 }
.slider.loaded .slide:nth-child(4) { background: #a78df5 }
.slider.loaded .slide:nth-child(5) { background: #ff8686 }
/*}*/
.control {
position: absolute;
top: 50%;
width: 50px;
height: 50px;
background: #fff;
border-radius: 50px;
margin-top: -20px;
box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.3);
z-index: 2;
}
.prev,
.next {
background-size: 22px;
background-position: center;
background-repeat: no-repeat;
cursor: pointer;
}
.prev {
background-image: url(https://cdn0.iconfinder.com/data/icons/navigation-set-arrows-part-one/32/ChevronLeft-512.png);
left: -20px;
}
.next {
background-image: url(https://cdn0.iconfinder.com/data/icons/navigation-set-arrows-part-one/32/ChevronRight-512.png);
right: -20px;
}
.prev:active,
.next:active {
transform: scale(.8);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="slider" class="slider">
<div class="wrapper">
<div id="slides" class="slides">
<span class="slide">Slide 1</span>
<span class="slide">Slide 2</span>
<span class="slide">Slide 3</span>
<span class="slide">Slide 4</span>
<span class="slide">Slide 5</span>
</div>
</div>
<a href="" id="prev" class="control prev"></a>
<a href="" id="next" class="control next"></a>
</div></code></pre>
</div>
</div>
</p>
<p>Now it seems I have done the conversion correctly, and works as expected when compared to the original. But I think what I am looking to know is how well have I done this conversion?</p>
<p><strong>Use of <em>this</em></strong>
Using and tracking <em>this</em> is confusing at times. Have I been over-the-top in my use of <em>this</em>?</p>
<p><strong>Calling (or Binding) <em>this</em></strong>
Its a concept that is still new to me, are there areas where I have needed to use <code>call()</code>? Have I used <code>call()</code> when I should be using <code>bind()</code>?</p>
<p>I'm sure there are other areas I am not aware of that can be improved upon, so any input that can help improve this would be excellent.</p>
|
[] |
[
{
"body": "<h1>Question Responses</h1>\n<blockquote>\n<p><em>Using and tracking this is confusing at times. Have I been over-the-top in my use of this?</em></p>\n</blockquote>\n<p>I don't feel it is "over-the-top" though storing a reference to <code>this</code> in another variable is a sign that context isn't bound properly. Bear in mind that an arrow function "<em>Does not have its own bindings to this or super, and should not be used as methods</em>."<sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions\" rel=\"nofollow noreferrer\">1</a></sup> so referencing <code>this</code> within an arrow function declared inside another function will be the same context as outside the arrow function.</p>\n<blockquote>\n<p><em><strong>Calling (or Binding) <em>this</em></strong> Its a concept that is still new to me, are there areas where I have needed to <code>call()</code>? Have I used <code>call()</code> when I should be using <code>bind()</code>?</em></p>\n</blockquote>\n<p>Using <code>call(this)</code> adds unnecessary complexity which could confuse readers. If the function is declared on the object (either directly or via its prototype) then the context when it is called regularly will be set to <code>this</code>.\nThe original code contains this line at the end of the constructor:</p>\n<blockquote>\n<pre><code>this.slide.call(this);\n</code></pre>\n</blockquote>\n<p>That can simply be a regular function call:</p>\n<pre><code>this.slide();\n</code></pre>\n<p>The same is true in the <code>slide</code> method. It can simply call <code> this.cloneSlides()</code>.</p>\n<p>There are places where <code>bind</code> could be used to create a bound function - for example:</p>\n<blockquote>\n<pre><code>this.sliderItems.onmousedown = (ev) => {\n this.dragStart.call(_self, ev);\n}\n</code></pre>\n</blockquote>\n<p>This could simply be a reference without the excess arrow function, since <code>dragStart</code> is a function:</p>\n<pre><code>this.sliderItems.onmousedown = this.dragStart.bind(this);\n</code></pre>\n<p>See the code down below which achieves the same thing without using <code>.call()</code>.</p>\n<h1>Bug</h1>\n<p>Clicking the next and previous anchor links makes the browser navigate to another page. There are various ways to stop this, including calling <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault\" rel=\"nofollow noreferrer\"><code>preventDefault()</code></a> in the Javascript handler. For more solutions see <a href=\"https://stackoverflow.com/q/4387580/1575353\">answers to this StackOverflow question</a>. Actually I see <a href=\"https://codereview.stackexchange.com/q/239510/120114\">you mentioned something about that in your post <em>Showing form on btn click - preventDefault of submit btn, then remove listener</em></a>.</p>\n<h1>Review suggestions</h1>\n<h3>Class syntax</h3>\n<p>The ES6 <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes\" rel=\"nofollow noreferrer\">Class syntax</a> could be used to simplify the prototype syntax.</p>\n<h3>Variable names</h3>\n<p>The constructor method has this line to select items by class name <em>slides</em>:</p>\n<blockquote>\n<pre><code>this.sliderItems = slider.querySelector('.slides');\n</code></pre>\n</blockquote>\n<p>The name <code>sliderItems</code> makes me think it would be multiple elements, but yet it is a single element. A more appropriate name would be something like <code>sliderContainer</code>.</p>\n<h3>DOM selection</h3>\n<p>As I mentioned <a href=\"https://codereview.stackexchange.com/a/205457/120114\">in a previous review</a>, <code>querySelector()</code> can be slower than other DOM methods like <code>getElementById</code> and <code>getElementsByClassName()</code>. So the line above could simply be:</p>\n<pre><code>this.sliderContainer = slider.getElementsByClassName('slides')[0];\n</code></pre>\n<h3>Event handlers</h3>\n<p>The original code registering event handlers like this:</p>\n<blockquote>\n<pre><code>document.onmouseup = (ev) => {\n this.dragEnd.call(_self, ev)\n}\n</code></pre>\n</blockquote>\n<p>While it may not be necessary for this code, a drawback to this approach is that it doesn't allow multiple event handlers to be used. That could be achieved with <code>addEventListener</code> and cleared with <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener\" rel=\"nofollow noreferrer\"><code>removeEventListener()</code></a>. One important thing to note about <code>removeEventListener()</code> is that the <em><code>listener</code></em> to be removed must be a reference to the function added - so for a bound method it needs to be a reference to the function that was bound when <code>addEventListener()</code> was called - typically this requires storing the bound function in a variable so it can be used in both places.</p>\n<h3>Prefer strict equality comparisons</h3>\n<p>There are some comparisons using loose comparisons:</p>\n<blockquote>\n<pre><code>if(dir == 1) {\n</code></pre>\n</blockquote>\n<p>A good habit and recommendation of many style guides is to use strict equality operators (i.e. <code>===</code>, <code>!==</code>). The problem with loose comparisons is that it has <a href=\"https://stackoverflow.com/q/359494\">so many weird rules</a> one would need to memorize in order to be confident in its proper usage.</p>\n<h3>Minimize DOM access</h3>\n<p>In the slideshow constructor there are two lookups for elements with class name '<em>slide</em>' within three lines:</p>\n<blockquote>\n<pre><code>this.slides = this.sliderItems.getElementsByClassName('slide');\nthis.slidesLength = this.slides.length;\nthis.slideSize = this.sliderItems.getElementsByClassName('slide')[0].offsetWidth;\n</code></pre>\n</blockquote>\n<p>DOM access is expensive. The line to set the sliderSize can simply reference <code>this.slides[0]</code> instead of re-querying the DOM.</p>\n<h3>Default parameters</h3>\n<p>ES6 functions can have <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters\" rel=\"nofollow noreferrer\">default parameters</a>.</p>\n<p>The dragAction method can be simplified from:</p>\n<blockquote>\n<pre><code>Slideshow.prototype.dragAction = function(event) {\n\n event = event || window.event;\n</code></pre>\n</blockquote>\n<p>To:</p>\n<pre><code>Slideshow.prototype.dragAction = function(event = window.event) {\n</code></pre>\n<h3>Use of <code>window.event</code></h3>\n<p>There is a note on the MDN documentation for <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Window/event\" rel=\"nofollow noreferrer\"><code>window.event</code></a>:</p>\n<blockquote>\n<p>You <em>should</em> avoid using this property in new code, and should instead use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Event\" rel=\"nofollow noreferrer\">Event</a> passed into the event handler function. This property is not universally supported and even when supported introduces potential fragility to your code.</p>\n</blockquote>\n<h2>Updated Code</h2>\n<p>The code below uses suggestions from above. Notice it has no <code>.call()</code> calls.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>class Slideshow { //function Slideshow(slider) {\n constructor(slider) {\n this.slider = slider;\n this.sliderContainer = slider.getElementsByClassName('slides')[0];\n this.next = slider.querySelector('.control.next');\n this.prev = slider.querySelector('.control.prev');\n\n this.posX1 = 0;\n this.posX2 = 0;\n this.posInitial = null;\n this.posFinal = null;\n this.threshold = 100;\n this.slides = this.sliderContainer.getElementsByClassName('slide');\n this.slidesLength = this.slides.length;\n this.slideSize = this.slides[0].offsetWidth;\n this.firstSlide = this.slides[0];\n this.lastSlide = this.slides[this.slidesLength - 1];\n this.cloneFirst = this.firstSlide.cloneNode(true);\n this.cloneLast = this.lastSlide.cloneNode(true);\n this.index = 0;\n this.allowShift = true;\n //Bound methods for adding and removing event listeners\n this.boundDragAction = this.dragAction.bind(this);\n this.boundDragEnd = this.dragEnd.bind(this);\n\n // Listen for mousedown events,\n // when they happen, call the dragStart function\n //this.sliderItems.onmousedown = this.dragStart.bind(this);\n this.sliderContainer.addEventListener('mousedown', this.dragStart.bind(this));\n\n // Touch Events \n this.sliderContainer.addEventListener('touchstart', this.dragStart.bind(this));\n this.sliderContainer.addEventListener('touchend', this.dragEnd.bind(this));\n this.sliderContainer.addEventListener('touchmove', this.dragAction.bind(this));\n\n // Click Events\n this.next.addEventListener('click', e => this.shiftSlide(1) || e.preventDefault());\n this.prev.addEventListener('click', e => this.shiftSlide(-1) || e.preventDefault());\n\n\n // Transition Events\n this.sliderContainer.addEventListener('transitionend', this.checkIndex.bind(this));\n\n this.slide();\n }\n\n slide() { //Slideshow.prototype.slide = function() {\n this.cloneSlides();\n }\n\n // Clone Slides\n cloneSlides() { //Slideshow.prototype.cloneSlides = function() {\n\n this.sliderContainer.appendChild(this.cloneFirst);\n this.sliderContainer.insertBefore(this.cloneLast, this.firstSlide);\n this.slider.classList.add('loaded');\n\n }\n\n // Drag Start\n dragStart(event) { //Slideshow.prototype.dragStart = function(event) {\n event = event || window.event;\n event.preventDefault();\n this.posInitial = this.sliderContainer.offsetLeft;\n\n if (event.type === 'touchstart') {\n this.posX1 = event.touches[0].clientX;\n } else {\n this.posX1 = event.clientX;\n //document.onmouseup = this.dragEnd.bind(this);\n document.addEventListener('mouseup', this.boundDragEnd);\n // document.onmousemove = this.dragAction;\n //document.onmousemove = this.dragAction.bind(this);\n document.addEventListener('mousemove', this.boundDragAction);\n }\n\n }\n\n // Drag Action\n dragAction(event = window.event) { //Slideshow.prototype.dragAction = function(event) {\n \n\n if (event.type === 'touchmove') {\n this.posX2 = this.posX1 - event.touches[0].clientX;\n this.posX1 = event.touches[0].clientX;\n } else {\n this.posX2 = this.posX1 - event.clientX;\n this.posX1 = event.clientX;\n }\n\n this.sliderContainer.style.left = (this.sliderContainer.offsetLeft - this.posX2) + \"px\";\n }\n\n // Drag Action\n dragEnd(ev) { //Slideshow.prototype.dragEnd = function(ev) {\n this.posFinal = this.sliderContainer.offsetLeft;\n\n if (this.posFinal - this.posInitial < -this.threshold) {\n this.shiftSlide(1, 'drag');\n } else if (this.posFinal - this.posInitial > this.threshold) {\n this.shiftSlide(-1, 'drag');\n } else {\n this.sliderContainer.style.left = (this.posInitial) + \"px\";\n }\n\n //document.onmouseup = null;\n //document.onmousemove = null;\n document.removeEventListener('mouseup', this.boundDragEnd);\n document.removeEventListener('mousemove', this.boundDragAction);\n }\n\n // Shift Slide\n shiftSlide(dir, action) { //Slideshow.prototype.shiftSlide = function(dir, action) {\n this.sliderContainer.classList.add('shifting');\n\n if (this.allowShift) {\n if (!action) {\n this.posInitial = this.sliderContainer.offsetLeft;\n }\n if (dir === 1) {\n this.sliderContainer.style.left = (this.posInitial - this.slideSize) + \"px\";\n this.index++;\n } else if (dir === -1) {\n this.sliderContainer.style.left = (this.posInitial + this.slideSize) + \"px\";\n this.index--;\n }\n };\n\n this.allowShift = false;\n }\n\n\n // Check Index\n checkIndex() { //Slideshow.prototype.checkIndex = function() {\n this.sliderContainer.classList.remove('shifting');\n\n if (this.index === -1) {\n this.sliderContainer.style.left = -(this.slidesLength * this.slideSize) + \"px\";\n this.index = this.slidesLength - 1;\n }\n\n if (this.index === this.slidesLength) {\n this.sliderContainer.style.left = -(1 * this.slideSize) + \"px\";\n this.index = 0;\n }\n\n this.allowShift = true;\n }\n}\n\n\nwindow.addEventListener('load', function() {\n const sliderElements = document.getElementsByClassName('slider');\n\n [...sliderElements].forEach((slide) => {\n new Slideshow(slide);\n })\n})</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>@import url('https://fonts.googleapis.com/css?family=Roboto');\n\n\n\n:root {\n --slider-width: 400px;\n --slider-height: 300px;\n}\n\n* { box-sizing: border-box; }\n\nbody {\n height: 100%;\n background-color: #7656d6;\n color: #333;\n font-family: 'Roboto', sans-serif;\n text-align: center;\n letter-spacing: 0.15em;\n font-size: 22px;\n}\n\n.slider {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n width: var(--slider-width);\n height: var(--slider-height);\n box-shadow: 3px 3px 10px rgba(0,0,0,.2);\n}\n\n.wrapper {\n overflow: hidden;\n position: relative;\n width: var(--slider-width);\n height: var(--slider-height);\n z-index: 1;\n}\n\n.slides {\n display: flex;\n position: relative;\n top: 0;\n left: calc(var(--slider-width) * -1);\n width: 10000px;\n}\n\n.slides.shifting {\n transition: left .2s ease-out;\n}\n\n.slide {\n width: var(--slider-width);\n height: var(--slider-height);\n cursor: pointer;\n display: flex;\n flex-direction: column;\n justify-content: center;\n transition: all 1s;\n position: relative;\n background: #FFCF47;\n border-radius: 2px;\n}\n\n/*.slider.loaded {*/\n.slider.loaded .slide:nth-child(2),\n.slider.loaded .slide:nth-child(7) { background: #FFCF47 }\n.slider.loaded .slide:nth-child(1),\n.slider.loaded .slide:nth-child(6) { background: #7ADCEF }\n.slider.loaded .slide:nth-child(3) { background: #3CFF96 }\n.slider.loaded .slide:nth-child(4) { background: #a78df5 }\n.slider.loaded .slide:nth-child(5) { background: #ff8686 }\n/*}*/\n\n.control {\n position: absolute;\n top: 50%;\n width: 50px;\n height: 50px;\n background: #fff;\n border-radius: 50px;\n margin-top: -20px;\n box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.3);\n z-index: 2;\n}\n\n.prev,\n.next {\n background-size: 22px;\n background-position: center;\n background-repeat: no-repeat;\n cursor: pointer;\n}\n\n.prev {\n background-image: url(https://cdn0.iconfinder.com/data/icons/navigation-set-arrows-part-one/32/ChevronLeft-512.png);\n left: -20px;\n}\n\n.next {\n background-image: url(https://cdn0.iconfinder.com/data/icons/navigation-set-arrows-part-one/32/ChevronRight-512.png);\n right: -20px;\n}\n\n.prev:active,\n.next:active {\n transform: scale(.8);\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"slider\" class=\"slider\">\n <div class=\"wrapper\">\n <div id=\"slides\" class=\"slides\">\n <span class=\"slide\">Slide 1</span>\n <span class=\"slide\">Slide 2</span>\n <span class=\"slide\">Slide 3</span>\n <span class=\"slide\">Slide 4</span>\n <span class=\"slide\">Slide 5</span>\n </div>\n </div>\n <a href=\"\" id=\"prev\" class=\"control prev\"></a>\n <a href=\"\" id=\"next\" class=\"control next\"></a>\n</div></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-02T16:53:15.633",
"Id": "250119",
"ParentId": "250109",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "250119",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T09:12:02.093",
"Id": "250109",
"Score": "2",
"Tags": [
"javascript",
"html",
"ecmascript-6",
"event-handling",
"user-interface"
],
"Title": "Infinite Slider Conversion to Prototype"
}
|
250109
|
<p>I want to return a NumPy array of Element IDs with at least one Node being in the interesting Nodes list.</p>
<p>I have:</p>
<ul>
<li><p>A list of interesting Nodes, <code>Interesting_Nodes</code>.<br />
The size is ~300,000 items.</p>
</li>
<li><p>A list of sublists which represent Node forming an Element, <code>Nodes</code>.<br />
The size is ~1,000,000 lists of ~20 values.</p>
<p><code>Nodes[i]</code> contain the 20 Nodes creating <code>Elements[i]</code>. Which is an integer ID.</p>
</li>
<li><p>A list of Elements, <code>Elements</code>.
The size is ~1,000,000 items.</p>
</li>
</ul>
<p>Here is an example of these lists.</p>
<pre><code>import numpy as np
Interesting_Nodes=[1,2,10,40,400,1000]
Elements=[1,2,3]
Nodes=[[1,20,25],[30,400,35],[500,501,502]]
</code></pre>
<p>In this case the function will return <code>[1,2]</code> because <code>Elements[0]</code> have the Node 1 in the <code>Interesting_Nodes</code> list and <code>Elements[1]</code> contains the Node 400 which is also in the <code>Interesting_Nodes</code> list</p>
<p>I wrote this it seems to work but is very slow. Is there a way to perform this faster?</p>
<pre><code>def recuperation_liste_element_dans_domaine_interet(Interesting_Nodes,Elements,Nodes):
Liste_elements=list([])
for n in Interesting_Nodes:
id=np.where(Nodes==n)
Liste_elements=Liste_elements+list(Elements[id[0]])
nbrListe = list(set(Liste_elements)) # remove all the element duplication
return np.array(nbrListe)
</code></pre>
<p>Another way to perform that I think could be: (be still too slow)</p>
<pre><code>def recuperation_liste_element_dans_domaine_interet(Interesting_Nodes,Elements,Nodes):
Liste_elements=[0]*len(Elements)
compteur=0
j=0
for n in Nodes:
if any(i in Interesting_Nodes for i in n):
Liste_elements[compteur]=Elements[j]
compteur=compteur+1
j=j+1
Liste_elements=Liste_elements[:compteur]
return np.array(Liste_elements)
</code></pre>
|
[] |
[
{
"body": "<p>I'm assuming <code>Elements</code> is always a list of continuous indices from zero to the length of <code>Nodes</code> minus one and thus strictly not needed.</p>\n<p>As a general guideline, explicit loops tend to be slow and also hard to read (and non-Pythonic).</p>\n<p>To solve your problem efficiently, use data structures (namely <a href=\"https://en.wikipedia.org/wiki/Hash_table\" rel=\"nofollow noreferrer\">sets</a>):</p>\n<pre><code>import numpy as np\n\n# Suppose you start with these lists\nu = [1,2,10,40,400,1000]\nn = [[1,20,25],[30,400,35],[500,501,502]]\n\n# Convert them into sets\nu = set(u)\nn = [set(x) for x in n]\n\n# An individual bit is true if the corresponding list is "interesting"\nidx = [bool(a.intersection(u)) for a in n]\n\n# Perhaps convert to integer indices if you wish\nnp.where(idx)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T18:27:21.707",
"Id": "490653",
"Score": "0",
"body": "thanks a lot for your help. I figured out myself that set is much more powerful to do what I expected 1 hour ago ;) But not as \"clean\" as you write. I think it would do the job perfectly ! Thanks again !"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T18:45:56.450",
"Id": "490655",
"Score": "0",
"body": "By the way in fact i need Elements because it is not a continuous list. It coub be [10,1000,300]. But with idx I suppose I can juste write Elements[idx] to have my answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T13:29:49.690",
"Id": "490721",
"Score": "0",
"body": "Did you see an improvement in your \"very slow\" execution time? What kind of improvement did you see?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-04T16:56:33.110",
"Id": "490804",
"Score": "1",
"body": "a HUGE improvement !!! With the previous version, with the \"utltimate\" amount of data, i never manage to reach the end. With the new version, the code finish in few minutes. Thank you again @Juho"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T17:32:08.107",
"Id": "250121",
"ParentId": "250112",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "250121",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T13:17:11.050",
"Id": "250112",
"Score": "2",
"Tags": [
"python"
],
"Title": "find in which sublist of a list are any value of a list in python"
}
|
250112
|
<p>The purpose of this project is to generate an interactive <a href="https://en.wikipedia.org/wiki/Mandelbrot_set" rel="nofollow noreferrer">Mandelbrot set</a>. The user can specify the degree of magnification from the command-line and click on the produced picture to magnify the picture at that point.</p>
<p>Here is a data-type implementation for Complex numbers:</p>
<pre><code>public class Complex
{
private final double re;
private final double im;
public Complex(double re, double im)
{
this.re = re;
this.im = im;
}
public double re()
{
return re;
}
public double im()
{
return im;
}
public double abs()
{
return Math.sqrt(re*re + im*im);
}
public Complex plus(Complex b)
{
double real = re + b.re;
double imag = im + b.im;
return new Complex(real, imag);
}
public Complex times(Complex b)
{
double real = re*b.re - im*b.im;
double imag = re*b.im + im*b.re;
return new Complex(real, imag);
}
public Complex divide(Complex b)
{
double real = (re*b.re + im*b.im) / (b.re*b.re + b.im*b.im);
double imag = (im*b.re - re*b.im) / (b.re*b.re + b.im*b.im);
return new Complex(real, imag);
}
public boolean equals(Complex b)
{
if (re == b.re && im == b.im) return true;
else return false;
}
public Complex conjugate()
{
return new Complex(re, -1.0*im);
}
public String toString()
{
return re + " + " + im + "i";
}
}
</code></pre>
<p>Here is my program:</p>
<pre><code>import java.awt.Color;
public class InteractiveMandelbrot {
private static int checkDegreeOfDivergence(Complex c) {
Complex nextRecurrence = c;
for (int i = 0; i < 255; i++) {
if (nextRecurrence.abs() >= 2) return i;
nextRecurrence = nextRecurrence.times(nextRecurrence).plus(c);
}
return 255;
}
private static Color[] createRandomColors() {
Color[] colors = new Color[256];
double r = Math.random();
int red = 0, green = 0, blue = 0;
for (int i = 0; i < 256; i++) {
red = 13*(256-i) % 256;
green = 7*(256-i) % 256;
blue = 11*(256-i) % 256;
colors[i] = new Color(red,green,blue);
}
return colors;
}
private static void drawMandelbrot(double x, double y, double zoom) {
StdDraw.enableDoubleBuffering();
Color[] colors = createRandomColors();
int resolution = 1000;
int low = -resolution / 2;
int high = resolution / 2;
double xLowScale = x + zoom*(1.0 * low / resolution);
double xHighScale = x + zoom*(1.0 * high / resolution);
double yLowScale = y + zoom*(1.0 * low / resolution);
double yHighScale = y + zoom*(1.0 * high / resolution);
StdDraw.setXscale(xLowScale, xHighScale);
StdDraw.setYscale(yLowScale, yHighScale);
for (int i = low; i < high; i++) {
for (int j = low; j < high; j++) {
double realPart = zoom*(1.0 * i / resolution) + x;
double imaginaryPart = zoom*(1.0 * j / resolution) + y;
Complex c = new Complex(realPart,imaginaryPart);
int degreeOfDivergence = checkDegreeOfDivergence(c);
Color color = colors[degreeOfDivergence];
StdDraw.setPenColor(color);
double radius = 1.0 / (resolution * 2 / zoom);
StdDraw.filledSquare(realPart, imaginaryPart, radius);
}
}
StdDraw.show();
}
public static void main(String[] args) {
double x = Double.parseDouble(args[0]);
double y = Double.parseDouble(args[1]);
int magnifier = Integer.parseInt(args[2]);
double zoom = 1;
drawMandelbrot(x, y, zoom);
while (true) {
if (StdDraw.isMousePressed()) {
x = StdDraw.mouseX();
y = StdDraw.mouseY();
zoom = zoom/magnifier;
drawMandelbrot(x, y, zoom);
}
}
}
}
</code></pre>
<p><a href="https://introcs.cs.princeton.edu/java/stdlib/javadoc/StdDraw.html" rel="nofollow noreferrer">StdDraw</a> is a simple API written by the authors of the book <em>Computer Science An Interdisciplinary Approach</em>. I checked my program and it works. Here is one instance of it.</p>
<p>Input: 0.5 0.5 10</p>
<p>Output (actually a succession of outputs):</p>
<p><a href="https://i.stack.imgur.com/gcty1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gcty1.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/miCf7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/miCf7.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/4zlUX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4zlUX.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/MNx6S.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MNx6S.png" alt="enter image description here" /></a></p>
<p>I used paint to show where I clicked.</p>
<p>From my own previous posts, I already know how to improve <code>Complex</code>. In this post, I am solely interested in the improvement of <code>InteractiveMandelbrot</code>. Is there any way that I can improve my program?</p>
<p>Thanks for your attention.</p>
|
[] |
[
{
"body": "<h2>Comment 1</h2>\n<p>You are not using the <code>r</code> variable in <code>createRandomColors</code> , so there is nothing random in it.</p>\n<h2>Comment 2</h2>\n<pre><code>if (nextRecurrence.abs() >= 2) return i;\n</code></pre>\n<p>You should use brackets after <code>if</code>, don't try to be smart by writing one-liners like this. It will bite you one day when you misread it or edit it without noticing.</p>\n<h2>Comment 3</h2>\n<pre><code>for (int i = low; i < high; i++) {\n for (int j = low; j < high; j++) {\n double realPart = zoom*(1.0 * i / resolution)\n</code></pre>\n<p>The calculation <code>zoom * 1.0 / resolution</code> is calculated 3 times in this double <code>for</code> loop, that's for every pixel on screen I think. It might be worth optimizing your calculations by taking out this factor and calculating it just once.</p>\n<p>Since it doesn't depend on <code>i</code> or <code>j</code>, you could take this calculation out of the loop entirely and so you would calculate it once per screen instead of 3*millions times.</p>\n<p>Likewise, the <code>realPart</code> does not depend on <code>j</code>, so calculate it outside of the <code>j</code> loop to save yourself 999/1000 (approximately) calculations for <code>realPart</code>.</p>\n<p><code>double realPart = zoom*(1.0 * i / resolution) + x;</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T20:47:08.803",
"Id": "250129",
"ParentId": "250113",
"Score": "3"
}
},
{
"body": "<h1>Performance: the Complex class</h1>\n<p>You've mentioned that you already know how to improve it, but the single biggest performance improvement to this program is <em>removing the Complex class</em>. Perhaps it's sad to say goodbye to that class, but run some performance tests and decide.</p>\n<p>On my PC, at the point/zoom <code>0.5, 0.5, 10</code>, the original code runs in 100 - 110 ms per frame. Excluding drawing time, I removed that and just save the colors to an array. Excluding the first run, which is slower as is usual with Java.</p>\n<p>If I write the complex arithmetic inline, without fundamentally changing it, like this:</p>\n<pre><code>private static int checkDegreeOfDivergence(double r, double i) {\n double a = r, b = i;\n \n for (int j = 0; j < 255; j++) {\n if (Math.sqrt(a * a + b * b) >= 2) return j;\n \n double nextA = a * a - b * b + r;\n double nextB = a * b + b * a + i;\n a = nextA;\n b = nextB;\n }\n return 255;\n}\n</code></pre>\n<p>Now it runs in 30 - 40ms per frame. Around 3 times as fast, just by simple refactoring.</p>\n<p>The logic can be slightly optimized, but the improvement from this is much less significant.</p>\n<pre><code>private static int checkDegreeOfDivergence(double r, double i) {\n double a = r, b = i;\n \n for (int j = 0; j < 255; j++) {\n if ((a * a + b * b) >= 4) return j;\n \n double nextA = a * a - b * b + r;\n double nextB = a * b * 2 + i;\n a = nextA;\n b = nextB;\n }\n return 255;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T22:05:39.597",
"Id": "490764",
"Score": "0",
"body": "Just wow! It's a great perspective. Thank you very much."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T16:30:47.323",
"Id": "250155",
"ParentId": "250113",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "250155",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T13:42:58.773",
"Id": "250113",
"Score": "3",
"Tags": [
"java",
"performance",
"beginner",
"fractals"
],
"Title": "Interactive Mandelbrot set pictures"
}
|
250113
|
<p>I am plotting a distribution of 10,000 samples of sum of 100 poisson variables, and overlaying that distribution of the approximate normal distribution. However, the normal distribution line does not show up. I also plotted with sum of 4 variables, in which case it worked. So what is the difference here that makes normal distribution disappear?</p>
<p>Here is my code in the sum of 4 variables case</p>
<pre><code>final = c()
for (i in 1:10000){
sum = sum(rpois(4,2))
final = c(final,sum)
}
dens_final = density(final)
aprox_norm <- dnorm(min(final):max(final), 8,sqrt(8))
plot(dens_final)
lines(aprox_norm, col='red')
</code></pre>
<p>and here is my code of sum of 100 variables</p>
<pre><code>final = c()
for (i in 1:10000){
sum = sum(rpois(100,2))
final = c(final,sum)
}
dens_final = density(final)
aprox_norm <- dnorm(min(final):max(final), 200,sqrt(200))
plot(dens_final)
lines(aprox_norm, col='red')
</code></pre>
<p>I have also attached images of the 2 plots as reference</p>
<p><a href="https://i.stack.imgur.com/1y0E6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1y0E6.png" alt="plot of distribution of sum of 4 variables" /></a></p>
<p><a href="https://i.stack.imgur.com/7fQtI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7fQtI.png" alt="plot of distribution of sum of 100 variables" /></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-05T00:44:52.020",
"Id": "490833",
"Score": "1",
"body": "Your normal distribution is just outside of the plotting window. Use for instance `plot(dens_final, xlim = c(0, 300))` and you'll see it. But that's not really a Code Review question (use [Cross Validated](https://stats.stackexchange.com/) for help on statistics, or [Stack Overflow](https://stackoverflow.com/) for questions about R programming)."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T15:02:02.577",
"Id": "250114",
"Score": "1",
"Tags": [
"r",
"data-visualization"
],
"Title": "normal distribution line does not show up when plotting"
}
|
250114
|
<p>I have a tree in my application from which I need to periodically take a snapshot. I've been using locks so far, but after running into a few deadlock issues I decided to create a lock-free implementation. I'm using a <em>persistent</em> <code>Map</code> implementation together with an <code>actor</code>. My goals were:</p>
<ul>
<li>Consistent snapshot from the <code>Map</code> in a concurrent environment</li>
<li>Flattened tree structure</li>
<li>Thread safety when writing</li>
</ul>
<p>I have completed a preliminary implementation, but I'm not 100% sure that my implementation is idiomatic. I'm not that concerned with complexity, as writes won't be often, but I really need the consistent snapshot and the thread safety. I'd like some guidance on the</p>
<ul>
<li>overall design</li>
<li>idiomatic use of coroutines / persistent data structures</li>
<li>possible design oversights or thread safety issues</li>
<li>anything that I missed (it happened in the past that I wrote something and it turned out that there is a well-known algorithm that does the same but better)</li>
</ul>
<p>So without further ado, this is the implementation:</p>
<pre class="lang-kotlin prettyprint-override"><code>// primary interfaces
import kotlinx.collections.immutable.PersistentList
import kotlinx.collections.immutable.persistentListOf
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.channels.actor
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlin.math.max
interface Tree<D : Any> {
// this is the flattened tree
val descendants: Sequence<TreeNode<D>>
val children: Sequence<TreeNode<D>>
// children can only be created through a reference to a Tree or a TreeNode
fun createChild(data: D? = null): TreeNode<D>
companion object {
fun <D : Any> create(): Tree<D> {
return ConcurrentTree()
}
}
}
interface TreeNode<D : Any> {
val data: D?
val parent: TreeNode<D>?
val hasParent: Boolean
get() = parent != null
val children: Sequence<TreeNode<D>>
fun createChild(data: D? = null): TreeNode<D>
fun remove()
}
</code></pre>
<p>The <code>TreeNode</code> implementations look like this:</p>
<pre class="lang-kotlin prettyprint-override"><code>open class ConcurrentTreeNode<D : Any>(
override val parent: ConcurrentTreeNode<D>? = null,
override val data: D? = null,
private val tree: ConcurrentTree<D>
) : TreeNode<D> {
override val children: Sequence<TreeNode<D>>
get() = tree.children.filter { it.parent == this }
override fun createChild(data: D?): ConcurrentTreeNode<D> {
val parent = this
return ConcurrentTreeNode(
parent = this,
data = data,
tree = tree
).apply {
tree.addChildTo(parent, this)
}
}
override fun remove() {
tree.remove(this)
}
override fun toString(): String {
return "TreeNode(data=$data)"
}
}
private class RootNode<D : Any>(
parent: ConcurrentTreeNode<D>? = null,
data: D? = null,
tree: ConcurrentTree<D>
) : ConcurrentTreeNode<D>(
parent = parent,
data = data,
tree = tree
) {
override fun remove() {
throw RuntimeException("A root node can't be removed.")
}
}
</code></pre>
<p>And this is the <code>Tree</code> implementation:</p>
<pre class="lang-kotlin prettyprint-override"><code>class ConcurrentTree<D : Any> : Tree<D> {
sealed class Message {
data class AddChildTo<D : Any>(
val parent: TreeNode<D>,
val child: TreeNode<D>
) : Message()
data class DeleteChild<D : Any>(
val child: TreeNode<D>
) : Message()
}
private val treeScope = CoroutineScope(Dispatchers.Default + SupervisorJob())
private val actor = treeScope.actor<Message> {
for (msg in channel) { // iterate over incoming messages
when (msg) {
is AddChildTo<*> -> {
val (parent, child) = msg
val lastChildIdx = backend.indexOfLast { it.parent == parent }
val parentIdx = backend.indexOf(parent)
val idx = max(lastChildIdx, parentIdx) + 1
backend = if (idx == backend.lastIndex) {
backend.add(child as TreeNode<D>)
} else {
backend.add(idx, child as TreeNode<D>)
}
}
is Message.DeleteChild<*> -> {
val parent = msg.child.parent
val child = msg.child
val toDelete = backend
.dropWhile { it !== child }
.takeWhile { it === child || it.parent !== parent }
backend = backend.removeAll(toDelete)
}
}
}
}
private val root = RootNode(
parent = null,
data = null,
tree = this
)
private var backend: PersistentList<TreeNode<D>> = persistentListOf(root)
override val descendants: Sequence<TreeNode<D>>
get() = backend.asSequence().drop(1)
override val children: Sequence<TreeNode<D>>
get() = root.children
override fun createChild(data: D?) = root.createChild(data)
fun addChildTo(parent: TreeNode<D>, child: TreeNode<D>) {
treeScope.launch {
actor.send(AddChildTo(parent, child))
}
}
fun remove(node: TreeNode<D>) {
treeScope.launch {
actor.send(Message.DeleteChild(node))
}
}
override fun toString(): String {
return "Tree(descendants=${descendants.joinToString()})"
}
}
</code></pre>
<p>Complexity of operations is <code>O(n)</code>, but more importantly snapshot creation is <code>O(1)</code>, as I'm using a <code>PersistentList</code> as a backend for the whole thing.</p>
<p>The operations (apart from the snapshot) are eventually consistent, but this doesn't matter in my case, I only want to see an operation either completed successfully or the previous state.</p>
<p>Can I do better? Is this idiomatic Kotlin code?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-07T15:09:19.990",
"Id": "491143",
"Score": "0",
"body": "I would be really helpfull for me, if you could include imports to your code snippets so I can copy/paste it in my IDE without having to think about, if we have he same implementation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-07T18:24:02.607",
"Id": "491165",
"Score": "0",
"body": "of course, one moment"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-07T21:37:46.203",
"Id": "491179",
"Score": "0",
"body": "I added the missing imports."
}
] |
[
{
"body": "<p>The following points are my personal, subjective suggestions based on my own experiece and understanding of your domain. I din't check if the solution is feasable but analyzed it for itself.</p>\n<p><strong>Some suggestions</strong> are <strong>explicetely commented or mentioned</strong> in the post's text, some more are in form of the <strong>modified code</strong> in the snippets.</p>\n<h2>Overall Design</h2>\n<ul>\n<li>I would suggest to genereally <strong>rethink</strong> the cases where you decided to go for <strong>nullability</strong>. In my experience it is often better to get an "<em>Optinal is empty but expected XYZ</em>" exception, instead of "<em>NullPointerException at line 123</em>" which tells almost nothing.</li>\n<li>There are so many google results why casting is bad, so I just tell you - <strong>avoid casting</strong> for your <code>Message</code> classes. My proposal is to give the sealed class a Wildcard and the compiler will smart cast for you <code>sealed class Message<A : Any></code></li>\n<li>It is never too annoying to repeat: Favor <strong>composition over inheritance</strong> :) . Your open <code>ConcurrentTreeNode</code> will get complex very fast and all further overrides will not do it any favor.</li>\n<li>Avoid using <code>var</code>s, especially for fields and go for immutability - this gives you (almost always) thread safety</li>\n</ul>\n<h2>Idiomatic use of coroutines</h2>\n<p>There are some things which are obselete and some others, which I would redesign, because I like it the other way - like readability and my own code style.</p>\n<p><strong>Obsolete</strong>:</p>\n<ul>\n<li>Using <code>actor</code> -> Go for <code>channels</code> and <code>flows</code> (<a href=\"https://stackoverflow.com/questions/59412793/kotlin-coroutines-channel-vs-flow\">link</a>), which give you more functionality, interoperability and future support</li>\n</ul>\n<p><strong>I would do it the other way</strong>:</p>\n<ul>\n<li>Create a <code>channel</code> to send and receive messages\n<ul>\n<li>Launch a coroutine which coverts a <code>channel</code> to a <code>flow</code> and consumes every message sequentially</li>\n</ul>\n</li>\n<li>mark <code>send()</code> and <code>resume()</code> functions as <code>suspend</code> to send messages to your channel\n<ul>\n<li>force the caller to make use of coroutine context to be able to send those</li>\n</ul>\n</li>\n</ul>\n<h2>Modified implemention with suggestions</h2>\n<p>Some siggestions are in form of a comment, some are intrinsic in the way I modified the code.</p>\n<pre class=\"lang-kotlin prettyprint-override\"><code>import kotlinx.collections.immutable.PersistentList\nimport kotlinx.collections.immutable.persistentListOf\nimport kotlinx.coroutines.CoroutineScope\nimport kotlinx.coroutines.Dispatchers\nimport kotlinx.coroutines.SupervisorJob\nimport kotlinx.coroutines.channels.Channel\nimport kotlinx.coroutines.flow.collect\nimport kotlinx.coroutines.flow.consumeAsFlow\nimport kotlinx.coroutines.launch\n\ninterface Tree<D : Any> {\n\n // Did you consider Sequences for some special intent? Reading the documentation, their implementation can differ\n // highly and it introduces uncertainty to your code\n\n val descendants: Sequence<TreeNode<D>>\n val children: Sequence<TreeNode<D>>\n\n fun createChild(data: D? = null): TreeNode<D>\n\n companion object {\n\n fun <D : Any> create(): Tree<D> { // I dislike public static code in general\n return ConcurrentTree() // and see no practical use of this method - unless you want to hide the implementations\n }\n }\n}\n\ninterface TreeNode<D : Any> {\n val data: D?\n val parent: TreeNode<D>? // I guess, if data is NULL then parent also has to be NULL (like in RootNode)?\n // If so, bundle them inside same class and make it nullable, so its impossible to break this relation by compiler\n\n val hasParent: Boolean // this would fit better as a function, like 'List.isEmpty()'\n get() = parent != null\n val children: Sequence<TreeNode<D>>\n\n fun createChild(data: D? = null): TreeNode<D>\n\n fun remove() // remove what? A bit hard to find out just by the interface what it does or supposed to remove\n}\n\n// -----------\n\n// Do you really need inheritance? a.k.a - Favor delegation over inheritance\nopen class ConcurrentTreeNode<D : Any>(\n override val parent: ConcurrentTreeNode<D>? = null,\n override val data: D? = null,\n private val tree: ConcurrentTree<D>\n) : TreeNode<D> {\n\n private val treeScope = CoroutineScope(Dispatchers.Default + SupervisorJob())\n\n override val children: Sequence<TreeNode<D>> = tree.children.filter { it.parent == this }\n\n override fun createChild(data: D?): ConcurrentTreeNode<D> {\n return ConcurrentTreeNode(\n parent = this,\n data = data,\n tree = tree\n ).apply {\n treeScope.launch {\n tree.addChildTo(this@ConcurrentTreeNode, this@apply) // very poor to modify fields of classes, even worse doing so after construction\n }\n }\n }\n\n override fun remove() {\n treeScope.launch { tree.remove(this@ConcurrentTreeNode) }\n }\n\n override fun toString(): String = "TreeNode(data=$data)"\n}\n\nprivate class RootNode<D : Any>(\n parent: ConcurrentTreeNode<D>? = null,\n data: D? = null,\n tree: ConcurrentTree<D>\n) : ConcurrentTreeNode<D>(\n parent = parent,\n data = data,\n tree = tree\n) {\n // Design flaw. Maybe rethink the structure and create a special Node which doesn't have this function at all\n override fun remove() = error("A root node can't be removed.")\n}\n\nclass ConcurrentTree<D : Any> : Tree<D> {\n\n sealed class Message<A : Any> { // You need a Wildcard for parent sealed class to maintain concrete types of children\n\n // be careful when using wildcard types with equal letters!\n // Try to use always a different letter in same file and/or class\n\n data class AddChildTo<B : Any>(val parent: TreeNode<B>, val child: TreeNode<B>) : Message<B>()\n\n data class DeleteChild<B : Any>(val child: TreeNode<B>) : Message<B>()\n }\n\n private val channel = Channel<Message<D>>(Channel.BUFFERED) // choose the type you like here\n\n init {\n CoroutineScope(Dispatchers.Default + SupervisorJob()).launch {\n\n fun idx(msg: AddChildTo<D>): Int {\n val lastChildIdx = backend.indexOfLast { it.parent == msg.parent }\n val parentIdx = backend.indexOf(msg.parent)\n return maxOf(lastChildIdx, parentIdx) + 1\n }\n\n fun addDependingOnIdx(message: AddChildTo<D>) {\n when (val idx = idx(message)) { // poor variable naming 'idx'\n backend.lastIndex -> backend.add(message.child)\n else -> backend.add(idx, message.child)\n }\n }\n\n fun toDeleteElements(msg: DeleteChild<D>): List<TreeNode<D>> {\n val parent = msg.child.parent\n val child = msg.child\n return backend\n .dropWhile { it !== child }\n .takeWhile { it === child || it.parent !== parent }\n }\n\n fun modifyBackendFor(message: Message<D>) {\n when (message) {\n is AddChildTo<D> -> addDependingOnIdx(message)\n is DeleteChild<D> -> backend.removeAll(toDeleteElements(message))\n }\n }\n\n channel\n .consumeAsFlow() // hot flow which guarantees sequential operations\n .collect { msg -> modifyBackendFor(msg) }\n }\n }\n\n // private val root = RootNode(parent = null, data = null, tree = this)\n //\n // --> there is no need for a field here and it doesn't harm to create such a small object, unless you go for\n // very large numbers. Fields are like global variables - highly doubtful when not actually needed\n\n private val backend: PersistentList<TreeNode<D>> = persistentListOf(RootNode(tree = this)) // VAL instead of VAR!\n\n override val descendants: Sequence<TreeNode<D>>\n get() = backend.asSequence().drop(1) // not thread safe. Btn: Weird to have un-deterministic behaviour for a getter\n // since the backend can be modified\n\n override val children: Sequence<TreeNode<D>> by lazy { RootNode(tree = this).children }\n\n override fun createChild(data: D?) = RootNode(tree = this).createChild(data)\n\n suspend fun addChildTo(parent: TreeNode<D>, child: TreeNode<D>) = channel.send(AddChildTo(parent, child))\n\n suspend fun remove(node: TreeNode<D>) = channel.send(DeleteChild(node))\n\n override fun toString(): String = "Tree(descendants=${descendants.joinToString()})"\n}\n</code></pre>\n<hr />\n<p>PS: This review & analysis was done in ~4 hours</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T10:16:57.993",
"Id": "491615",
"Score": "0",
"body": "I went for nullability, because this will only be used from Kotlin and the Kotlin devs themsevelves suggest to use `null` in these cases. Thank you for your humongous effort!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T10:19:33.080",
"Id": "491616",
"Score": "0",
"body": "There won't be any more implementors of `ConcurrentTreeNode`, that's why I picked inheritance. I don't see how this can be implemented using composition instead that's not much more complex."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T10:20:41.740",
"Id": "491617",
"Score": "0",
"body": "The only place where I'm using `var`s is the `PersistentList`, but it is necessary because a `PersistentList` is immutable. This is what enables consistent snapshots."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T19:34:40.330",
"Id": "491666",
"Score": "0",
"body": "What are the advantages of a hot `Flow`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T08:58:14.207",
"Id": "492737",
"Score": "0",
"body": "@AdamArold advantage compared to what? Actors will not be supported in near future, so there is the obvious one. The rest is well explained [here](https://stackoverflow.com/questions/59412793/kotlin-coroutines-channel-vs-flow) and [here](https://kotlinlang.org/docs/reference/coroutines/flow.html)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T09:00:16.350",
"Id": "492738",
"Score": "0",
"body": "We don't know what comes next, but in the relevant KEEP they say that `actor` will be present until complex actors arrive."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T10:13:14.817",
"Id": "492743",
"Score": "0",
"body": "@AdamArold good to know, I thought actors will be gone completely. For me flows are easy to use with very familiar api (collections) and at the end of the day, people use whats looks common and simple .."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T10:29:04.763",
"Id": "492745",
"Score": "1",
"body": "I'm following the convo on the relevant issue [here](https://github.com/Kotlin/kotlinx.coroutines/issues/87). As I've figured out your solution is better, because it works in a multiplatform project as well. I didn't use the `Flow` in the end though, just the `Channel` and a coroutine."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-08T09:50:22.903",
"Id": "250358",
"ParentId": "250116",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "250358",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T16:18:36.337",
"Id": "250116",
"Score": "4",
"Tags": [
"tree",
"concurrency",
"kotlin"
],
"Title": "A Concurrent Tree implementation with consistent snapshot capability"
}
|
250116
|
<p>I am trying to solve a problem, which requires me to output the xor of all coefficients in the product of 2 input polynomials. Having seen that the normal <code>O(n^2)</code> multiplication is not optimal, I tried to accomplish the same task by using the Karatsuba method which is equivalent to the one for numbers. It turned out that my code ran even slower in practice than the <code>O(n^2)</code> one, even though it gave me the correct answer.</p>
<pre><code>#include <bits/stdc++.h>
using namespace std;
// In ra đa thức
// Print the polynomial coefficient
void print(vector<int> a) {
for (int &i: a) cout << i << " ";
cout << endl;
}
// Lũy thừa bậc 2 tiếp theo của 1 số
// The next power of 2 of a number
int nextPowerOf2(int n)
{
n--;
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
n++;
return n;
}
// Đưa 2 đa thức về cùng bậc, trả về bậc chung
// Make 2 polynomials to have the same degree
int equalize(vector<int> &a, vector<int> &b) {
int x = a.size(), y = b.size();
if (x > y) {
b.resize(x);
return x;
}
else if (x < y) {
a.resize(y);
return y;
}
return x;
}
// Loại bỏ các hệ số đa thức bậc cao nhất bằng 0
// Remove the highest degree coefficients which are equal
void cuttail(vector<int> &a) {
while (a.back() == 0)
a.pop_back();
}
// Hàm tính tổng 2 đa thức
// Sum of 2 polynomials
vector<int> sum(vector<int> a, vector<int> b) {
int deg = equalize(a, b);
vector<int> c(deg);
for (int i = 0; i < deg; i++)
c[i] = a[i] + b[i];
return c;
}
// Hàm tính hiệu 2 đa thức
// Difference of 2 polynomials
vector<int> diff(vector<int> a, vector<int> b) {
int deg = a.size();
vector<int> c(deg);
for (int i = 0; i < deg; i++)
c[i] = a[i] - b[i];
return c;
}
// Hàm tính tích 2 đa thức
// Product of 2 polynomials
vector<int> prod(vector<int> a, vector<int> b) {
int deg = a.size();
int hdeg = deg/2;
if (deg == 1) return {a[0] * b[0]};
vector<int> a1(hdeg), a2(hdeg), b1(hdeg), b2(hdeg), v(deg), u(deg), w(deg*2);
for (int i = 0; i < deg/2; i++) {
a1[i] = a[i];
b1[i] = b[i];
a2[i] = a[i + hdeg];
b2[i] = b[i + hdeg];
}
u = prod(a1, b1);
v = prod(a2, b2);
w = prod(sum(a1, a2), sum(b1, b2));
w = diff(diff(w, u), v);
vector<int> wdeg(hdeg, 0), vdeg(deg, 0);
w.insert(w.begin(), wdeg.begin(), wdeg.end());
v.insert(v.begin(), vdeg.begin(), vdeg.end());
return sum(u, sum(w, v));
};
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
int n, m;
cin >> n;
vector<int> a(n+1);
for (int &i: a)
cin >> i;
cin >> m;
vector<int> b(m+1);
for (int &i: b)
cin >> i;
int deg = nextPowerOf2(equalize(a, b));
a.resize(deg);
b.resize(deg);
vector<int> c = prod(a, b);
cuttail(c);
int result = 0;
for (int i: c)
result = result ^ i;
cout << result;
return 0;
}
</code></pre>
<p>I highly doubted that the vector allocation is behind the slow speed of multiplication, but I don't know how to fix it. I would appreciate if you can take a look at my code and give me some idea to improve it.</p>
<p><strong>EDIT:</strong> As requested, I have a test case given here:</p>
<p>3 83 86 77 15</p>
<p>4 93 35 86 92 49</p>
<p>The 2 input polynomials are in the degree of 3 and 4 respectively: <span class="math-container">$$83 + 86x + 77x^2 + 15x^3$$</span> and <span class="math-container">$$93 + 35x + 86x^2 + 92x^3 + 49x^4$$</span>
The output is 20731, which is the xor of all coefficients of the product of 2 input polynomials above (7719 xor 10903 xor 17309 xor 19122 xor 19126 xor 12588 xor 5153 xor 735 = 20731)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T17:58:03.630",
"Id": "490649",
"Score": "2",
"body": "@pacmaninbw Thank you a lot. This is an optional self-research homework for in my Programming Technique class, which is provided by my teacher who is involved in training teams for competitive programming competitions. I guess that's why the problem looks like a coding challenge. Unfortunately, the problem is not written in English, so I provided a brief description of the problem in the question above"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T01:22:11.527",
"Id": "490686",
"Score": "2",
"body": "Can you provide some examples for ease of testing?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T01:26:32.777",
"Id": "490688",
"Score": "0",
"body": "@L.F. Yes, the first input polynomial is 3 83 86 77 15 (degree 3, with 4 coefficients from the lowest degree to the highest degree). The second input polynomial is 4 93 35 86 92 49. I have to output 20731, which is 7719 xor 10903 xor 17309 xor 19122 xor 19126 xor 12588 xor 5153 xor 735 = 20731 (xor of all coefficients in the product polynonimal)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T01:27:40.237",
"Id": "490689",
"Score": "2",
"body": "Thanks. You can [edit] the question to present the data in the required format."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T06:26:26.770",
"Id": "490700",
"Score": "2",
"body": "`turned out that my code ran even slower in practice than the O(n^2) one` as in *where the n² algorithm took 2 hours, my Karatsuba implementation overtaxed my patience*? The cross-over points are pretty high in integer multiplication; eye-balling the overhead, I'd not expect them to be lower here. Padding may not be the best idea. I somehow doubt `int` is appropriate for the product coefficients when the degree is high enough to warrant use of Karatsuba's."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T09:24:51.997",
"Id": "490706",
"Score": "0",
"body": "(Regarding the original problem: I don't need the final coefficients to tell whether their XOr is odd - #odd original coefficients in each polynomial will do. Do I *need* them for the full XOr?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T11:31:26.023",
"Id": "490717",
"Score": "0",
"body": "@greybeard I did think about it, but I see that XOR is not distributive with addition, or in other words, ```(a+b) XOR c``` is different from ```a XOR c + b XOR c```, so it's difficult to think of another solution here (I read about XOR but still cannot find a useful property of that operator)"
}
] |
[
{
"body": "<h1>Algorithmic complexity is not a good indicator of real-world performance</h1>\n<p>When you have to choose between an <span class=\"math-container\">\\$\\mathcal{O}(N^2)\\$</span> or <span class=\"math-container\">\\$\\mathcal{O}(N^{1.58})\\$</span> algorithm, you would think that the latter is faster, however that is only true for <em>sufficiently large</em> values of <span class=\"math-container\">\\$N\\$</span>. In practice, unless you have more than a thousand digits to multiply, the simple <span class=\"math-container\">\\$\\mathcal{O}(N^2)\\$</span> algorithm is faster.</p>\n<h1>Don't make the inputs of equal length</h1>\n<p>If you want to multiply a polynomial of degree 100 with a polynomial of degree 1, then your program will expand the latter polynomial to degree 100, and then do the multiplication. But most of the work is now wasted on multiplying things by 0. Try to make your algorithm work for vectors of different lengths.</p>\n<h1>Avoid creating unnecessary intermediate results</h1>\n<p>If the goal is purely to get the XOR of the coefficients of the product, then you don't actually need to store the product before calculating the final result of the XORs. Instead, with a trivial algorithm, you can just simply do:</p>\n<pre><code>int result{};\nfor (auto i: a)\n for (auto j: b)\n result ^= i * j;\n</code></pre>\n<p>This avoids creating a temporary vector, which requires heap memory allocation, and avoids an additional pass over the temporary result to get the final answer. Again, this doesn't reduce algorithmic complexity, but it does reduce how many cycles you have to spend for each iteration of the <span class=\"math-container\">\\$\\mathcal{O}(N^2)\\$</span> algorithm even further.</p>\n<h1>Use a hybrid approach</h1>\n<p>In your implementation of Karatsuba's algorithm, you have this line:</p>\n<pre><code>if (deg == 1) return {a[0] * b[0]};\n</code></pre>\n<p>Knowing that for smaller vectors, a naive algorithm is actually faster, you can replace this line with:</p>\n<pre><code>if (deg < CUTOFF)\n return naive_product(a, b);\n</code></pre>\n<p>Where you set the constant <code>CUTOFF</code> to some value that you have to determine experimentally. This approach is similar to those taken by state-of-the-art sorting algorithms, which typically also use a divide-and-conquer approach and when the problem gets small enough, they will use <a href=\"https://en.wikipedia.org/wiki/Insertion_sort\" rel=\"nofollow noreferrer\">insertion sort</a>.</p>\n<h1>Pass vectors by <code>const</code> reference</h1>\n<p>Most of your functions like <code>prod()</code>, <code>sum()</code>, and so on, take parameters by value. This is very inefficient, since it means a copy of the vectors used as input arguments will be made. Pass them by <code>const</code> reference instead, it's as simple as:</p>\n<pre><code>vector<int> sum(const vector<int> &a, const vector<int> &b) {\n ...\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T11:27:18.970",
"Id": "490716",
"Score": "0",
"body": "Thanks for your comment. Yes, except for the given test, I was given that there are 5 hidden tests with the ith test having 2 polynomials of degree ```10^i```, so Karatsuba is the solution I thought that is appropriate here. I have an issue here: I did think about avoiding to create intermediate results, but it is the fact that ```(a + b) XOR c``` is not equal to ```a XOR c + b XOR c```, so I really can't think of a better solution"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T08:57:54.147",
"Id": "250143",
"ParentId": "250117",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "250143",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T16:30:59.853",
"Id": "250117",
"Score": "7",
"Tags": [
"c++",
"performance",
"beginner",
"algorithm",
"array"
],
"Title": "Polynomial multiplication using Karatsuba method"
}
|
250117
|
<p>I am trying to speed up the performance of this program. The only file we can change is dictionary.c</p>
<p>The problem is basically to load a dictionary and then do a spell check on submitted text. The approach we used was to assume the dictionary would be already sorted (it is)and then create a hash table in a trie and load the dictionary in a number of tries. All of that to make the check function fast. Unfortuanately, while the program runs it's performance is not that great. You can see how it performs relative to other submissions here: <a href="https://speller.cs50.net/cs50/problems/2020/x/challenges/speller" rel="nofollow noreferrer">https://speller.cs50.net/cs50/problems/2020/x/challenges/speller</a> I'm listed as rsail at number 3004</p>
<p>speller.c</p>
<pre><code>// Implements a spell-checker
#include <ctype.h>
#include <stdio.h>
#include <sys/resource.h>
#include <sys/time.h>
#include "dictionary.h"
// Undefine any definitions
#undef calculate
#undef getrusage
// Default dictionary
#define DICTIONARY "dictionaries/large"
// Prototype
double calculate(const struct rusage *b, const struct rusage *a);
int main(int argc, char *argv[])
{
// Check for correct number of args
if (argc != 2 && argc != 3)
{
printf("Usage: ./speller [DICTIONARY] text\n");
return 1;
}
// Structures for timing data
struct rusage before, after;
// Benchmarks
double time_load = 0.0, time_check = 0.0, time_size = 0.0, time_unload = 0.0;
// Determine dictionary to use
char *dictionary = (argc == 3) ? argv[1] : DICTIONARY;
// Load dictionary
getrusage(RUSAGE_SELF, &before);
bool loaded = load(dictionary);
getrusage(RUSAGE_SELF, &after);
// Exit if dictionary not loaded
if (!loaded)
{
printf("Could not load %s.\n", dictionary);
return 1;
}
// Calculate time to load dictionary
time_load = calculate(&before, &after);
// Try to open text
char *text = (argc == 3) ? argv[2] : argv[1];
FILE *file = fopen(text, "r");
if (file == NULL)
{
printf("Could not open %s.\n", text);
unload();
return 1;
}
// Prepare to report misspellings
printf("\nMISSPELLED WORDS\n\n");
// Prepare to spell-check
int index = 0, misspellings = 0, words = 0;
char word[LENGTH + 1];
// Spell-check each word in text
for (int c = fgetc(file); c != EOF; c = fgetc(file))
{
// Allow only alphabetical characters and apostrophes
if (isalpha(c) || (c == '\'' && index > 0))
{
// Append character to word
word[index] = c;
index++;
// Ignore alphabetical strings too long to be words
if (index > LENGTH)
{
// Consume remainder of alphabetical string
while ((c = fgetc(file)) != EOF && isalpha(c));
// Prepare for new word
index = 0;
}
}
// Ignore words with numbers (like MS Word can)
else if (isdigit(c))
{
// Consume remainder of alphanumeric string
while ((c = fgetc(file)) != EOF && isalnum(c));
// Prepare for new word
index = 0;
}
// We must have found a whole word
else if (index > 0)
{
// Terminate current word
word[index] = '\0';
// Update counter
words++;
// Check word's spelling
getrusage(RUSAGE_SELF, &before);
bool misspelled = !check(word);
getrusage(RUSAGE_SELF, &after);
// Update benchmark
time_check += calculate(&before, &after);
// Print word if misspelled
if (misspelled)
{
printf("%s\n", word);
misspellings++;
}
// Prepare for next word
index = 0;
}
}
// Check whether there was an error
if (ferror(file))
{
fclose(file);
printf("Error reading %s.\n", text);
unload();
return 1;
}
// Close text
fclose(file);
// Determine dictionary's size
getrusage(RUSAGE_SELF, &before);
unsigned int n = size();
getrusage(RUSAGE_SELF, &after);
// Calculate time to determine dictionary's size
time_size = calculate(&before, &after);
// Unload dictionary
getrusage(RUSAGE_SELF, &before);
bool unloaded = unload();
getrusage(RUSAGE_SELF, &after);
// Abort if dictionary not unloaded
if (!unloaded)
{
printf("Could not unload %s.\n", dictionary);
return 1;
}
// Calculate time to unload dictionary
time_unload = calculate(&before, &after);
// Report benchmarks
printf("\nWORDS MISSPELLED: %d\n", misspellings);
printf("WORDS IN DICTIONARY: %d\n", n);
printf("WORDS IN TEXT: %d\n", words);
printf("TIME IN load: %.2f\n", time_load);
printf("TIME IN check: %.2f\n", time_check);
printf("TIME IN size: %.2f\n", time_size);
printf("TIME IN unload: %.2f\n", time_unload);
printf("TIME IN TOTAL: %.2f\n\n",
time_load + time_check + time_size + time_unload);
// Success
return 0;
}
// Returns number of seconds between b and a
double calculate(const struct rusage *b, const struct rusage *a)
{
if (b == NULL || a == NULL)
{
return 0.0;
}
else
{
return ((((a->ru_utime.tv_sec * 1000000 + a->ru_utime.tv_usec) -
(b->ru_utime.tv_sec * 1000000 + b->ru_utime.tv_usec)) +
((a->ru_stime.tv_sec * 1000000 + a->ru_stime.tv_usec) -
(b->ru_stime.tv_sec * 1000000 + b->ru_stime.tv_usec)))
/ 1000000.0);
}
}
</code></pre>
<p>dictionary.h</p>
<pre><code>// Declares a dictionary's functionality
#ifndef DICTIONARY_H
#define DICTIONARY_H
#include <stdbool.h>
// Maximum length for a word
// (e.g., pneumonoultramicroscopicsilicovolcanoconiosis)
#define LENGTH 45
// Prototypes
bool check(const char *word);
unsigned int hash(const char *word);
bool load(const char *dictionary);
unsigned int size(void);
bool unload(void);
#endif // DICTIONARY_H
</code></pre>
<p>dictionary.c</p>
<p>// Implements a dictionary's functionality</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include "dictionary.h"
#include <limits.h>
#include <math.h>
#include <ctype.h>
#define MAXWORDS 200000
#define MAXBUCKETS 511
unsigned int numberOfWords = 0;
int target;
unsigned int N = 1; //number of buckets in hash table. (a function of how big the dictionary is)
// we modified nodeWords to containe more information
typedef struct nodeWords
{
char *word;
char *wordEnd;
int index;
struct nodeWords *left;
struct nodeWords *right;
} nodeWords;
nodeWords *headHashNode;
nodeWords **nodeArray;
nodeWords *nodeHash;
nodeWords *nodeTri;
nodeWords **nodeHistory;
int hashBuckets;
int hashFlag = 0;
char (*words)[LENGTH + 1] = NULL;
long int findSize(const char *file_name);
unsigned int size(void);
unsigned int hash(const char *word);
bool check(const char *word);
bool unload(void);
nodeWords *leftRightAddress(int buckets, nodeWords *nodeGen);
int *nextBuckets(int power, int kick, int oob, int buckets);
//used for testing
typedef struct nodeNumbers
{
int number;
struct nodeNumbers *left;
struct nodeNumbers *right;
} nodeNumbers;
// Returns true if word is in dictionary else false
bool check(const char *word)
{
// we created tries for both the hash table and dictionary
int lc = strlen(word);;
char *lcWord = malloc(46);
for (int i = 0; i < lc; i++)
{
lcWord[i] = tolower(word[i]);
}
lcWord[lc] = '\0';
int nodeIdx = hash(lcWord);
if (nodeIdx < 0)
{
free(lcWord);
return false;
}
nodeWords *searchNode;
searchNode = nodeArray[nodeIdx];
bool searchContinues = true, found = false;
// this is our binary searech
do
{
if (strcmp(lcWord, searchNode->word) == 0)
{
searchContinues = false;
found = true;
}
else if (strcmp(lcWord, searchNode->word) < 0)
{
if (searchNode->left == NULL)
{
searchContinues = false;
}
else
{
searchNode = searchNode->left;
}
}
else
{
if (searchNode->right == NULL)
{
searchContinues = false;
}
else
{
searchNode = searchNode->right;
}
}
}
while (searchContinues);
free(lcWord);
return found;
}
unsigned int hash(const char *word)
{
// we assume the dictionary is already sorted
nodeWords *node;
node = headHashNode;
int idx = -9;
int lc = strlen(word);;
char *lcWord = malloc(46);
bool rightFlag = false;
bool leftFag = false;
for (int i = 0; i < lc; i++)
{
lcWord[i] = tolower(word[i]);
}
lcWord[lc] = '\0';
// printf("HASH\n");
// printf("%s %s %s\n",lcWord, words[0],words[numberOfWords - 1]);
if (strcmp(lcWord, words[0]) < 0 || strcmp(lcWord, words[numberOfWords - 1]) > 0)
{
free(lcWord);
return -1;
}
do
{
// printf("%s %s %s %d\n",lcWord, node->word,node->wordEnd,strcmp(lcWord,node->word));
if (strcmp(lcWord, node->word) == 0)
{
//printf("FOUND 0\n");
free(lcWord);
return node->index;
}
else if (strcmp(lcWord, node->word) > 0)
{
if (strcmp(lcWord, node->wordEnd) <= 0 || node->right == NULL)
{
//printf("FOUND 1\n");
free(lcWord);
return node->index;
}
// printf("RIGHT\n");
node = node->right;
}
else
{
// printf("LEFT\n");
if (node->left == NULL)
{
return -1;
}
else
{
node = node->left;
}
}
}
while (true);
}
// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
// messy but does the job
// printf("enter load\n");
//find number of bytes in dictionary file
long int dictionarySize = findSize(dictionary);
if (dictionarySize == -1)
{
//printf("File Not Found 0!\n");
return false;
}
//printf("dictsize %ld\n",dictionarySize);
//allocate memory to read in entire file
char *data = malloc(dictionarySize + 1);
//open dictionary file
int filedesc = open(dictionary, O_RDONLY);
if (filedesc < 0)
{
//printf("File Not Found 1!\n");
return false;
}
//trying to gain load speed
//read entire dictionary
int bytesRead = read(filedesc, data, dictionarySize);
close(filedesc);
//printf("bytes %d\n",bytesRead);
FILE *fp;
fp = fopen("dict.txt", "w+");
int row = 0;
int col = 0;
words = malloc(MAXWORDS * (LENGTH + 1));
//parse dictionary string based on new lines and replace new line char with \0 (null)
for (int i = 0; i < dictionarySize ; i++)
{
words[row][col] = data[i];
col++;
if (data[i] == 0x0a)
{
words[row][col - 1] = '\0';
//printf("%d %s\n", row , words[row]);
col = 0;
row++;
}
}
//printf("col = %d %s\n",col,words[row-1] );
if (col != 0)
{
words[row][col] = '\0';
//printf("extra %d %s\n", row , words[row]);
}
else
{
row--;
}
numberOfWords = row + 1;
fclose(fp);
free(data);
//compute number of hash buckets
target = (int) pow(2, ceil(log2(pow(numberOfWords, .5)))) - 1; //target = number of buckets per tri (except maybe the last one.)
if (target == 0)
{
target = 1;
}
hashBuckets = ceil((float)numberOfWords /
target); // hashBuckets = number of buckets for hash table - each bucket will point to a tri
//printf("words %d target %d hashbuckets %d\n",numberOfWords,target,hashBuckets);
if (hashBuckets > MAXBUCKETS)
{
printf("FATAL ERROR: Too many hash buckets\n");
exit(-1);
}
//allocate space for hash buckets
int cnt = 0;
nodeHash = malloc(hashBuckets * sizeof(*nodeHash));
for (int i = 0; i < numberOfWords ; i = i + target)
{
int endIdx = (i + target - 1 < numberOfWords) ? i + target - 1 : numberOfWords - 1;
nodeHash[cnt].word = malloc((strlen(words[i]) + 1) * sizeof(char));
strcpy(nodeHash[cnt].word, words[i]);
nodeHash[cnt].wordEnd = malloc((strlen(words[endIdx]) + 1) * sizeof(char));
strcpy(nodeHash[cnt].wordEnd, words[endIdx]);
cnt++;
}
headHashNode = leftRightAddress(hashBuckets, nodeHash);
int triCnt;
cnt = 0;
nodeArray = malloc(hashBuckets * sizeof(*nodeHash));
nodeHistory = malloc(hashBuckets * sizeof(*nodeHash));
for (int i = 0; i < numberOfWords; i = i + target)
{
nodeTri = malloc(target * sizeof(*nodeTri));
nodeHistory[cnt] = nodeTri;
triCnt = 0;
for (int j = i, stopper = (i + target < numberOfWords) ? i + target : numberOfWords; j < stopper; j++)
{
nodeTri[triCnt].word = malloc((strlen(words[j]) + 1) * sizeof(char));
strcpy(nodeTri[triCnt].word, words[j]);
int endIdx = (j + target - 1 < numberOfWords) ? j + target - 1 : numberOfWords - 1;
nodeTri[triCnt].wordEnd = malloc((strlen(words[endIdx]) + 1) * sizeof(char));
strcpy(nodeTri[triCnt].wordEnd, words[endIdx]);
triCnt++;
}
nodeArray[cnt] = leftRightAddress(triCnt, nodeTri);
cnt++;
}
return true;
}
// Returns number of words in dictionary if loaded else 0 if not yet loaded
unsigned int size(void)
{
return numberOfWords;
}
// Unloads dictionary from memory, returning true if successful else false
bool unload(void)
{
// quick and easy
for (int i = 0; i < hashBuckets; i++)
{
free(nodeHash[i].word);
free(nodeHash[i].wordEnd);
}
free(nodeHash);// TODO
int cnt = 0;
for (int i = 0; i < hashBuckets; i++)
{
nodeTri = nodeHistory[i];
for (int j = 0; j < target; j++)
{
if (cnt < numberOfWords)
{
free(nodeTri[j].word);
free(nodeTri[j].wordEnd);
}
cnt++;
}
free(nodeTri);
}
free(words);
free(nodeArray);
free(nodeHistory);
return true;
}
long int findSize(const char *file_name)
{
// opening the file in read mode
FILE *fp = fopen(file_name, "r");
// checking if the file exist or not
if (fp == NULL)
{
//printf("File Not Found!\n");
return -1;
}
fseek(fp, 0L, SEEK_END);
// calculating the size of the file
long int size = ftell(fp);
// closing the file
fclose(fp);
return size;
}
nodeWords *leftRightAddress(int buckets, nodeWords *nodeGen)
{
//did not use recursion for speed
bool printFlag = false;
int numbers[buckets] ;
for (int i = 0; i < buckets; i++)
{
numbers[i] = i;
}
int loops = (int)(log2(buckets) + .000001),
cnt = 0,
oob = 0,
rob = 0;
int idx, ilx = -100, irx = -100,
jdx, jlx = -100, jrx = -100,
kdx, klx = -100, krx = -100,
ldx, llx = -100, lrx = -100,
mdx, mlx = -100, mrx = -100,
ndx, nlx = -100, nrx = -100,
odx, olx = -100, orx = -100,
pdx, plx = -100, prx = -100,
qdx, qlx = -100, qrx = -100;
int ikick = 0, ijmp = 0,
jkick = 0, jjmp = 0,
kkick = 0, kjmp = 0,
lkick = 0, ljmp = 0,
mkick = 0, mjmp = 0,
nkick = 0, njmp = 0,
okick = 0, ojmp = 0,
pkick = 0, pjmp = 0,
qkick = 0, qjmp = 0;
int *nextBucket;
bool oddlot = false;
int used[buckets];
if (buckets != (int)pow(2, loops + 1) - 1)
{
for (int i = 0; i < buckets; i++)
{
used[i] = -99;
}
oddlot = true;
}
if (printFlag)
{
printf("loops= %d buckets=%d \n", loops, buckets);
}
for (int i = 0; i < buckets; i++)
{
if (printFlag)
{
printf("%d %s %p \n", i, nodeGen[i].word, &nodeGen[i]);
}
}
//comments
for (int i = 0; i < 1; i++)
{
if (cnt < buckets)
{
idx = pow(2, loops) - 1;
nodeGen[idx].index = idx;
if (printFlag)
{
printf("index = %d idx = %d word = %s cnt = %d \n", nodeGen[idx].index, idx, nodeGen[idx].word, cnt);
}
cnt ++;
if (loops > 0)
{
nextBucket = nextBuckets(loops - 1, jkick, oob, buckets);
if (printFlag)
{
printf("NEXT %d %d %s\n", nextBucket[0], nextBucket[1], nodeGen[idx].word);
}
nodeGen[idx].left = &nodeGen[nextBucket[0]];
nodeGen[idx].right = &nodeGen[nextBucket[1]];
//printf("VALUES %f %d idx=%d i=%d\n",pow(2,loops)-1,oddlot,idx,i);
if (idx > pow(2, loops) - 1 && oddlot)
{
used[idx] = idx;
if (nextBucket[0] <= pow(2, loops) - 1 || used[nextBucket[0]] == nextBucket[0])
{
nodeGen[idx].left = NULL;
}
}
if (nextBucket[1] <= idx)
{
nodeGen[idx].right = NULL;
}
}
else
{
nodeGen[idx].left = NULL;
nodeGen[idx].right = NULL;
}
if (printFlag)
{
printf("node idx = %p %d left: %p %d right: %p %d oob: %d rob: %d\n\n", &nodeGen[idx], idx, nodeGen[idx].left, ilx,
nodeGen[idx].right, irx, oob, rob);
}
}
//comments
for (int j = 0; j < ((buckets > 1) ? 2 : 0); j++)
{
if (cnt < buckets)
{
jdx = pow(2, loops - 1) - 1 + jkick;
jkick = jkick + pow(2, loops);
if (jdx > buckets - 1 - oob)
{
while (jdx > buckets - 1 - oob)
{
jdx = jdx - 1 ;
}
oob++;
}
nodeGen[jdx].index = jdx;
if (printFlag)
{
printf("index = %d jdx = %d word = %s cnt = %d \n", nodeGen[jdx].index, jdx, nodeGen[jdx].word, cnt) ;
}
cnt ++;
if (loops > 1)
{
nextBucket = nextBuckets(loops - 2, kkick, oob, buckets);
if (printFlag)
{
printf("NEXT %d %d\n", nextBucket[0], nextBucket[1]);
}
nodeGen[jdx].left = &nodeGen[nextBucket[0]];
nodeGen[jdx].right = &nodeGen[nextBucket[1]];
if (jdx > pow(2, loops) - 1 && oddlot)
{
used[jdx] = jdx;
if (nextBucket[0] <= pow(2, loops) - 1 || used[nextBucket[0]] == nextBucket[0])
{
nodeGen[jdx].left = NULL;
}
if (nextBucket[1] <= jdx)
{
nodeGen[jdx].right = NULL;
}
}
}
else
{
nodeGen[jdx].left = NULL;
nodeGen[jdx].right = NULL;
}
if (printFlag)
{
printf("node = %p %d left: %p %d right: %p %d\n\n", &nodeGen[jdx], jdx, nodeGen[jdx].left, jlx, nodeGen[jdx].right, jrx);
}
}
//comments
for (int k = 0; k < ((buckets > 3) ? 2 : 0); k++)
{
if (cnt < buckets)
{
kdx = pow(2, loops - 2) - 1 + kkick;
kkick = kkick + pow(2, loops - 1);
if (kdx > buckets - 1 - oob)
{
while (kdx > buckets - 1 - oob)
{
kdx = kdx - 1 ;
}
oob++;
}
nodeGen[kdx].index = kdx;
if (printFlag)
{
printf("index = %d kdx = %d word = %s cnt = %d \n", nodeGen[kdx].index, kdx, nodeGen[kdx].word, cnt) ;
}
cnt ++;
if (loops > 2)
{
nextBucket = nextBuckets(loops - 3, lkick, oob, buckets);
if (printFlag)
{
printf("NEXT %d %d\n", nextBucket[0], nextBucket[1]);
}
nodeGen[kdx].left = &nodeGen[nextBucket[0]];
nodeGen[kdx].right = &nodeGen[nextBucket[1]];
if (kdx > pow(2, loops) - 1 && oddlot)
{
used[kdx] = kdx;
if (nextBucket[0] <= pow(2, loops) - 1 || used[nextBucket[0]] == nextBucket[0])
{
nodeGen[kdx].left = NULL;
}
if (nextBucket[1] <= kdx)
{
nodeGen[kdx].right = NULL;
}
}
}
else
{
nodeGen[kdx].left = NULL;
nodeGen[kdx].right = NULL;
}
if (printFlag)
{
printf("node = %p %d left: %p %d right: %p %d\n\n", &nodeGen[kdx], kdx, nodeGen[kdx].left, klx, nodeGen[kdx].right, krx);
}
}
//comments
for (int l = 0; l < ((buckets > 7) ? 2 : 0); l++)
{
if (cnt < buckets)
{
ldx = pow(2, loops - 3) - 1 + lkick;
lkick = lkick + pow(2, loops - 2);
if (ldx > buckets - 1 - oob)
{
while (ldx > buckets - 1 - oob)
{
ldx = ldx - 1;
}
oob++;
}
nodeGen[ldx].index = ldx;
if (printFlag)
{
printf("index = %d ldx = %d word = %s cnt = %d \n", nodeGen[ldx].index, ldx, nodeGen[ldx].word, cnt) ;
}
cnt ++;
if (loops > 3)
{
nextBucket = nextBuckets(loops - 4, mkick, oob, buckets);
if (printFlag)
{
printf("NEXT %d %d\n", nextBucket[0], nextBucket[1]);
}
nodeGen[ldx].left = &nodeGen[nextBucket[0]];
nodeGen[ldx].right = &nodeGen[nextBucket[1]];
if (ldx > pow(2, loops) - 1 && oddlot)
{
used[ldx] = ldx;
if (nextBucket[0] <= pow(2, loops) - 1 || used[nextBucket[0]] == nextBucket[0])
{
nodeGen[ldx].left = NULL;
}
if (nextBucket[1] <= ldx)
{
nodeGen[ldx].right = NULL;
}
}
}
else
{
nodeGen[ldx].left = NULL;
nodeGen[ldx].right = NULL;
}
if (printFlag)
{
printf("node = %p %d left: %p %d right: %p %d\n\n", &nodeGen[ldx], ldx, nodeGen[ldx].left, llx, nodeGen[ldx].right, lrx);
}
}
//comments
for (int m = 0; m < ((buckets > 15) ? 2 : 0); m++)
{
if (cnt < buckets)
{
mdx = pow(2, loops - 4) - 1 + mkick;
mkick = mkick + pow(2, loops - 3);
if (mdx > buckets - 1 - oob)
{
while (mdx > buckets - 1 - oob)
{
mdx = mdx - 1;
}
oob++;
}
nodeGen[mdx].index = mdx;
if (printFlag)
{
printf("index = %d mdx = %d word = %s cnt = %d \n", nodeGen[mdx].index, mdx, nodeGen[mdx].word, cnt) ;
}
cnt ++;
if (loops > 4)
{
nextBucket = nextBuckets(loops - 5, nkick, oob, buckets);
if (printFlag)
{
printf("NEXT %d %d\n", nextBucket[0], nextBucket[1]);
}
nodeGen[mdx].left = &nodeGen[nextBucket[0]];
nodeGen[mdx].right = &nodeGen[nextBucket[1]];
if (mdx > pow(2, loops) - 1 && oddlot)
{
used[mdx] = mdx;
if (nextBucket[0] <= pow(2, loops) - 1 || used[nextBucket[0]] == nextBucket[0])
{
nodeGen[mdx].left = NULL;
}
if (nextBucket[1] <= mdx)
{
nodeGen[mdx].right = NULL;
}
}
}
else
{
nodeGen[mdx].left = NULL;
nodeGen[mdx].right = NULL;
}
if (printFlag)
{
printf("node = %p %d left: %p %d right: %p %d oob: %d rob: %d\n\n", &nodeGen[mdx], mdx, nodeGen[mdx].left, mlx,
nodeGen[mdx].right, mrx, oob, rob);
}
}
//comments
for (int n = 0; n < ((buckets > 31) ? 2 : 0); n++)
{
if (cnt < buckets)
{
ndx = pow(2, loops - 5) - 1 + nkick;
nkick = nkick + pow(2, loops - 4);
if (ndx > buckets - 1 - oob)
{
while (ndx > buckets - 1 - oob)
{
ndx = ndx - 1;
}
oob++;
}
nodeGen[ndx].index = ndx;
if (printFlag)
{
printf("index = %d ndx = %d word = %s cnt = %d \n", nodeGen[ndx].index, ndx, nodeGen[ndx].word, cnt) ;
}
cnt ++;
if (loops > 5)
{
nextBucket = nextBuckets(loops - 6, okick, oob, buckets);
if (printFlag)
{
printf("NEXT %d %d\n", nextBucket[0], nextBucket[1]);
}
nodeGen[ndx].left = &nodeGen[nextBucket[0]];
nodeGen[ndx].right = &nodeGen[nextBucket[1]];
if (ndx > pow(2, loops) - 1 && oddlot)
{
used[ndx] = ndx;
if (nextBucket[0] <= pow(2, loops) - 1 || used[nextBucket[0]] == nextBucket[0])
{
nodeGen[ndx].left = NULL;
}
if (nextBucket[1] <= ndx)
{
nodeGen[ndx].right = NULL;
}
}
}
else
{
nodeGen[ndx].left = NULL;
nodeGen[ndx].right = NULL;
}
if (printFlag)
{
printf("node = %p %d left: %p %d right: %p %d\n\n", &nodeGen[ndx], ndx, nodeGen[ndx].left, nlx, nodeGen[ndx].right, nrx);
}
}
//comments
for (int o = 0; o < ((buckets > 63) ? 2 : 0); o++)
{
if (cnt < buckets)
{
odx = pow(2, loops - 6) - 1 + okick;
okick = okick + pow(2, loops - 5);
if (odx > buckets - 1 - oob)
{
while (odx > buckets - 1 - oob)
{
odx = odx - 1;
}
oob++;
}
nodeGen[odx].index = odx;
if (printFlag)
{
printf("index = %d odx = %d word = %s cnt = %d \n", nodeGen[odx].index, odx, nodeGen[odx].word, cnt) ;
}
cnt ++;
if (loops > 6)
{
nextBucket = nextBuckets(loops - 7, pkick, oob, buckets);
if (printFlag)
{
printf("NEXT %d %d\n", nextBucket[0], nextBucket[1]);
}
nodeGen[odx].left = &nodeGen[nextBucket[0]];
nodeGen[odx].right = &nodeGen[nextBucket[1]];
if (odx > pow(2, loops) - 1 && oddlot)
{
used[odx] = odx;
if (nextBucket[0] <= pow(2, loops) - 1 || used[nextBucket[0]] == nextBucket[0])
{
nodeGen[odx].left = NULL;
}
if (nextBucket[1] <= odx)
{
nodeGen[odx].right = NULL;
}
}
}
else
{
nodeGen[odx].left = NULL;
nodeGen[odx].right = NULL;
}
if (printFlag)
{
printf("node = %p %d left: %p %d right: %p %d\n\n", &nodeGen[odx], odx, nodeGen[odx].left, olx, nodeGen[odx].right, orx);
}
}
//comments
for (int p = 0; p < ((buckets > 127) ? 2 : 0); p++)
{
if (cnt < buckets)
{
pdx = pow(2, loops - 7) - 1 + pkick;
pkick = pkick + pow(2, loops - 6);
if (pdx > buckets - 1 - oob)
{
while (pdx > buckets - 1 - oob)
{
pdx = pdx - 1;
}
oob++;
}
nodeGen[pdx].index = pdx;
if (printFlag)
{
printf("index = %d pdx = %d word = %s cnt = %d \n", nodeGen[pdx].index, pdx, nodeGen[pdx].word, cnt) ;
}
cnt ++;
if (loops > 7)
{
nextBucket = nextBuckets(loops - 8, qkick, oob, buckets);
if (printFlag)
{
printf("NEXT %d %d\n", nextBucket[0], nextBucket[1]);
}
nodeGen[pdx].left = &nodeGen[nextBucket[0]];
nodeGen[pdx].right = &nodeGen[nextBucket[1]];
if (pdx > pow(2, loops) - 1 && oddlot)
{
used[pdx] = pdx;
if (nextBucket[0] <= pow(2, loops) - 1 || used[nextBucket[0]] == nextBucket[0])
{
nodeGen[pdx].left = NULL;
}
if (nextBucket[1] <= pdx)
{
nodeGen[pdx].right = NULL;
}
}
}
else
{
nodeGen[pdx].left = NULL;
nodeGen[pdx].right = NULL;
}
if (printFlag)
{
printf("node = %p %d left: %p %d right: %p %d\n\n", &nodeGen[pdx], pdx, nodeGen[pdx].left, plx, nodeGen[pdx].right, prx);
}
}
//comments
for (int q = 0; q < ((buckets > 255) ? 2 : 0); q++)
{
if (cnt < buckets)
{
qdx = pow(2, loops - 8) - 1 + qkick;
qkick = qkick + pow(2, loops - 7);
if (qdx > buckets - 1 - oob)
{
while (qdx > buckets - 1 - oob)
{
qdx = qdx - 1;
}
oob++;
}
nodeGen[qdx].index = qdx;
if (printFlag)
{
printf("index = %d qdx = %d word = %s cnt = %d \n", nodeGen[qdx].index, qdx, nodeGen[qdx].word, cnt) ;
}
cnt ++;
nodeGen[qdx].left = NULL;
nodeGen[qdx].right = NULL;
if (printFlag)
{
printf("node = %p %d left: %p %d right: %p %d\n\n", &nodeGen[qdx], qdx, nodeGen[qdx].left, qlx, nodeGen[qdx].right, qrx);
}
}
}
}
}
}
}
}
}
}
}
return (&nodeGen[idx]);
}
int *nextBuckets(int power, int kick, int oob, int buckets)
{
//comments
static int next[2];
for (int i = 0; i < 2; i++)
{
next[i] = pow(2, power) - 1 + kick;
kick = kick + pow(2, power + 1);
if (next[i] > buckets - 1 - oob)
{
while (next[i] > buckets - 1 - oob)
{
next[i] = next[i] - 1 ;
}
oob++;
}
}
return next;
}
</code></pre>
|
[] |
[
{
"body": "<h1>Don't read a file character by character</h1>\n<p>Reading a file a character at a time is slow. Even if standard input is buffered, then you still have the overhead of individual calls to <code>fgetc()</code>, which has to check each time if there is at least one character in the input buffer, and if so remove it from the buffer and return it, otherwise read some more data in the buffer.</p>\n<p>The fastest way to process the file is probably to <a href=\"https://man7.org/linux/man-pages/man2/mmap.2.html\" rel=\"nofollow noreferrer\"><code>mmap()</code></a> it, although that is not portable C. Instead, consider reading in entire lines with <a href=\"https://en.cppreference.com/w/c/io/fgets\" rel=\"nofollow noreferrer\"><code>fgets()</code></a>, or a few thousand bytes at a time using <a href=\"https://en.cppreference.com/w/c/io/fread\" rel=\"nofollow noreferrer\"><code>fread()</code></a>. Then just loop through the line/array of characters you just read.</p>\n<p>Note that if you read in whole lines, and you know there is no hyphenation, you always know you will have read whole words, so you don't need to copy characters into <code>word[]</code> anymore, you just need to keep track of the start and end of a word.</p>\n<h1>Don't include benchmarking code in the submission</h1>\n<p>Note that calls to <code>getrusage()</code> themselves might be expensive, so don't include that in your submissions. In fact, I would just not call <code>getrusage()</code> at all, but use an external tool like <a href=\"https://man7.org/linux/man-pages/man1/time.1.html\" rel=\"nofollow noreferrer\"><code>time</code></a> or Linux's <a href=\"https://en.wikipedia.org/wiki/Perf_(Linux)\" rel=\"nofollow noreferrer\"><code>perf</code></a> to measure the time or CPU cycles used by your program.</p>\n<h1>Avoid allocating memory if possible</h1>\n<p>When building the dictionary, you first allocate memory to read in the file, then allocate memory for an array of words, then memory for the hash buckets, then for each bucket you allocate some memory for the word stored in it. So basically, you have three copies of each word in memory. And that's before building the trie, which has a lot of allocations per word.</p>\n<p>This is a huge waste of memory, and duplicating all the data is not free either. If the dictionary is larger than the input text, it is also a huge waste of effort. So, remove redundant copies and allocations as much as possible.</p>\n<p>I also see that you call <code>malloc()</code> inside <code>hash()</code>, just for a small temporary buffer. In this case, just use a simple array:</p>\n<pre><code>char lcWord[LENGTH + 1];\n</code></pre>\n<h1>Faster ways to load the dictionary</h1>\n<p>The problem specification mentions that the dictionary lists all words already lexicographically sorted. Unless the text to spell check has much more words than the dictionary, I would not even bother hashing it or creating a tree from it, instead I would just <code>mmap()</code> it, and use a binary search to find words from the input in the dictionary. But let's assume we need to use only standard C functions, and that you do want to build a trie.</p>\n<p>First, load the dictionary as you already do in memory. Note that you now have all the words in the dictionary in memory, so you don't need to copy them anymore, instead you can just create pointers into that buffer. You can replace all newlines with NUL bytes, so that all words are valid C strings.</p>\n<p>When building the trie, you can use the fact that the dictionary is sorted.</p>\n<h1>Hash? Trie? Both?</h1>\n<p>I struggle to understand how you index the dictionary. The <code>hash()</code> function doesn't look like a <a href=\"https://en.wikipedia.org/wiki/Hash_function\" rel=\"nofollow noreferrer\">hash function</a> at all, instead it does a binary search. The point of a hash function is to avoid any kind of tree traversal. And after your <code>hash()</code> returns, then you are doing another binary search inside <code>check()</code>. I think this will get you the worst of both worlds.</p>\n<p>The problem statement clearly says that you should implement a spell checker "using a hash table". So I would avoid using a trie at all, and just focus on writing a good hash table implementation. If you really want to use a trie, then forget about <code>hash()</code>, and just encode the dictionary as a single trie.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T22:34:53.567",
"Id": "250133",
"ParentId": "250120",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T17:02:02.917",
"Id": "250120",
"Score": "1",
"Tags": [
"performance",
"c"
],
"Title": "Spellchecking Challenge - Implementing a dictionary lookup"
}
|
250120
|
<p>Can this code be shortened or optimized,
Written out this script to be used before node.js
starts a few canvas elements and some vide streams.
wondering if the initial checks can be shortend or optimized.
is there any issues that I have not spotted or that could be reworked to
be shorter. the code block that is inbetween the two <code>performance.now()</code>
checks takes between 5ms to 12ms to run, based one a few browser refreshes.
which is not loads, but when I've got all the other animations and assets loaded in that may add up,
Just wondering what other programmers thoughts are.</p>
<p>my Js code</p>
<pre><code> "use-strict";
window.addEventListener('DOMContentLoaded', () => {
/* --------------------- Main Code Wrapper ----------------------- event*/
console.log('DOM fully loaded and parsed');
// console.log(performance.now);
const PerfNow01 = performance.now(); // Usefull benchmarking tool.
function CompatabilityChecks(){
if(window.Worker){
console.log("WebWorkers are enabled")
const CanvWorker = new Worker('Scripts/CanvasThread.js');
const AnimeWorker = new Worker('Scripts/AnimeThread.js');
const ReactWorker = new Worker('Scripts/ReactionThread.js');
const DBWorker = new Worker('Scripts/DBThread.js');
}
if(window.Worklet){
console.log("Worklets are enabled")
}
if(window.requestAnimationFrame){
console.log("requestAnimationFrame Functions are Supported")
}else{ // fetch('polyFill');
}
if(window.Element.prototype.animate !== undefined){
console.log(`Element.animate() functions are Supported`)
}else{ // fetch('polyFill');
}
var WebSocketObject = window.WebSocket || window.MozWebSocket;
if(WebSocketObject){
console.log(`WebSockets Supported.`)
}
}
CompatabilityChecks();
function GetUserAgentMetaData(){
// let UAx = navigator.userAgent;
let UAxMeta = {
Platform: navigator.platform,
BrowserVersion: navigator.appVersion,
CookiesEnabled: navigator.cookieEnabled,
BrowserCodeName: navigator.appCodeName,
UserAgentHeader: navigator.userAgent,
BrowserLanguage: navigator.language,
BrowserOnline: navigator.onLine,
BrowserName: navigator.appName
};
console.log(UAxMeta);
}GetUserAgentMetaData();
const PerfNow02 = performance.now(); // Usefull benchmarking tool.
function isiOS(){return isiPod()||isiPhone()||isiPad()}
function isiPod(){return/iPod/i.test(navigator.userAgent)&&window["MSStream"]===undefined}
function isiPhone(){return/iPhone/i.test(navigator.userAgent)&&window["MSStream"]===undefined}
function isMobileDevice(){
return/Android|webOS|BlackBerry|IEMobile|Opera Mini|SamsungBrowser/i.test(navigator.userAgent)||isiOS()
};
function isiPad(){return((/iPad/i.test(navigator.userAgent)||(navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1))&&window["MSStream"]===undefined)}
function isMobileDevice(){return/Android|webOS|BlackBerry|IEMobile|Opera Mini|SamsungBrowser/i.test(navigator.userAgent)||isiOS()};
console.log(`Performance::>> ${PerfNow01 - PerfNow02} milliseconds.`);
// Delay all Animation Starts.........................................
// let LazyLoadCount = {} && [];
// ::>> Main Usr Video Section................................................
let video = document.getElementsByClassName("MainUsrOffScreenVid")[0];
)};
</code></pre>
<p>is working code with no errors so far...
<a href="https://i.stack.imgur.com/i8VWl.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/i8VWl.jpg" alt="enter image description here" /></a></p>
<p>if anyone can suggest two more tags that i can add onto the question, would be helpful.</p>
<p>Just Noticed myself that I have two duplicate functions of <code>function isMobileDevice()</code> So will remove this but leave it in the original question.
Thanks in advanced...</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T18:54:08.293",
"Id": "490656",
"Score": "0",
"body": "Just an aside, you don't always need to use all five tag slots. You only need to use tags that help identify what your question is about / asking about."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T18:31:00.363",
"Id": "250123",
"Score": "2",
"Tags": [
"javascript",
"performance",
"design-patterns"
],
"Title": "Pre setup script to get user metadata and check supported api's within the browser/device"
}
|
250123
|
<p><strong>What are anagrams?</strong></p>
<p>An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, “abcd” and “dabc” are an anagram of each other</p>
<pre><code>def anagram_check(string1,string2):
list1 = [char1.lower() for char1 in string1 if char1 != " "]
list2 = [char2.lower() for char2 in string2 if char2 != " "]
if len(list1) != len(list2):
return False
else:
list1.sort()
list2.sort()
return list1 == list2
print(anagram_check('clint eastwood','old west action'))
</code></pre>
<p><strong>Question</strong></p>
<p>I have started to learn data structures and algorithms, and my question is: Am I using too many Python tricks to solve this problem or do I need to think of a more basic approach to solve this?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T20:34:03.543",
"Id": "490670",
"Score": "0",
"body": "You can look at my `Counter` based solution which is pythonic and one liner. https://www.github.com/strikersps/Competitive-Programming/tree/master/Other-Programs%2FAnagram-Detection%2Fanagram_detection_another_solution.py"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T20:50:39.313",
"Id": "490674",
"Score": "1",
"body": "@strikersps doesn't really work for OP's case https://tio.run/##XY4xCsMwDEV3nUJ4siFL062QqScxttIaHMvICqGnd0xLlv7p8XnDqx99c7n3DqvwhoFzpqCJS8O0VRbFJ@9FSQAirehtU0nldZvwB7N7AI4J6S7lki/L4bL8fbMDqAPUemtCHoDkmx7M0UxoOEc8qCn6b4VxrvcT"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T01:22:29.343",
"Id": "490687",
"Score": "2",
"body": "*\"am I using too much of python tricks\"* - What does that even mean? Too much for what?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T17:49:39.980",
"Id": "490733",
"Score": "0",
"body": "@hjpotter92 Agreed; it needs to be `Counter(string1.replace(\" \", \"\").lower()) == Counter(string2.replace(\" \", \"\").lower())` (although that's begging to be made DRY)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-05T19:12:06.367",
"Id": "490944",
"Score": "0",
"body": "@hjpotter92 Sorry! my bad I didn't take care of spaces in between the strings. Updated the code-base. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-06T06:17:16.820",
"Id": "491002",
"Score": "0",
"body": "Guys, I forgot the email address I used for this account from which I have posted this question. How do recover this account? LOL the question went HOT"
}
] |
[
{
"body": "<p>Welcome to Code Review.</p>\n<p>Since you're looking for Python tricks here, there are great many things which can both make it Pythonic, maintainable, shorter, etc. Depending on your understanding, as well the target audience for the code in near future, you may choose individual methods. A few pointers to get you started:</p>\n<ol>\n<li><p>You can use a <code>filter</code> to remove all whitespace characters:</p>\n<pre><code>filter(lambda char: char != ' ', string.lower())\n</code></pre>\n</li>\n<li><p>You can use <code>replace</code> to replace all whitespaces:</p>\n<pre><code>string.lower().replace(' ', '')\n</code></pre>\n</li>\n<li><p>You can use <code>collections.Counter</code> to verify that count of each character in both strings is equal, although list equality works as well.</p>\n</li>\n<li><p>You can validate (or simply return) equality of a <code>sorted</code> call on the filtered strings.</p>\n</li>\n</ol>\n<hr />\n<pre><code>def anagram_check(string1, string2):\n return sorted(string1.lower().replace(' ', '')) == sorted(string2.lower().replace(' ', ''))\n</code></pre>\n<p>The one-liner above is perfectly Pythonic, imo.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T20:21:58.617",
"Id": "490667",
"Score": "0",
"body": "Isn't this pretty WET? `reduce` is superseded by what you replaced it from, also it is generally tainted in most Python circles. I would not recommend it in Python 3."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T20:29:08.943",
"Id": "490668",
"Score": "0",
"body": "@Peilonrayz I didn't get you. What does \"reduce is superseded ...... circles\" mean?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T20:32:30.570",
"Id": "490669",
"Score": "0",
"body": "Ah sorry that's meant to be `filter` not `reduce`. If that's not cleared it up enough; the new Pythonic form of `filter` is generator expressions and list comprehensions (depending on Python version). Additionally [`filter` is depreciated](https://google.github.io/styleguide/pyguide.html#215-deprecated-language-features) in the Google style guide."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T20:34:38.607",
"Id": "490671",
"Score": "0",
"body": "@Peilonrayz oh ok! I know that filter/map now give a generator and not a list. Hence I stated them as \"a few pointers\" to let the OP do some research of their own."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T01:33:54.513",
"Id": "490690",
"Score": "2",
"body": "@hjpotter92 Hmm, why do you say \"you're looking for python tricks\"? They're asking \"am I using *too much* of python tricks\". (And the title has in the meantime been clarified, changed to \"*Avoiding* python tricks\".)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T01:35:42.627",
"Id": "490691",
"Score": "0",
"body": "@Peilonrayz Where does that Google style guide say `filter` is deprecated? I only see it say that `filter` *with lambda* is. And it says that about `map` as well and explicitly lists `map(math.sqrt, ...` as a \"Yes\"/\"Ok\" example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T04:03:22.913",
"Id": "490696",
"Score": "0",
"body": "Something implicit in your answer and perhaps should be made explicit is that `lower` works on entire strings, not just individual characters."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T05:08:46.677",
"Id": "490697",
"Score": "0",
"body": "@HeapOverflow the OP updated their question within few seconds after i had posted this answer. earlier question was just the opposite :/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T15:31:18.887",
"Id": "490724",
"Score": "0",
"body": "Looking at the history, I see that the \"am I using too much of python tricks\" was there since the beginning, an hour before your answer. Only the title changed in the meantime, and like I said I think it's a clarification (I'd say \"Using\" doesn't imply that they *want* to use tricks if the question already asks about \"using too much\")."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T20:15:18.003",
"Id": "250126",
"ParentId": "250124",
"Score": "8"
}
},
{
"body": "<p>To answer your specific question, I only see a few "tricks" being used in your code:</p>\n<ol>\n<li>Converting to lower case.</li>\n<li>Eliminating spaces.</li>\n<li>Comparing the lengths as a shortcut</li>\n<li>Sorting the lists to quickly compare them.</li>\n</ol>\n<p>None of these are particularly "Python-centric". The only caveat would be that Python strings are <span class=\"math-container\">\\$O(1)\\$</span> to compute the length, while for example C strings are <span class=\"math-container\">\\$O(n)\\$</span> to compute the length.</p>\n<p>(Note: while Python's standard <code>sort()</code> is faster than C's standard <code>qsort()</code>, this is a library thing and not your responsibility.)</p>\n<p>One "obvious" thing would be to use <code>collections.Counter</code> to generate an equivalence class that would determine whether two strings were anagrams. That definitely <em>would</em> be Python-centric, since most other languages don't have a direct equivalent. (Although it's trivial to write in a language that already has dict/hash/assoc-array support.)</p>\n<p>That said, let's look at your code from a Python standpoint.</p>\n<h2>Does it pep8?</h2>\n<p>I see a couple of problems with your function from a <a href=\"https://pep8.org\" rel=\"noreferrer\">PEP-8</a> standpoint.</p>\n<ol>\n<li><p>Your function has no <a href=\"https://pep8.org/#documentation-strings\" rel=\"noreferrer\">docstring.</a></p>\n</li>\n<li><p>Use spaces after commas.</p>\n</li>\n</ol>\n<h2>Is it quick-like?</h2>\n<p>You have done a fair job of optimizing the code without becoming "too Pythonic." I would suggest some of the following, however:</p>\n<ol>\n<li><p>Only call <code>.lower()</code> once. You call <code>char1.lower() for char1 in string1</code> but you could instead use <code>char1 for char1 in string1.lower()</code> which would call <code>.lower()</code> once per string, rather than once per character. This will become significant when someone passes you a 60,000 character string. ;-)</p>\n</li>\n<li><p>Trust the snake! Instead of checking the length, trust Python to do that! You can simplify your code even further with that.</p>\n</li>\n</ol>\n<h2>Fix that name!</h2>\n<p>Unless you have some kind of requirement that you must use the name, change that name! The name <code>anagram_check</code> sounds like a procedure (do something) not like a function (return something). But you're returning a boolean value. So make it a boolean-sounding name:</p>\n<pre><code>is_anagram_of\nare_anagrams\nhas_anagram\ncompare_equal_when_sorted_with_spaces_removed\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T01:50:08.167",
"Id": "490693",
"Score": "8",
"body": "Seems counterproductive that your \"Is it quick-like?\" part suggests to remove the O(1) length check that can likely avoid unnessecary O(n log n) sorting."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T20:29:19.157",
"Id": "250127",
"ParentId": "250124",
"Score": "8"
}
},
{
"body": "<p>Taking advantage of the work previously submitted by @hjpotter92 and adding an extra twist:</p>\n<pre><code>def anagram_check(*args ):\n return len( { tuple(sorted(x.lower().replace(' ', ''))) for x in args } ) == 1\n</code></pre>\n<p>This, potentially, gains an additional pythonicity score by avoiding repetition of the <code>sorted(x.lower().replace( ...)</code> construct. Instead, the construct is applied to both arguments in the set comprehension, and the test to see if the resulting set has a single element provides the answer. This implementation also generalizes the API to cover more that two strings if wanted, returning <code>True</code> if all strings given are anagrams of each other (thanks to Heap Overflow for pointing this out).</p>\n<p>If you really want a function which is limited to two strings, you might prefer:</p>\n<pre><code>def anagram_check(string1, string2):\n return len({tuple(sorted(x.lower().replace(' ', ''))) for x in [string1,string2]}) == 1\n</code></pre>\n<p>The code can be made less terse and more legible by defining a function to act on each string:</p>\n<pre><code>def make_unique(x): \n return tuple( sorted( x.lower().replace(' ', '') ) )\n\ndef anagram_check(*args): \n return len( { make_unique(x) for x in args } ) == 1\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T01:42:49.303",
"Id": "490692",
"Score": "2",
"body": "It's not a b̶u̶g̶ weakness, it's a feature! With `*args`, you check whether any (positive) number of strings are all anagrams of each other."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T07:46:25.290",
"Id": "490702",
"Score": "0",
"body": "Thanks, I'll edit the answer to reflect your comment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T19:20:22.463",
"Id": "490742",
"Score": "0",
"body": "This seems unnecessarily terse. My eyes have to fly to the middle of the one-liner to get a grasp of what's happening, then work my way out and trust I don't lose track of parenthesis. I think OP would be better served by taking the spirit of this function and breaking out parts of it, such as `cleaned_string = string.lower().replace(' ','')` and so on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T19:26:31.713",
"Id": "490744",
"Score": "1",
"body": "`: 'Two or more strings'` and `-> 'True if all strings are anagrams'` - you used type annotations as comments. It doesn't fail at runtime but static code analysers will complain about it and it confuses readers of the code. Please consider editing your answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T20:23:07.460",
"Id": "490747",
"Score": "4",
"body": "using type annotations as comments is not their intended purpose at all. and the code leans too much towards brevity than readability."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-04T18:01:36.680",
"Id": "490806",
"Score": "0",
"body": "I've taken the misused type annotations out .. thanks for the correction."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-04T19:11:15.263",
"Id": "490810",
"Score": "0",
"body": "@wizzwizz4: I'm sorry, but I don't understand your suggestions. Converting the list to a set will omit duplicated characters, which we don't want, and I don't know where `ignored=..` can be used."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-04T19:25:28.943",
"Id": "490812",
"Score": "0",
"body": "@user1717828 : Fair point. I've added an expanded version with a `make_unique` function defined in advance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-05T05:55:45.453",
"Id": "490848",
"Score": "0",
"body": "@MJuckes Ah, good point."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T22:47:55.757",
"Id": "250134",
"ParentId": "250124",
"Score": "10"
}
},
{
"body": "<p>I'll focus on performance. Let's first benchmark removing spaces and lower-casing:</p>\n<pre><code>string1 = 'clint eastwood'; string2 = 'old west action'\n\n6.45 μs list1 = [char1.lower() for char1 in string1 if char1 != " "]; list2 = [char2.lower() for char2 in string2 if char2 != " "]\n0.42 μs string1.replace(' ', ''); string2.replace(' ', '')\n0.25 μs string1.lower(); string2.lower()\n0.63 μs string1.replace(' ', '').lower(); string2.replace(' ', '').lower()\n0.71 μs string1.lower().replace(' ', ''); string2.lower().replace(' ', '')\n</code></pre>\n<p>Your preprocessing is <em>a lot</em> slower than using string methods. And unsurprisingly, it's faster to remove spaces <em>before</em> lower-casing. Both @M_Juckes and @hjpotter92 did it the other way around.</p>\n<p>Now let's check length, sorting and counting of the preprocessed strings:</p>\n<pre><code>string1 = 'clinteastwood'; string2 = 'oldwestaction'\n\n0.16 μs len(string1); len(string2)\n1.65 μs sorted(string1); sorted(string2)\n6.59 μs Counter(string1); Counter(string2)\n</code></pre>\n<p>Getting the length is far cheaper than sorting and counting, which are also a lot slower than the space-removal and lower-casing and thus make up most of the time. So for performance it's a good idea to do your length check and not sort/count at all if the lengths already differ. Also, counting is far more expensive than sorting. Probably not for a lot longer strings, but I find it unrealistic to check whether two very long strings are anagrams.</p>\n<p>Let's turn what we learned into an optimized solution:</p>\n<pre><code>def anagram_check(string1, string2):\n s = string1.replace(' ', '')\n t = string2.replace(' ', '')\n if len(s) != len(t):\n return False\n return sorted(s.lower()) == sorted(t.lower())\n</code></pre>\n<p>First I <em>only</em> remove the spaces, so that the length check can avoid unnecessary lowering as well. Then lower-case and use sorting. I kept the longer parameter names for clarity but internally switched to more convenient short variable names.</p>\n<p>Benchmarks on full solutions, first with your original string pair:</p>\n<pre><code>('clint eastwood', 'old west action')\n\n7.97 μs original\n2.69 μs heap_overflow\n3.71 μs M_Juckes\n2.45 μs hjpotter92\n</code></pre>\n<p>Mine is a bit slower than hjpotter92's, as the length check does take a little time. Next let's modify the second string a bit so they're not anagrams:</p>\n<pre><code>('clint eastwood', 'new west action')\n\n7.74 μs original\n2.62 μs heap_overflow\n3.63 μs M_Juckes\n2.50 μs hjpotter92\n</code></pre>\n<p>Pretty much the same. Now let's make the second string a bit <em>longer</em>:</p>\n<pre><code>('clint eastwood', 'older west action')\n\n6.94 μs original\n0.77 μs heap_overflow\n4.00 μs M_Juckes\n2.64 μs hjpotter92\n</code></pre>\n<p>Now the length check pays off. In my solution more than in yours, as I avoid not only the sorting but also the lower-casing. It's by far the fastest now, as expected from the earlier timings of the individual steps.</p>\n<p>I don't know what data you're using this on, but if the length check fails let's say 50% of the time, then it's clearly worth doing, and my solution is fastest on average. I'd also say it's better style than those long one-liners.</p>\n<p>Full benchmark code:</p>\n<pre><code>from collections import Counter\nfrom functools import partial\nfrom timeit import repeat\n\ntests = [\n ('clint eastwood','old west action'),\n ('clint eastwood','new west action'),\n ('clint eastwood','older west action'),\n ]\n\n#----------------------------------------------------------------------------\n\nnormers = [\n 'list1 = [char1.lower() for char1 in string1 if char1 != " "]; list2 = [char2.lower() for char2 in string2 if char2 != " "]',\n "string1.replace(' ', ''); string2.replace(' ', '')",\n "string1.lower(); string2.lower()",\n "string1.replace(' ', '').lower(); string2.replace(' ', '').lower()",\n "string1.lower().replace(' ', ''); string2.lower().replace(' ', '')",\n ]\n\nfor test in tests[:1]:\n setup = f'string1 = {test[0]!r}; string2 = {test[1]!r}'\n print(setup)\n tss = [[] for _ in normers]\n for _ in range(3):\n for normer, ts in zip(normers, tss):\n t = min(repeat(normer, setup, number=10**5)) * 10\n ts.append(t)\n for normer, ts in zip(normers, tss):\n print('%.2f μs ' % min(ts), normer)\n print()\n\n#----------------------------------------------------------------------------\n\nnormers = [\n "len(string1); len(string2)",\n "sorted(string1); sorted(string2)",\n "Counter(string1); Counter(string2)",\n ]\n\nfor test in tests[:1]:\n string1 = test[0].replace(' ', '').lower()\n string2 = test[1].replace(' ', '').lower()\n setup = f'string1 = {string1!r}; string2 = {string2!r}'\n print(setup)\n setup += '; from collections import Counter'\n tss = [[] for _ in normers]\n for _ in range(3):\n for normer, ts in zip(normers, tss):\n t = min(repeat(normer, setup, number=10**5)) * 10\n ts.append(t)\n for normer, ts in zip(normers, tss):\n print('%.2f μs ' % min(ts), normer)\n print()\n\n#----------------------------------------------------------------------------\n\ndef original(string1,string2):\n list1 = [char1.lower() for char1 in string1 if char1 != " "]\n list2 = [char2.lower() for char2 in string2 if char2 != " "]\n if len(list1) != len(list2):\n return False\n else:\n list1.sort()\n list2.sort()\n return list1 == list2\n \ndef heap_overflow(string1, string2):\n s = string1.replace(' ', '')\n t = string2.replace(' ', '')\n if len(s) != len(t):\n return False\n return sorted(s.lower()) == sorted(t.lower())\n\ndef M_Juckes(*args : 'Two or more strings') -> 'True if all strings are anagrams':\n return len( { tuple(sorted(x.lower().replace(' ', ''))) for x in args } ) == 1\n\ndef hjpotter92(string1, string2):\n return sorted(string1.lower().replace(' ', '')) == sorted(string2.lower().replace(' ', ''))\n\nfuncs = original, heap_overflow, M_Juckes, hjpotter92\n\nfor test in tests:\n print(test)\n print()\n tss = [[] for _ in funcs]\n for _ in range(3):\n for func, ts in zip(funcs, tss):\n t = min(repeat(partial(func, *test), number=10**5)) * 10\n ts.append(t)\n for func, ts in zip(funcs, tss):\n print('%.2f μs ' % min(ts), func.__name__)\n print()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T19:08:03.923",
"Id": "250159",
"ParentId": "250124",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "250127",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T19:15:26.553",
"Id": "250124",
"Score": "8",
"Tags": [
"python",
"python-3.x"
],
"Title": "Avoiding Python tricks to find anagrams"
}
|
250124
|
<p>The main reasoning behind this PDO wrapper, is that I find myself using unique constraints quite frequently in my designs, and I have <code>if ($ex->errorInfo[1] == 1062)</code> littered throughout my code, and I thought there has to be a better way.</p>
<pre><code><?php
class PDOMysql extends \PDO {
public function __construct($dsn, $username = null, $passwd = null, $options = null)
{
parent::__construct($dsn, $username, $passwd, $options);
$this->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$this->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_OBJ);
}
public function prepareAndExecute($statement, array $params = []): \PDOStatement
{
try {
$stmt = $this->prepare($statement);
$stmt->execute($params);
return $stmt;
} catch (\PDOException $ex) {
if ($ex->errorInfo[1] == 1062) {
throw new PDOMysqlUniqueConstraintException($ex);
} else {
throw $ex;
}
}
}
}
class PDOMysqlUniqueConstraintException extends \PDOException {
public function __construct(\PDOException $ex)
{
parent::__construct($ex->getMessage(), $ex->getCode(), $ex->getPrevious());
}
}
// example usage
$user = 'vps';
$pass = 'vps';
$db = new PDOMysql("mysql:host=localhost;dbname=testdb", $user, $pass);
// create table
$sql = "create table if not exists `mytable` (col1 varchar(100) null, constraint idx_u unique (col1) )";
$db->prepareAndExecute($sql);
// insert first row
$params = ['col1' => uniqid('')];
$sql = "insert into mytable (col1) values (:col1)";
$db->prepareAndExecute($sql, $params);
// select row
$sql = "select * from mytable where col1 = :col1";
$stmt = $db->prepareAndExecute($sql, $params);
var_dump($stmt->fetchAll());
// insert duplicate row
try {
$sql = "insert into mytable (col1) values (:col1)";
$db->prepareAndExecute($sql, $params);
} catch (\PDOMysqlUniqueConstraintException $ex) {
die('Unique Constraint Detected');
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T22:22:39.990",
"Id": "490685",
"Score": "1",
"body": "Do you run into this situation often ? Isn't is better to fix existing code to avoid the exception, rather than having to handle it ? Last but not least, is your exception class doing anything special that a generic, application-wide exception handler could not do ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-04T09:08:32.917",
"Id": "490780",
"Score": "0",
"body": "approx 15 uses in total across 5 projects. I was under the impression using the db constraint was the correct approach. Take for example users signing up, with a unique email address. I could go and select the user first to see if the email exists, but that would result in a race condition (however unlikely). I would like to be able to detect and handle that particular exception differently, which is why it isn't just a generic exception."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-04T13:15:38.137",
"Id": "490788",
"Score": "0",
"body": "Database locks are meant to avoid race conditions. In Mysql you may want to use [SELECT FOR UPDATE](https://dev.mysql.com/doc/refman/8.0/en/innodb-locking-reads.html) for example, at least if your tables are InnoDB."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-04T18:45:19.303",
"Id": "490809",
"Score": "0",
"body": "I don't quite understand how SELECT FOR UPDATE would help in the case of inserting a user with a duplicate email address? If the email address doesn't exist in the db, there will be no row to select?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-06T14:37:36.577",
"Id": "491039",
"Score": "1",
"body": "\"For index records the search encounters, locks the rows and any associated index entries\" So if there is a unique index, it gets locked and modification of the row or the index (range) is not possible until the transaction ends. And this applies even if there is no such row, the index entry is virtual, yet part of the locked index range."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-07T22:42:57.563",
"Id": "491182",
"Score": "0",
"body": "@slepic I didn't know that, I will try it out, thanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T17:29:37.667",
"Id": "503499",
"Score": "0",
"body": "@Anonymous database locks are evil and you should avoid them when possible. The op has the correct approach to the problem and introduction table locks will make it much worse. Not to mention that there is no UPDATE query can be seen"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-29T06:35:38.710",
"Id": "510301",
"Score": "0",
"body": "What about a husband and wife who share a computer and an email account but want to login separately?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-29T06:36:25.747",
"Id": "510302",
"Score": "0",
"body": "Use transactions to deal with race conditions."
}
] |
[
{
"body": "<p>In <a href=\"https://www.youtube.com/watch?v=GtB5DAfOWMQ\" rel=\"nofollow noreferrer\">this presentation about cleaning up code</a> Rafael Dohms talks about many ways to keep code lean - like avoiding the <code>else</code> keyword. (<a href=\"https://www.slideshare.net/rdohms/bettercode-phpbenelux212alternate/11-OC_1Only_one_indentation_level\" rel=\"nofollow noreferrer\">see the slides here</a>).</p>\n<p>It is wise to avoid the <code>else</code> keyword - especially when it isn't needed - e.g. when a previous block contains a <code>throw</code> statement - like in the <code>catch</code> section of the the method <code>PDOMysql::prepareAndExecute()</code>, there are two <code>throw</code> statements:</p>\n<blockquote>\n<pre><code>if ($ex->errorInfo[1] == 1062) {\n throw new PDOMysqlUniqueConstraintException($ex);\n} else {\n throw $ex;\n}\n</code></pre>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T17:14:38.673",
"Id": "255224",
"ParentId": "250125",
"Score": "3"
}
},
{
"body": "<p>This code is so good that it's the first time I have nothing to say.</p>\n<p>Your approach to the problem is absolutely correct and you should keep using it.</p>\n<p>There could be only microscopic nuances, such as one mentioned by Sam. Or, the fact that your constructor would override the configuration settings passed in the $options array. Say, if someone would want to use FETCH_ASSOC as a default fetch mode, your class won't let them. I would rather make it this way</p>\n<pre><code>$defaults = [\n PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,\n PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,\n PDO::ATTR_EMULATE_PREPARES => false, // I would throw in this one too\n];\n$options = array_merge($defaults,$options); \nparent::__construct($dsn, $username, $passwd, $options);\n</code></pre>\n<p>So this way you would have your preferred defaults that, however, could be overwritten, making your class flexible, without artificial restrictions.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T17:44:37.323",
"Id": "255227",
"ParentId": "250125",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "255227",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T20:00:47.090",
"Id": "250125",
"Score": "5",
"Tags": [
"php",
"mysql",
"error-handling",
"pdo"
],
"Title": "Mysql PDO Wrapper that throws Unique Constraint Exception"
}
|
250125
|
<p>I enjoyed the many headaches this project gave me as I learned a lot! I have been studying Java for less than a year and am new to programming in general. I read over the comments rules and hope I followed them correctly. I don't know many people that code and would love any feedback. This was a school project I worked very hard on, but I know I have a long way to go. Please, let me know if you can help me get better...</p>
<pre><code>import java.util.Scanner;
import java.util.Random;
public class RPS {
public static void main(String[] args) {
Boolean playAgain = true;
Scanner input = new Scanner(System.in);
String play;
while (playAgain = true) {
WelcomeP1(); // Welcome & basic rule example
// Final Result & Replay Option
System.out.print("*********************" );
System.out.print("-------------> You " +Game()+ "!!!" );
System.out.println("\n*********************" );
System.out.println("Play Again?!");
System.out.println("Please press y for (Y)es or n for (N)o: ");
play = input.nextLine().trim();
while (play.isEmpty()){
System.out.println("Do you want to play Rock, Paper, Scissors?");
System.out.println("Please press y for (Y)es \nor n for (N)o: ");
play = input
.nextLine().trim();
} // end while ~ validate/catch error ~ for empty space
switch ( play.charAt(0) ){
case 'n' : case 'N':
playAgain = false;
System.exit(0);
case 'y': case 'Y':
System.out.println("\n*********************" );
System.out.print("Excellent;\nGlad you enjoyed playing!");
System.out.println("\nJust checking again...");
} // end while
} // end switch
} // end main
// Welcome Validation Start
public static void WelcomeP1(){
Scanner stdIn= new Scanner(System.in);
Boolean validGame = false;
String userPlay;
while( validGame == false ){
System.out.println("Do you want to play Rock, Paper, Scissors?");
System.out.println("Please press y for (Y)es \nor n for (N)o: ");
userPlay = stdIn.nextLine().trim();
while (userPlay.isEmpty()){
System.out.println("Do you want to play Rock, Paper, Scissors?");
System.out.println("Please press y for (Y)es \nor n for (N)o: ");
userPlay = stdIn.nextLine().trim();
} // end while ~ validate/catch error ~ for empty space
// below valiates user entry
switch ( userPlay.charAt(0) ){
case 'n' : case 'N':
System.exit(0);
case 'y': case 'Y':
validGame = true;
System.out.println("*************************************");
System.out.println("Excellent! Thank you...\nLet's Play!");
break;
default:
} // end switch
} // end while loop
} // end class Welcome ~ End Welcome Validation
// User Input Validation Start
public static int P1Choice(){
Scanner userIn = new Scanner(System.in);
Boolean validUserIn = false;
String userInput;
int userPiece = 0;
while (validUserIn == false){
System.out.println("*************************************");
System.out.println("Choose (R)ock, (P)aper, or (S)cissors ");
System.out.println("Please type the first letter only.");
System.out.println("Your Choice: ");
userInput = userIn.nextLine();
while (userInput.isEmpty()){
System.out.println("Choose (R)ock, (P)aper, or (S)cissors ");
System.out.println("Please type the first letter only.");
System.out.println("Your Choice: ");
userInput = userIn.nextLine();
} // end while ~ validate/catch error ~ for empty space
// below valiates user entry further
userPiece = userInput.charAt(0);
if (userInput.equalsIgnoreCase("r")){
userPiece = 0;
System.out.println("You Chose: Rock");
validUserIn = true;
}
else if (userInput.equalsIgnoreCase("p")){
userPiece = 1;
System.out.println("You Chose: Paper");
validUserIn = true;
}
else if (userInput.equalsIgnoreCase("s")) {
userPiece = 2;
System.out.println("You Chose: Scissors");
validUserIn = true;
}
else {
System.out.println("Invalid Choice.");
validUserIn = false;
}
} // end while loop
return userPiece;
} // end class UserPiece ~ End User Input Validation & Return
// Computer Choice Calculation & Print ~ Start
public static int ComputerChoice(){
Random random = new Random();
int choiceStart;
choiceStart = random.nextInt(3); // max number 3 ~ 0-2
int computerInput = 0;
String computerPiece = null;
switch (choiceStart) {
case 0:
computerInput = 0;
computerPiece = "Rock";
break;
case 1:
computerInput = 1; //Paper
computerPiece = "Paper";
break;
case 2:
computerInput = 2; //Scissors
computerPiece = "Scissors";
break;
} // end switch
System.out.println("*************************************");
System.out.println("*************************************");
System.out.println("The computer has decided as well...");
System.out.println("|||||||||||||||||||||||||||||||||||||");
System.out.println("|||||||||||||||||||||||||||||||||||||");
System.out.println("The computer's choice was " +computerPiece+ "...");
System.out.println("*************************************");
System.out.println("*************************************");
return computerInput;
} // end class ComputerChoice ~ End Computer Choice Calculation & Print
// Calculate Game & Return Win/Loss/Tie ~ Calculations
public static String Game(){
int user = P1Choice();
int computer = ComputerChoice();
String error = "*** If you are reading this, there has been a"
+" system error. Please restart the program. ***";
// 0 = rock
// 1 = paper
// 2 = scissors
if (user == 0) {
if (computer != 1){
if (computer != 0){
return "Win";
}
return "Tie";
}
return "Lose";
} // end first nested for loop logic
if (user == 1){
if (computer != 2){
if (computer != 1) {
return "Win";
}
return "Tie";
}
return "Lose";
} // end second nested for loop logic
if (user == 2){
if (computer != 0){
if (computer != 2) {
return "Win";
}
return "Tie";
}
return "Lose";
} // end third nested for loop logic
return error; // null -- Needed to return something
// -- better practice teacher?
} // end class Game ~ End Calculate Game & Return
} // end class RPS
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<h2>Code formatting</h2>\n<p>You have some formatting and indentation problems. Please run your code through a formatter, for example this one</p>\n<p><a href=\"https://www.tutorialspoint.com/online_java_formatter.htm\" rel=\"noreferrer\">https://www.tutorialspoint.com/online_java_formatter.htm</a></p>\n<p>to make it more readable and follow standards.</p>\n<h2>Logic</h2>\n<pre><code>while (playAgain = true) {\n</code></pre>\n<p>This is wrong, it's supposed to be <code>==</code> , not <code>=</code> . It works anyway since what you do is just set the <code>playAgain</code> variable to <code>true</code> in the first run, which is the same value as it already has, and since during the <code>while</code> loop it checks the truth value of <code>playAgain</code>.</p>\n<p><code>while(playAgain)</code> is equivalent to <code>while(playAgain == true)</code></p>\n<h2>Comments</h2>\n<pre><code> } // end while \n} // end switch \n</code></pre>\n<p>These comments are in the wrong order. The <code>switch</code> is inside the <code>while</code> , so it ends first. But you should not need these comments at all. If you use a good code editor and proper indentation, you will easily see (and get auto-highlight) on which bracket matches which. I suggest using an editor such as IntelliJ or Visual studio code.</p>\n<h2>Logic 2</h2>\n<p>The win/lose/tie code is very long and messy.</p>\n<p>First, for ties you can just check</p>\n<pre><code>if (user == computer) {\n return "Tie";\n}\n</code></pre>\n<p>That covers all combinations that create a tie. With those cases out of the way, the remaining logic gets simpler.</p>\n<p>Since paper beats rock (1 beats 0) and scissors beats paper (2 beats 1), with your convenient number definitions you can then check <code>user == computer + 1</code>, but we also need the case for rock beats scissors.</p>\n<pre><code>if (user == computer + 1 || user == 0 && computer == 2) {\n return "Win";\n}\n</code></pre>\n<p>Since we have now covered all cases of Tie or Win, any other case will lose</p>\n<pre><code>else {\n return "Lose";\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T23:46:37.270",
"Id": "250135",
"ParentId": "250130",
"Score": "10"
}
},
{
"body": "<h2>Java naming convention</h2>\n<p>The method name should always start with a lower case.</p>\n<ul>\n<li><code>WelcomeP1</code> -> <code>welcomeP1</code></li>\n<li><code>P1Choice</code> -> <code>p1Choice</code></li>\n<li><code>ComputerChoice</code> -> <code>computerChoice</code></li>\n<li><code>Game</code> -> <code>game</code></li>\n</ul>\n<h2>Use <code>java.io.PrintStream#printf</code> instead of <code>java.io.PrintStream#println</code> when you have to concatenate</h2>\n<p><code>java.io.PrintStream#printf</code> offer you to use <a href=\"https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/Formatter.html\" rel=\"noreferrer\">patterns</a> to build the string without concatenating it manually. The only downside is you will be forced to add the break line character yourself; in java you can use the <code>%n</code> to break the line (portable between various platforms) or uses the traditional <code>\\n</code> / <code>\\r\\n</code>.</p>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>System.out.print("-------------> You " + game() + "!!!");\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>System.out.printf("-------------> You %s!!!", game());\n</code></pre>\n<hr />\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>System.out.println("The computer's choice was " + computerPiece + "...");\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>System.out.printf("The computer's choice was %s...%n", computerPiece); //With a new line\n</code></pre>\n<h2>Always use the primitives when possible</h2>\n<p>When you know that it's impossible to get a null value with the number, try to use the primitives; this can prevent the unboxing of the value in some case.</p>\n<p>In your code, you can replace the <code>Boolean</code> to <code>boolean</code> since you have only the <code>true</code> and <code>false</code> values.</p>\n<h2>Extract some of the logic to methods.</h2>\n<p>When you have logic that does the same thing, you can generally move it into a method and reuse it.</p>\n<p>You can extract some of the logic that asks if the user wants to play Rock, Paper or Scissors into a method and reuses it.</p>\n<pre class=\"lang-java prettyprint-override\"><code>private static String askIfWantToPlay(Scanner scanner) {\n String userPlay = "";\n while (userPlay.isEmpty()) {\n System.out.println("Do you want to play Rock, Paper, Scissors?");\n System.out.println("Please press y for (Y)es \\nor n for (N)o: ");\n userPlay = scanner.next().trim();\n }\n return userPlay;\n}\n</code></pre>\n<p>This method will remove some duplication.</p>\n<p>If you want to, you could centralize the logic of exiting in this new method; check if the user want to exit or not.</p>\n<pre class=\"lang-java prettyprint-override\"><code>private static void askIfWantToPlayAndExitOtherwise(Scanner scanner) {\n String userPlay = "";\n\n while (!"n".equalsIgnoreCase(userPlay) && !"y".equalsIgnoreCase(userPlay)) {\n System.out.println("Do you want to play Rock, Paper, Scissors?");\n System.out.println("Please press y for (Y)es \\nor n for (N)o: ");\n userPlay = scanner.next();\n }\n\n if ("y".equalsIgnoreCase(userPlay)) {\n System.exit(0);\n } else {\n System.out.println("*************************************");\n System.out.println("Excellent! Thank you...\\nLet's Play!");\n }\n}\n</code></pre>\n<p>With this method, the code is easier to read and don’t propagate logic everywhere in the application; you can do the same thing with the user choice for the (R)ock, (P)aper, or (S)cissors and return only a valid choice.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-04T00:45:59.683",
"Id": "250168",
"ParentId": "250130",
"Score": "8"
}
},
{
"body": "<p>I can agree with all of in two previous answers, however I have to address the issue of implementation of game logic itself. I just so happens that we understand the game logic of the game because we all know the game, but if we look at the code it is difficult to extract the game logic from the code. It is not written in clean, easy to understand way, especially with deep <code>if</code> statement nesting.</p>\n<pre><code>public static String Game(){\n int user = P1Choice();\n int computer = ComputerChoice();\n String error = "*** If you are reading this, there has been a"\n +" system error. Please restart the program. ***";\n \n // 0 = rock\n // 1 = paper\n // 2 = scissors\n if (user == 0) {\n if (computer != 1){\n if (computer != 0){\n return "Win";\n }\n return "Tie";\n }\n return "Lose";\n } // end first nested for loop logic\n if (user == 1){\n if (computer != 2){\n if (computer != 1) {\n return "Win";\n }\n return "Tie";\n }\n return "Lose"; \n } // end second nested for loop logic\n if (user == 2){\n if (computer != 0){\n if (computer != 2) {\n return "Win";\n }\n return "Tie";\n }\n return "Lose"; \n } // end third nested for loop logic\n return error; // null -- Needed to return something \n // -- better practice teacher?\n } // end class Game ~ End Calculate Game & Return \n } // end class RPS\n</code></pre>\n<p>I found a way to implement this game logic in more clear and easy to read and understand way.</p>\n<h3>Use enumerations</h3>\n<p>Enumerations can help greatly with code clarity</p>\n<pre><code>public enum PlayedMove\n{\n ROCK,\n PAPER,\n SCISSORS;\n}\n</code></pre>\n<p>They are self-explanatory</p>\n<pre><code>public enum Winer\n{\n DRAW,\n PLAYER,\n COMPUTER;\n}\n</code></pre>\n<h3>The new game logic</h3>\n<p>As if you are explaining it to a man and not a computer</p>\n<pre><code>public class GameLogic\n{\n public static Winer getWiner(PlayedMove player, PlayedMove computer)\n {\n if (player == computer)\n {\n return Winer.DRAW;\n }\n else if (isPlayerWiner(player, computer))\n {\n return Winer.PLAYER;\n }\n else\n {\n return Winer.COMPUTER;\n }\n }\n \n private static boolean isPlayerWiner(PlayedMove player, PlayedMove computer)\n {\n return ((player == PlayedMove.ROCK && computer == PlayedMove.SCISSORS)\n || (player == PlayedMove.SCISSORS && computer == PlayedMove.PAPER)\n || (player == PlayedMove.PAPER && computer == PlayedMove.ROCK));\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-06T11:45:50.193",
"Id": "250272",
"ParentId": "250130",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T21:00:21.787",
"Id": "250130",
"Score": "11",
"Tags": [
"java",
"rock-paper-scissors"
],
"Title": "Rock, Paper, Scissors Game - Basic Game Simulation"
}
|
250130
|
<p>I'm new to MVC and EF so this may be a really simple question, but what is the best way to prevent the user from trying to enter duplicate records?</p>
<p>I have a table called Category with two columns Id and <code>CategoryName</code> (Id is PK and I set the Index value to unique one <code>CategoryName</code>). What I want to do is prevent the user from entering the same categories.</p>
<p>My <code>CategoriesController</code> looks like:</p>
<pre><code> using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Library;
namespace Library.Controllers
{
public class CategoriesController : Controller
{
private LibraryDbEntities1 db = new LibraryDbEntities1();
// GET: Categories
public ActionResult Index()
{
return View(db.Category.ToList());
}
// GET: Categories/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Category category = db.Category.Find(id);
if (category == null)
{
return HttpNotFound();
}
return View(category);
}
// GET: Categories/Create
public ActionResult Create()
{
return View();
}
// POST: Categories/Create
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,CategoryName")] Category category)
{
if (ModelState.IsValid)
{
db.Category.Add(category);
db.SaveChanges();
return RedirectToAction("Index");
}
int temp = Convert.ToInt32(cmd.ExcecuteScalar().To)
return View(category);
}
// GET: Categories/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Category category = db.Category.Find(id);
if (category == null)
{
return HttpNotFound();
}
return View(category);
}
// POST: Categories/Edit/5
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,CategoryName")] Category category)
{
if (ModelState.IsValid)
{
db.Entry(category).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(category);
}
// GET: Categories/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Category category = db.Category.Find(id);
if (category == null)
{
return HttpNotFound();
}
return View(category);
}
// POST: Categories/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Category category = db.Category.Find(id);
db.Category.Remove(category);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
</code></pre>
<p>The index view looks like this:</p>
<pre><code> @model Library.Category
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Category</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Id, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Id, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Id, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.CategoryName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.CategoryName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.CategoryName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
</code></pre>
<p>MY question is: how can I prevent the user from entering the same category two times? For example, I create a category named "Action", but I don't want any other user to be able to create the same Category.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T21:28:48.200",
"Id": "250131",
"Score": "1",
"Tags": [
"c#",
".net",
"database",
"entity-framework"
],
"Title": "Preventing the user from entering the same categories"
}
|
250131
|
<h2>Security threats in mind:</h2>
<ul>
<li><p><strong>SQL Injections!!!</strong> --- Solutions: Prepared Statements (PDO) and including
<code>$bpdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);</code> in the
database connection</p>
</li>
<li><p><strong>XSS Attacks!!!</strong> --- Solutions: htmlspecialchars(), Content-Security
Policy (placed in htaccess).</p>
</li>
<li><p><strong>OS Command Attacks!!!</strong> --- Solutions: Striping whitespace.</p>
</li>
<li><p><strong>DOS Attacks!!!</strong> --- Solution: None implemented. I'm unsure if any additional precaution is necessary, since there are no login possibilities on my website.</p>
</li>
</ul>
<p>Is the following script sufficient enough to sanitize user input?</p>
<pre><code>//sanitize user input
$Tmessage = trim(preg_replace('/\s\s+/', ' ', htmlspecialchars($_POST["message"])));
$sanitizedMessage = filter_var($Tmessage, FILTER_SANITIZE_STRING);
//prepare info and submit into table
$stmnt = $pdo->prepare("INSERT INTO submissionsTable (message) VALUES (:message)");
$stmnt->execute(['message' => $sanitizedMessage]);
header("Location: success.html");
exit (0);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T06:18:08.213",
"Id": "490698",
"Score": "0",
"body": "You better read something about how htmlspecialchars helps mitigate XSS attacks. It seems you dont get it even after you've been told several times."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T06:25:06.310",
"Id": "490699",
"Score": "1",
"body": "In short. Validate your input and sanitize your output. If you sanitize input you are effectivelly forcing your way of correcting clients mistake where the client may prefer a different kind of correction. If input contains invalid charcters or so, just refuse to process the request and thus give the client the opportunity to choose their own way of correcting the input and retry."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T06:28:00.600",
"Id": "490701",
"Score": "0",
"body": "You should sanitize output So that if i inputted a HTML fragment. On output i will just see it as text that included HTML markup rather then embedding my HTML fragment message as part of your HTML page."
}
] |
[
{
"body": "<p>I am concerned that you are not digesting the advice given in previous reviews, because you are ONLY to call <code>htmlspecialchars()</code> just before you print to an html document (print to screen).</p>\n<p>Effectively, you only need to handle whitespace related characters. Since you seem to be concerned with handling multibyte characters, the <code>u</code>nicode flag should be used on your regex patterns. See this relevant SO page: <a href=\"https://stackoverflow.com/q/10066647/2943403\">Multibyte trim in PHP?</a></p>\n<pre><code>$stmt->execute([\n 'message' => filter_var(\n preg_replace(\n ['/^\\s+|\\s+$/u', '/\\s{2,}/u'],\n ['', ' '],\n $_POST["message"]\n ),\n FILTER_SANITIZE_STRING\n )\n]);\n</code></pre>\n<p>If you are using <code>FILTER_SANITIZE_STRING</code> to strip tags, please see some potentially buggy behavior in the comments at <a href=\"https://www.php.net/manual/en/filter.filters.sanitize.php\" rel=\"noreferrer\">https://www.php.net/manual/en/filter.filters.sanitize.php</a></p>\n<p>P.s. I'd probably not use a named parameter in the prepared statement; there is only one bound parameter so there is no chance of confusion.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T01:49:46.027",
"Id": "250137",
"ParentId": "250132",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "250137",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T21:36:18.800",
"Id": "250132",
"Score": "3",
"Tags": [
"php",
"html",
"security",
"pdo",
"sql-injection"
],
"Title": "Sanitizing user form input in php"
}
|
250132
|
<p>This class is designed to decide if a ticket is qualified or not. A qualified tickets is one that is open and not assigned or if a ticket is a work in progress and assigned it can be taken over. It also validates if a ticket has proper ticket form is CSXXXXXXX. Any and all advise/ideas are wanted and appreciated!</p>
<pre><code>class Ticket:
def CSCheck(serviceNow:object):
while True:
CSNumber = input("CS Number: ")
if CSNumber.startswitch("CS"):
if " " not in CSNumber:
if len(CSNumber) > 9 or len(CSNumber) < 9:
print("Ticket numbers are 9 characters long")
else:
return CSNumber
else:
print("Ticket cannot contain spaces")
else:
print("Ticket's must start with CS")
async def qualifyTicket(username:str,computerInfo:object):
available = await checkState(computerInfo)
assigned = await checkAssigned(username,computerInfo)
if available = "open" and assigned != "":
print("This ticket appears to be assigned by a supervisor")
elif available = "open" and assigned == "":
#Ask user if they would like to have this ticket
elif available = "in progress" and assigned == "":
# shouldn't happen later check last user to add notes
elif available = "in progress" and assigned != "":
while True:
takeover = input("{0} is working on this ticket, take it over (y/n)".format(assigned))
if takeover == "y":
# begin assigning process
elif takover == "n":
# later functionality to check another ticket
sys.exit(0)
async def checkState(computerInfo:object):
current_state = computerInfo["CS"].state
current_dispo = computerInfo["CS"].u_disposition
if current_dispo == "No Longer Required":
print("This ticket is no longer required")
return False
else:
if current_state == 1: #Open
return "open"
elif current_state == 2 or current_state == 11: #Work in Progress/On Hold
print("It appears this ticket is already being worked on.")
return "in Progress"
elif current_state == 3 or current_state == 7: #Closed/Cancelled
print("This ticket has been closed or cancelled.")
# later implement feature to check another ticket?
sys.exit(0)
async def checkAssigned(username:str,computerInfo:object):
technician = computerInfo["technician"].user_name
if computerInfo["CS"].assigned_to != None:
return technician
else:
return
async def userAccept(username:str, computerinfo:object):
accept = input("Do you accept this ticket (y/n): ")
while True:
if accept == "y":
await computerInfo["CS"].updateCS("assigned_to",username)
await computerInfo["assigned"].__init__(computerInfo["CS"].serviceNow,computerInfo["CS"].assigned_to)
await computerInfo["CS"].updateCS("u_wi_primary_tech",username)
await computerInfo["technician"].__init__(computerInfo["CS"].serviceNow,computerInfo["CS"].u_wi_primary_tech)
await computerInfo["CS"].updateCS("state",2)
await computerInfo["CS"].updateCS("u_substate", " ")
elif accept == "n":
# later implement feature to check another ticket?
</code></pre>
|
[] |
[
{
"body": "<p>Some comments:</p>\n<ol>\n<li><p>This is not really a class, but rather a namespace, and seemingly a pointless one, given Python code structure.</p>\n<p>None of your methods are instance methods, (non take or need the <code>self</code> parameter), nor does your class contain any data fields.</p>\n<p>It seems more like a collection of mostly unrelated utility functions, so there really is no advantage in grouping them under a class instead of under a file, which you can treat as a module.</p>\n</li>\n<li><p>The <code>CSCheck</code> function, which seems more suited to be called <code>getValidCS</code>, does not check the 'XXXXXXX' part of the ticket id.\nCan any character go there other than a space? Like letters, or things like @ $ # etc?</p>\n<p>I would recommend using a regular expression, as tight as possible, and reducing the number of individual checks.\nYou might not be able to tell the user precisely what part of his input is bad, but you will have proper control over the validity of the ticket identifier.</p>\n<p>This will also make your code shorter and more maintainable.</p>\n</li>\n<li><p>The <code>checkState</code> method seems to be particularly problematic because its behavior varies greatly:</p>\n<p>It can return a string, return boolean, or just end the program.\nWhile Python's dynamic typing allows this, it is not a very good practice, as return values of such functions are harder to handle, especially handle correctly.</p>\n<p>Also, it is not quite clear what purpose converting numeric status values to sting status values serves, if you are not going to use those strings in UI?<br />\nIt seems, from your code structure, it would be better to leave the status as numbers, as that will reduce risk of bugs due to typos.</p>\n<p>It would also be better to assigned them to named constants, both to make them more readable and help the interpreter catch some of the bugs.</p>\n<p>Though Python does not have true constants, the use of all upper case class members or global (file level) variables is commonly considered to define constants.</p>\n<p>The <code>math</code> module even violates this rule and uses lower case constants like <code>math.pi</code></p>\n</li>\n<li><p>Similar thing with <code>checkAssigned</code>:<br />\nIn one branch it returns no value, not even <code>None</code></p>\n<p>It also demonstrates a strange design feature of the <code>computerInfo</code> object:\nThere seems to be no connection between the actual <code>assigned_to</code> field and the field holding the name of the person the ticket is actually assigned to.</p>\n<p>I would consider reworking that to make this function obsolete.</p>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T16:31:50.797",
"Id": "490729",
"Score": "0",
"body": "I completely agree with your first point concerning vaudating the number (I found out I could use the re module). As for the namespace mention, how could I reformat this to match that idea (Sorry still very new to truly pythonic design)? After for the computerInfo object, it’s a stored dictionary of 5-6 objects, that’s why it has a lot of computerInfo[key].variable. I’ll probably post that as a rework question later. I really appreciate your help!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T16:08:28.733",
"Id": "250154",
"ParentId": "250136",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T01:00:28.620",
"Id": "250136",
"Score": "1",
"Tags": [
"python",
"python-3.x"
],
"Title": "class to qualify if a ticket is valid for selection"
}
|
250136
|
<h1>Introduction</h1>
<p>As a Python neophyte, I implemented the <a href="https://en.wikipedia.org/wiki/Hangman_(game)" rel="nofollow noreferrer">Hangman</a> game as a practice, which operates case-insensitively on the 26 English letters.</p>
<p>My biggest concern at the moment is my use of <code>bytearray</code> to store the word, but I might have made other beginner mistakes as well. I'd like to locate them and improve accordingly.</p>
<h1>Code</h1>
<pre><code>import itertools
class Hangman:
def __init__(self, target, guesses):
assert target.isascii() and target.isalpha()
self.target = bytearray(target.lower(), 'utf-8')
self.guesses = guesses
self.display = bytearray(itertools.repeat(ord('_'), len(target)))
def run(self):
while True:
print()
print()
print(''.join(chr(byte) for byte in self.display))
print()
print(f'Remaining guesses: {self.guesses}')
guess = input('Guess a letter: ')
if len(guess) != 1:
print('Invalid guess.')
continue
elif not guess.isascii() or not guess.isalpha():
print('Non-letter guessed.')
continue
guess = ord(guess)
if self.display.count(guess) != 0:
print('Already guessed this letter.')
continue
if self.target.count(guess) == 0:
self.guesses -= 1
else:
self.display = bytearray(
(
guess if target_c == guess else display_c
) for display_c, target_c in zip(self.display, self.target)
)
if self.display == self.target:
print()
print()
print(''.join(chr(byte) for byte in self.target))
print('You won.')
break
elif self.guesses == 0:
print()
print()
print(''.join(chr(byte) for byte in self.target))
print()
print('You lost.')
break
if __name__ == '__main__':
# Merriam-Webster Word of the Day: October 2, 2020
hangman = Hangman('pachyderm', 6)
hangman.run()
</code></pre>
<h1>Example session</h1>
<pre><code>$ python hangman.py
_________
Remaining guesses: 6
Guess a letter: a
_a_______
Remaining guesses: 6
Guess a letter: e
_a____e__
Remaining guesses: 6
Guess a letter: i
_a____e__
Remaining guesses: 5
Guess a letter: o
_a____e__
Remaining guesses: 4
Guess a letter: u
_a____e__
Remaining guesses: 3
Guess a letter: r
_a____er_
Remaining guesses: 3
Guess a letter: y
_a__y_er_
Remaining guesses: 3
Guess a letter: c
_ac_y_er_
Remaining guesses: 3
Guess a letter: h
_achy_er_
Remaining guesses: 3
Guess a letter: p
pachy_er_
Remaining guesses: 3
Guess a letter: d
pachyder_
Remaining guesses: 3
Guess a letter: m
pachyderm
You won.
</code></pre>
|
[] |
[
{
"body": "<h2>Use more functions</h2>\n<p>Currently, the entirety of your hangman game lies inside the <code>run()</code> call. You can split certain parts of it to their own functions, such as checking for win condition, asking for character input, displaying the current state etc.</p>\n<h2>Empty <code>print</code>s</h2>\n<p>Use <code>\\n</code> to get a new line in console, instead of putting in empty print statements.</p>\n<h2>Checking guessed character</h2>\n<p>For strings, you can just check if the character is in string or not, since you have no need for the count of repetitions itself.</p>\n<h2><code>ord</code>, <code>chr</code> and <code>bytearray</code></h2>\n<p>They are of no use. You do not need a bytearray of ordinals, simply splitting the word into a list would be enough (not really needed though).</p>\n<h2>Type hints</h2>\n<p>With newer python, type hinting feature has also become available. Use them to assist you with the type of values for the variables.</p>\n<hr />\n<p>So, your program could also be rewritten like:</p>\n<pre><code>class Hangman:\n def __init__(self, target: str, guesses: int):\n assert self.is_ascii_alphabetical(\n target\n ), "Provided secret word is not ascii alphabetical string."\n self.secret_word = target\n self.guesses = guesses\n self.guessed_word = ["_"] * len(target)\n self._finish = False\n\n def is_ascii_alphabetical(self, value: str) -> bool:\n return value.isascii() and value.isalpha()\n\n def display(self, real_word: bool = False):\n if not real_word:\n print(f"\\n\\n{''.join(self.guessed_word)}\\n")\n else:\n print(f"\\n\\n{self.secret_word}\\n")\n\n def read_character(self) -> str:\n while True:\n guess = input("Guess a letter: ")\n if len(guess) != 1:\n print("Invalid guess.")\n continue\n elif not self.is_ascii_alphabetical(guess):\n print("Non-letter guessed.")\n continue\n if self.is_guess_repeat(guess):\n print("Already guessed this letter.")\n continue\n return guess.lower()\n\n def update_guessed_word(self, character: str) -> None:\n self.guessed_word = [\n new if new == character else old\n for old, new in zip(self.guessed_word, self.secret_word)\n ]\n\n def is_guess_repeat(self, guess: str) -> bool:\n return guess in self.guessed_word\n\n def is_guess_valid(self, guess: str) -> bool:\n if guess not in self.secret_word:\n return False\n return True\n\n def is_game_over(self) -> bool:\n return self.guesses <= 0\n\n def is_game_won(self) -> bool:\n return "_" not in self.guessed_word\n\n def run(self):\n while not self._finish:\n self.display()\n print(f"Remaining guesses: {self.guesses}")\n guess = self.read_character()\n if self.is_guess_valid(guess):\n self.update_guessed_word(guess)\n else:\n self.guesses -= 1\n if self.is_game_won():\n self.display(True)\n print("You won.")\n self._finish = True\n elif self.is_game_over():\n self.display(True)\n print("You lost.")\n self._finish = True\n\n\nif __name__ == "__main__":\n # Merriam-Webster Word of the Day: October 2, 2020\n hangman = Hangman("pachyderm", 6)\n hangman.run()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-04T01:26:44.600",
"Id": "490769",
"Score": "0",
"body": "Thanks. I guess I am still not used to thinking in Python, since I must have subconsciously rejected using a list of strings as somehow inefficient."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T07:59:22.370",
"Id": "250140",
"ParentId": "250138",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "250140",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T01:51:10.650",
"Id": "250138",
"Score": "4",
"Tags": [
"python",
"beginner",
"game",
"hangman",
"byte"
],
"Title": "Command-line English Hangman game"
}
|
250138
|
<p>I am looking for the best way to save regular data from a series of sensors to a CSV file.
the program will be reading every sensor once a minute 24/7 and needs to report the results to a CSV file that can be accessed at anytime via ftp..
I also wish to create a new file each day.</p>
<p>Is it best to;</p>
<p>A: open the file at midnight, and keep it open for 24 hours as I append to it every minute, then close it at the end of the day?</p>
<p>B: open and close the file every hour, to save an updated copy to the hard disk? in case of a crash.</p>
<p>C: open and close it every minute, only long enough to add the new line of data?</p>
<p>or is there a better practice to consider.</p>
<p>my current code:</p>
<pre class="lang-py prettyprint-override"><code>def writeData:
today = date.today()
today = date.strftime("%b-%d-%Y")
fileName = "Sensor Log {}".format(today)
with open(fileName, mode='w') as logFile:
logFile = csv.writer(logFile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
time = datetime.now()
logFile.writerow(['Time','Date', 'Sensor01', 'Sensor02'])
logFile.writerow([time, date, sen01, sen02])
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T12:25:09.130",
"Id": "490719",
"Score": "2",
"body": "`def writeData:` that's not valid syntax."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T12:29:38.860",
"Id": "490720",
"Score": "1",
"body": "Unfortunately your question is currently off-topic. We only review [code that works as intended](//codereview.meta.stackexchange.com/a/3650). [Generic best practice questions](//codereview.meta.stackexchange.com/a/3652) cannot be reasonably answered. Once you [edit] your post to fix the issues we'll be happy to review your code."
}
] |
[
{
"body": "<p>I think the answer to your question will depend largely on the operating environment of your Python program.</p>\n<p>The actual language (Python) is not really relevant here, as it does nothing special in this regard.\nFile management is the responsibility of the OS, and Python, like most programming languages only provides an interface to the underlying OS APIs.</p>\n<p>Generally speaking, "once a minute" is long enough interval on any modern system, including SBCs like Raspbery Pi, to justify "open -> append -> close" method.</p>\n<p>This will ensure that:</p>\n<p>A) The file is always as up to date as possible and ready for download.<br />\nB) If there is a software crash, power loss, or other indecent, as little data as possible is lost.</p>\n<p>Also, one thing to note is that while on Linux based OS (or BSD based), a file can be simultaneously accessed for reading an writing by different processes, on Windows keeping the file open for writing may render it inaccessible for download over FTP.</p>\n<p>Of course, if your system has some particular constraints about storage, for example an extremely slow or extremely busy persistent storage, then reducing the number of access operations may be a good idea.</p>\n<p>Also, in the unlikely case appending data is problematic (like if you were writing to tape storage), waiting until the daily file is collected in RAM would be a requirement.</p>\n<p>All that said, your current code has some issues:</p>\n<p>First, you are using <code>strftime</code> incorrectly, it must be called on the actual object holding a specific date, not on the <code>date</code> class.<br />\nI also recommend avoiding spaces in file names as they can cause issues with some tools</p>\n<pre><code>fileName = "sensor_log_{}.csv".format(date.today().strftime("%b-%d-%Y"))\n</code></pre>\n<p>Second, your actual write code always clobbers the content of the file with a single line of actual data.</p>\n<p>You should write the column titles only once when creating a new file for the current day, and then use "append" mode each time you write a single sensor reading:</p>\n<pre><code>with open(fileName, mode='a', newline='') as logFile:\n logFile = csv.writer(logFile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)\n time = datetime.now()\n\n # you are missing code to crate date and time string:\n st_time = time.strftime("HH:mm")\n st_date = time.strftime("%b-%d-%Y")\n\n logFile.writerow([st_time, st_date, sen01, sen02])\n</code></pre>\n<p>Also, you may want to consider dropping the date column completely if you are going to have a new file for every day with the date already in its name.</p>\n<p>This will reduce file size.</p>\n<p>If you choose to keep it, for esthetics mostly, it is common to make the date column the first column, and then the time and everything else.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T13:38:05.610",
"Id": "490722",
"Score": "0",
"body": "Welcome to Code Review, and excellent answer. The question itself is off-topic because the code is incorrect and doesn't work. It will probably be closed and then only you, the person that asked the question and users that have more than 10,000 reputation will be able to see it so you won't get many reputation points. It is best not to answer off-topic questions. You can learn what makes a question off-topic in our [guidelines for asking](https://codereview.stackexchange.com/help/asking)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T11:45:53.623",
"Id": "250147",
"ParentId": "250139",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T07:45:50.103",
"Id": "250139",
"Score": "-2",
"Tags": [
"python",
"beginner",
"datetime",
"csv"
],
"Title": "what is the best practice concerning opening CSV files in python"
}
|
250139
|
<p>It's been a while since I did anything with JavaScript. I made a tile puzzle game to help me brush up. You can find it here: <a href="https://compucademy.net/tile-puzzle/" rel="nofollow noreferrer">https://compucademy.net/tile-puzzle/</a></p>
<p>I would like some feedback on my use of JS, HTML and CSS. Anything would be helpful - structure, best practices, overall approach, suggestions for improvement etc.</p>
<p>Any input much appreciated.</p>
<pre><code>document.addEventListener( 'DOMContentLoaded', () => {
const n = 16;
const initialTileArray = [];
for ( let i = 0; i < n; i++ ) {
initialTileArray.push( String( i + 1 ) );
}
const board = document.querySelector( '.game-board' );
const audio = document.getElementById( 'audio' );
const resetButton = document.getElementById( 'reset-btn' );
const scrambleButton = document.getElementById( 'scramble-btn' );
let selectedTiles = [];
let clickNumber = 0;
let scrambledTileValues = [];
resetButton.addEventListener( 'click', resetGame );
scrambleButton.addEventListener( 'click', scrambleTiles );
function resetGame() {
board.innerHTML = '';
scrambledTileValues = initialTileArray.slice( 0 );
createBoard();
}
function scrambleTiles() {
board.innerHTML = '';
scrambledTileValues.sort( () => 0.5 - Math.random() );
createBoard();
}
function createBoard() {
for ( let i = 0; i < scrambledTileValues.length; i++ ) {
const tile = document.createElement( 'div' );
tile.setAttribute( 'data-pos', i + 1 );
tile.classList.add( 'game-tile', 'game-blue', 'text-center' );
tile.addEventListener( 'click', processTile );
board.appendChild( tile );
tile.innerHTML = scrambledTileValues[i];
}
}
function checkWin() {
const tiles = board.childNodes;
const config = [];
for ( var i = 0; i < tiles.length; i++ ) {
config.push( tiles[i].innerHTML );
}
return JSON.stringify( config ) === JSON.stringify( initialTileArray );
}
function playSuccessSound() {
audio.play();
}
function processTile() {
const tilePos = this.getAttribute( 'data-pas' );
if ( clickNumber === 0 || clickNumber === 1 ) {
this.classList.remove( 'game-blue' );
this.classList.add( 'game-red' );
selectedTiles.push( this );
clickNumber += 1;
} else if ( clickNumber === 2 ) {
selectedTiles.push( this );
for ( var i = 0; i < selectedTiles.length; i++ ) {
selectedTiles[i].classList.remove( 'game-red' );
selectedTiles[i].classList.add( 'game-blue' );
}
window.console.log( this.getAttribute( 'data-pos' ) );
const val0 = selectedTiles[0].innerHTML;
const val1 = selectedTiles[1].innerHTML;
const val2 = selectedTiles[2].innerHTML;
selectedTiles[0].innerHTML = val2;
selectedTiles[1].innerHTML = val0;
selectedTiles[2].innerHTML = val1;
selectedTiles = [];
clickNumber = 0;
if ( checkWin() ) {
playSuccessSound();
}
}
}
resetGame();
} );
</code></pre>
<pre><code>
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="css/style.css"/>
<title>Tile Puzzle 3 | 3-Cycles</title>
</head>
<body>
<div class="container">
<div class="row mb-3 justify-content-center">
<h1>Tile Puzzle 3 | 3-Cycles</h1>
</div>
<div class="row mb-3 justify-content-center">
<p>Click 3 tiles to cycles their positions and solve the puzzle</p>
</div>
<div class="row justify-content-center">
<div class="col-">
<div class="game-board d-flex flex-wrap"></div>
</div>
</div>
<div class="row justify-content-center">
<button id="reset-btn" type="button" class="mt-3 game-btn">Reset</button>
&nbsp;
<button id="scramble-btn" type="button" class="mt-3 game-btn">Scramble</button>
</div>
</div>
<audio id="audio" src="assets/Success-sound-effect.mp3"></audio>
<script src="scripts/puzzle3.js"></script>
</body>
</html>
</code></pre>
<pre><code>body {
font-family: monospace, monospace;
}
.game-board {
width: 408px;
flex-wrap: wrap;
}
.game-tile {
font-family: monospace, monospace;
font-size: 50px;
color: white;
width:100px;
border: 1px solid white;
}
.game-btn {
font-family: monospace, monospace;
color: white;
font-size: 36px;
border: none;
padding: 0 5px;
background: green;
}
.game-btn:focus {
outline: none;
}
.game-blue {
background: blue;
}
.game-red {
background: red;
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T18:43:28.630",
"Id": "490736",
"Score": "0",
"body": "How about starting with a scrambled board?\nExplaining what the cycle does (moves last clicked to first clicked position, etc.)?\nA trial counter?\nCongratulating player when solved?\nFuture:\nScoreboard?\nCompetition against others?\nLeagues?\nPrizes?\n:)"
}
] |
[
{
"body": "<p><strong>Stray <code>console</code></strong> You have <code>window.console.log( this.getAttribute( 'data-pos' ) );</code>. They're useful for debugging, but remember to remove logs for production. Consider <a href=\"https://eslint.org/docs/rules/no-console\" rel=\"nofollow noreferrer\"><code>no-console</code></a>.</p>\n<p><strong>n</strong> A variable named <code>n</code> is not all that informative. How about calling it <code>totalNumberOfTiles</code> instead? Also, rather than</p>\n<pre><code>for ( let i = 0; i < n; i++ ) {\ninitialTileArray.push( String( i + 1 ) );\n}\n</code></pre>\n<p>You can start at 1 instead of 0 to make the logic a bit easier:</p>\n<pre><code>for ( let i = 1; i <= totalNumberOfTiles; i++ ) {\n initialTileArray.push( String( i ) );\n}\n</code></pre>\n<p><strong>Indentation</strong> A number of places in your code aren't properly indented, making it slightly harder to read than would be ideal. Consider an IDE which can indent automatically, like VSCode - that way the code can be made to look pretty without any manual effort at all on your part.</p>\n<p><strong>DOMContentLoaded?</strong> Keeping code free of unnecessary indentation can make it more readable - or, at least, some prefer it that way. If you feel the same, you can remove the <code>DOMContentLoaded</code> listener entirely - the <code><script></code> is at the bottom of the body already, so all elements will surely exist by then. You can also put the script in the <code><head></code> and do the same thing - all you need to do is give the script the <code>defer</code> attribute.</p>\n<p><strong>Biased sorting</strong> You use <code>scrambledTileValues.sort(() => 0.5 - Math.random());</code>. This is a biased algorithm. For a long article on this, see <a href=\"http://www.robweir.com/blog/2010/02/microsoft-random-browser-ballot.html\" rel=\"nofollow noreferrer\">here</a>; the results will not be altogether random. To sort, use a <a href=\"https://stackoverflow.com/q/2450954\">different method</a>.</p>\n<p><strong>processTile bug</strong> The same tile can be selected more than once. For example, click 1, 1, then 2. The result is the 2 disappearing entirely; there are now two 1s on the board. Change <code>processTile</code> so that, if the clicked element is in <code>selectedTiles</code> already, do nothing. (Or deselect it, decrement <code>clickNumber</code>, and remove it from the array)</p>\n<p><strong>Pointer?</strong> Tiles are clickable. You might make this clearer by giving them <code>cursor: pointer</code>.</p>\n<p><strong>Color toggling</strong> Rather than having one class for blue and another for red, consider having just a base color (blue) with one class that gets toggled (red when on):</p>\n<pre><code>.game-tile {\n background: blue;\n}\n.selected {\n background: red;\n}\n</code></pre>\n<p>That way, in the JS, you only have one class to toggle, not two.</p>\n<p><strong>Avoid <code>var</code></strong> You're using ES6, which is great. In ES6, there's no reason to use <code>var</code> - use <code>const</code> instead (or <code>let</code> when you must reassign). Consider a linter which will prompt you to <a href=\"https://eslint.org/docs/rules/no-var\" rel=\"nofollow noreferrer\">automatically fix</a> it.</p>\n<p>Or, even better, instead of iterating manually and messing with indicies, invoke the collection's iterator instead:</p>\n<pre><code>for ( var i = 0; i < tiles.length; i++ ) {\n config.push( tiles[i].innerHTML );\n}\n</code></pre>\n<p>can be rewritten as</p>\n<pre><code>for (const tile of tiles) {\n config.push( tile.textContent );\n}\n</code></pre>\n<p>Which leads to the next point:</p>\n<p><strong>Avoid <code>innerHTML</code></strong> - unless you're <em>deliberately inserting</em> or retrieving HTML markup, it's faster, safer, and more semantically appropriate to use <code>textContent</code> instead.</p>\n<p><strong>Typo</strong> You refer to <code>data-pos</code> twice, and <code>data-pas</code> once. You probably wanted <code>pos</code>.</p>\n<p>Also, for data attributes, rather than <code>getAttribute</code>, it can be nicer to use the <code>dataset</code> property instead: replace</p>\n<pre><code>const tilePos = this.getAttribute( 'data-pas' );\n</code></pre>\n<p>with</p>\n<pre><code>const tilePos = this.dataset.pos;\n</code></pre>\n<p>(or you could remove it entirely, since it isn't used anywhere else)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-05T19:57:37.440",
"Id": "490958",
"Score": "0",
"body": "Awesome, thank you. That was exactly the kind of feedback I was looking for. I've implemented all of that now and will remember the points in future."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-05T00:02:44.667",
"Id": "250206",
"ParentId": "250141",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "250206",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T08:23:33.567",
"Id": "250141",
"Score": "3",
"Tags": [
"javascript",
"game",
"html5"
],
"Title": "HTML5 Tile Cycle Puzzle"
}
|
250141
|
<p>The state machine has the below specifications</p>
<pre><code> (defparameter *test-machine*
(make-fsm
:alphabet '(a b)
:table '((2 1) (0 2) (1 0))
:initial 0
:accepting '(2)))
</code></pre>
<p>The FSM in the function is:</p>
<pre><code> [1]> (fsm-alphabet *test-machine*)
(A B)
[2]> (fsm-initial *test-machine*)
0
[3]> (fsm-accepting *test-machine*)
(1)
</code></pre>
<p>The transition of the function is - the element of the alphabet of fsm
the state index of the function is the index of the current state in the list of states</p>
<p>below is the function output</p>
<pre><code> [3]> (transition-function *test-machine* 0 'a)
2
[4]> (transition-function *test-machine* 0 'b)
1
[5]> (transition-function *test-machine* 2 'b)
0
</code></pre>
<p>the built-in function position will return the index of an element in a list if that element exists.
For example, (position '3 '(1 2 0 2 3 5 6)) will return 4.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-20T17:11:41.930",
"Id": "497339",
"Score": "1",
"body": "do you still need help with this question?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T10:03:41.720",
"Id": "250145",
"Score": "2",
"Tags": [
"lisp",
"state-machine"
],
"Title": "define a lisp function, that takes fsm , a transition and state-index and return the state obtained by the transition from the state"
}
|
250145
|
<p>I added type definitions to a simple <a href="https://github.com/MauricioRobayo/twitterize" rel="nofollow noreferrer">npm package</a>. I would love to get some feedback on ways to do better for the type definitions.</p>
<p>The package exports a single function which returns a function that returns a promise:</p>
<pre class="lang-js prettyprint-override"><code>function request(httpsOptions, body) {
return new Promise((resolve, reject) => {
const req = https.request(httpsOptions, (res) => {
let data = ''
res.on('data', (_data) => {
data += _data
})
res.on('end', () => {
resolve(JSON.parse(data))
})
})
req.on('error', (error) => {
reject(error)
})
req.write(body)
req.end()
})
}
module.exports = (oAuthOptions) => ({
subdomain = 'api',
endpoint,
requestMethod = 'GET',
queryParams = {},
bodyParams = {},
}) => {
const baseUrl = buildBaseUrl(subdomain, endpoint)
const body = buildBody(bodyParams)
const url = buildUrl(baseUrl, queryParams)
const httpsOptions = buildHttpsOptions(url, {
requestMethod,
body,
baseUrl,
queryParams,
bodyParams,
oAuthOptions,
})
return request(httpsOptions, body)
}
</code></pre>
<p>This is the type definition file that I created:</p>
<pre class="lang-js prettyprint-override"><code>export type OAuthOptions = {
api_key: string
api_secret_key: string
access_token: string
access_token_secret: string
}
export type RequestOptions = {
subdomain?: string
endpoint: string
requestMethod?: string
queryParams?: Record<string, string>
bodyParams?: Record<string, string>
}
export default function (
oAuthOptions: OAuthOptions,
): <T>(requestOptions: RequestOptions) => Promise<T>
</code></pre>
<p>Any advise on how to do better with the type definitions is highly appreciated.</p>
|
[] |
[
{
"body": "<p><strong>Narrow the <code>requestMethod</code></strong> Its type should be narrower. There are only a <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods\" rel=\"nofollow noreferrer\">small number</a> of possible methods. Instead of <code>string</code>, you should permit only those which make sense. You probably want something like:</p>\n<pre><code>requestMethod?: 'GET' | 'POST' | 'PUT' | 'DELETE' // etc\n</code></pre>\n<p>This will both reduce typos (eg, prevent someone from accidentally using <code>'PUST'</code>) and make it clear that the method should not just be any string, but one of a few particular strings.</p>\n<p><strong>String params?</strong> You have</p>\n<pre><code>queryParams?: Record<string, string>\nbodyParams?: Record<string, string>\n</code></pre>\n<p>But, do both parameters really have to be only string keys with string values? That doesn't sound right. For example, I would hope and expect to be able to do:</p>\n<pre><code>queryParams: { 1: 'foo' } // turns into `1=foo`\n</code></pre>\n<p>or</p>\n<pre><code>queryParams: { foo: 1 } // turns info `foo=1`\n</code></pre>\n<p>or maybe even</p>\n<pre><code>queryParams: { foo: false } // turns info `foo=false`\n</code></pre>\n<p>If the library can handle those sorts of inputs and serialize them properly, which I'd hope it could, the type definitions should reflect that.</p>\n<hr />\n<p>The JS can be improved a bit too:</p>\n<p><strong>Callbacks</strong> You can pass the <code>reject</code> callback alone to <code>.on('error'</code>:</p>\n<pre><code>req.on('error', (error) => {\n reject(error)\n})\n</code></pre>\n<p>can be</p>\n<pre><code>req.on('error', reject)\n</code></pre>\n<p><strong>JSON parsing and errors</strong></p>\n<pre><code>res.on('end', () => {\n resolve(JSON.parse(data))\n})\n</code></pre>\n<p>What if <code>data</code> happens not to be JSON-parseable? Then an error will be thrown, but the Promise will <em>not</em> reject - it'll remain pending forever. Better to enclose that in a <code>try</code>/<code>catch</code>, and call <code>reject</code> if parsing fails.</p>\n<p><strong>Narrower response type?</strong> You currently have:</p>\n<pre><code>export default function (\n oAuthOptions: OAuthOptions,\n): <T>(requestOptions: RequestOptions) => Promise<T>\n</code></pre>\n<p>without any constraint on <code>T</code>. You might consider explicitly requiring T to be a plain value when deserialized - that is, you wouldn't want people to be able to pass in a function type, or an object type where the object contains non-primitives (other than other plain objects and plain arrays). Maybe use something like <code>AsJson</code> in <a href=\"https://stackoverflow.com/a/57859435\">jcalz's answer here</a>.</p>\n<pre><code>type AsJson<T> = \n T extends string | number | boolean | null ? T : \n T extends Function ? never : \n T extends object ? { [K in keyof T]: AsJson<T[K]> } : \n never;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-05T11:44:26.533",
"Id": "490889",
"Score": "0",
"body": "This is a great code review, really grateful you took the time to provide this feedback."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-04T19:53:51.687",
"Id": "250198",
"ParentId": "250148",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "250198",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T12:04:47.490",
"Id": "250148",
"Score": "2",
"Tags": [
"javascript",
"typescript",
"type-safety"
],
"Title": "Type definitions for simple NPM package that generates OAuth 1.0a authorization header for Twitter API using native https nodejs module"
}
|
250148
|
<p>I had created hash function library (<code>MD5</code>, <code>MD4</code>, <code>SHA256</code>, <code>SHA384</code>, <code>SHA512</code>, <code>RipeMD128</code>, <code>RipeMD160</code>, <code>CRC16</code>, <code>CRC32</code>, <code>CRC64</code>), written in C++.</p>
<p>Everything working well and My library produces exactly the same output compared to the PHP output. (Except for CRC series)</p>
<p>The individual algorithmic abstraction layers consist of the chash::IAlgorithm interface and chash::IDigest. But I'd like to refine IDigest more elegantly. How can I do it?</p>
<p><a href="https://github.com/whoamiho1006/chash" rel="nofollow noreferrer">https://github.com/whoamiho1006/chash</a></p>
<p><strong>IAlgorithm.hpp</strong></p>
<pre><code>#pragma once
#include "Macros.hpp"
namespace chash {
enum class EAlgorithm {
Unknown = 0x0000,
CRC16 = 0x1000, // --> IBM Poly-Nomial.
CRC32 = 0x1001, // --> IEEE 802.3
CRC64 = 0x1002, // --> ISO Poly-Nomial.
SHA256 = 0x2000,
SHA384 = 0x2001,
SHA512 = 0x2002,
MD5 = 0x3000,
MD4 = 0x3001,
RipeMD128 = 0x4000,
RipeMD160 = 0x4001,
};
enum class EAlgorithmErrno {
Succeed = 0,
InvalidState,
InvalidDigest
};
class IDigest;
class IAlgorithm {
public:
IAlgorithm(EAlgorithm type)
: _type(type), _errno(EAlgorithmErrno::Succeed)
{
}
virtual ~IAlgorithm() { }
private:
EAlgorithm _type;
EAlgorithmErrno _errno;
protected:
inline void setError(EAlgorithmErrno _errno) {
this->_errno = _errno;
}
public:
/* get algorithm type. */
inline EAlgorithm type() const { return _type; }
/* get algorithm state. */
inline EAlgorithmErrno error() const { return _errno; }
/* create a new digest. */
virtual IDigest* create() const = 0;
/* initiate the algorithm. */
virtual bool init() = 0;
/* update the algorithm state by given bytes. */
virtual bool update(const uint8_t* inBytes, size_t inSize) = 0;
/* finalize the algorithm. */
virtual bool finalize(IDigest* outDigest) = 0;
/* compute hash with digest. */
virtual EAlgorithmErrno compute(IDigest* outDigest, const uint8_t* inBytes, size_t inSize) {
if (init()) {
update(inBytes, inSize);
finalize(outDigest);
return error();
}
return error();
}
};
}
</code></pre>
<p><strong>IDigest.hpp</strong></p>
<pre><code>#pragma once
#include "Macros.hpp"
#include <string>
namespace chash {
class IDigest {
public:
virtual ~IDigest() { }
public:
/* get bytes pointer. */
virtual uint8_t* bytes() const = 0;
/* get size in bytes. */
virtual size_t size() const = 0;
public:
inline std::string toHex() {
std::string outHex;
uint8_t* bytes = this->bytes();
size_t size = this->size();
outHex.reserve(size << 1);
for (size_t i = 0; i < size; ++i) {
int32_t b = bytes[i];
int32_t fr = b / 16;
int32_t bk = b % 16;
if (fr < 10) outHex.push_back('0' + fr);
else outHex.push_back('a' + (fr - 10));
if (bk < 10) outHex.push_back('0' + bk);
else outHex.push_back('a' + (bk - 10));
}
return outHex;
}
};
/* Digest in template. */
template<size_t Size>
class TDigest : public IDigest {
public:
TDigest() {
for (size_t i = 0; i < Size; ++i)
_bytes[i] = 0;
}
private:
mutable uint8_t _bytes[Size];
public:
/* get bytes pointer. */
virtual uint8_t* bytes() const { return _bytes; }
/* get size in bytes. */
virtual size_t size() const { return Size; }
};
}
</code></pre>
<p>I have a <a href="https://codereview.stackexchange.com/questions/250172/simple-c-hash-library-and-its-abstraction-design-that-seems-out-of-focus">follow up questions</a> based on the answer by G. Sliepen.</p>
|
[] |
[
{
"body": "<h1>Use the standard library</h1>\n<blockquote>\n<p>But I'd like to refine IDigest more elegantly. How can I do it?</p>\n</blockquote>\n<p>Your <code>IDigest</code> basically reimplements <code>std::vector<uint8_t></code>. Realizing this, I would therefore remove it entirely and replace it with <code>std::vector<uint8_t></code>. You could add this to namespace <code>chash</code> if you like:</p>\n<pre><code>using Digest = std::vector<uint8_t>;\n</code></pre>\n<p>Your <code>IDigest</code> has limitations: you cannot compare two digests with each other. But you can with <code>std::vector<uint8_t></code>. The only feature your class has is that it has a function to convert it to a string containing hexadecimal characters. I would leave that out entirely, and leave it up to the application to implement whatever they need to convert a digest to some other form, if they need that at all. But if you do want to provide this as a utility, simply create an out-of-class function to do this:</p>\n<pre><code>std::string toHex(const Digest &digest) {\n std::string outHex;\n outHex.reserve(digest.size() * 2);\n\n for (auto b: digest) {\n ...\n }\n\n return outHex;\n}\n</code></pre>\n<h1>Consider whether you need virtual base classes</h1>\n<p>Do you really need virtual base classes? These come with a cost: derived classes will now have a vtable, and function calls need to go through an extra level of indirection. Consider using a non-virtual base class, and make the base class's constructor <code>protected</code>, so you can no longer create an instance of a base class.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-04T03:56:53.190",
"Id": "490774",
"Score": "1",
"body": "Thank you so much!, I had modified implementation. can you review again?? https://codereview.stackexchange.com/questions/250172/simple-c-hash-library-and-its-abstraction-design-that-seems-out-of-focus"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T15:35:40.933",
"Id": "250152",
"ParentId": "250149",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "250152",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-03T12:23:01.913",
"Id": "250149",
"Score": "3",
"Tags": [
"c++",
"security"
],
"Title": "Simple C++ Hash function library"
}
|
250149
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.